# file: agent_system/main_real_data.py import numpy as np import pandas as pd import matplotlib.pyplot as plt # Internal Imports from core import Portfolio from factory import generate_synthetic_forces from brain import MPCBoltzmannBrain from execution import MPCExecutor from perception_tuned import RegimeClassifierTuned # From previous step from data_loader import DataLoader # NEW! def run_real_backtest(): # --- 1. LOAD REAL DATA --- loader = DataLoader() # Let's test the transition from 2021 Euphoria to 2022 Crash df = loader.fetch_data(ticker="BTC-USD", start="2010-01-01", end="2026-01-01") dates = df.index prices = df['close'].values days = len(prices) # --- 2. INITIALIZATION --- portfolio = Portfolio(cash=100000.0) # Start with $100k forces = generate_synthetic_forces(10) # Brain: Balanced exploration (T=0.5) brain = MPCBoltzmannBrain(temperature=0.5) # Executor: 0.2% Fee, requires 0.1% gain to trade executor = MPCExecutor(fee_rate=0.002, min_gain_threshold=0.01) # Perception: Lookback windows for trend/volatility classifier = RegimeClassifierTuned(fast_window=10, slow_window=50, vol_window=14) history = [] regime_log = [] print(f"🚀 Starting Real-World Backtest ({days} days)...") # --- 3. THE TIME LOOP --- for t in range(days): current_price = prices[t] current_date = dates[t] # A. BUILD CONTEXT (Perception) # We need to slice the dataframe up to time 't' for the classifier # (Simulating "Real-time" knowledge) if t < 50: # Not enough data for long_window (50), assume neutral or skip ctx_tags = {"calculating"} else: historical_slice = df.iloc[:t+1] # Data from start up to today ctx_tags = classifier.get_current_regime(historical_slice) regime_log.append(list(ctx_tags)) # B. UPDATE MARKET market_prices = {"BTC": current_price, "USDT": 1.0} portfolio.update(market_prices) # C. AGENT LOGIC if "calculating" not in ctx_tags: energies = brain.calculate_energies(forces, ctx_tags) target_weights = brain.get_weights(energies) executor.rebalance(portfolio, forces, target_weights, market_prices) # D. LOGGING history.append(portfolio.total_value) if t % 50 == 0: print(f"📅 {current_date.date()} | ${current_price:,.0f} | {ctx_tags} | Eq: ${portfolio.total_value:,.0f}") return history, prices, regime_log, dates if __name__ == "__main__": equity, btc_prices, regimes, date_index = run_real_backtest() # --- VISUALIZATION --- fig, ax1 = plt.subplots(figsize=(14, 7)) # Plot Equity (Blue) color = 'tab:blue' ax1.set_xlabel('Date') ax1.set_ylabel('Portfolio Equity ($)', color=color) ax1.plot(date_index, equity, color=color, label="Agent Equity") ax1.tick_params(axis='y', labelcolor=color) # Plot BTC Buy & Hold Reference (Gray, Dashed) ax2 = ax1.twinx() color = 'tab:gray' ax2.set_ylabel('BTC Price ($)', color=color) ax2.plot(date_index, btc_prices, color=color, linestyle='--', alpha=0.5, label="BTC Price") ax2.tick_params(axis='y', labelcolor=color) plt.title("Real-World Test: MPC Agent vs. 2022 Crash") fig.tight_layout() plt.show()