agent_system / simulator.py
janggi3's picture
Upload folder using huggingface_hub
d96a847 verified
Raw History Blame Contribute Delete
3.1 kB
# file: agent_system/simulator.py
import numpy as np
import pandas as pd
class BacktestSimulator:
def __init__(self, initial_capital=100000):
self.initial_capital = initial_capital
def run(self, agent, market_data, forces):
"""
:param market_data: A dict containing 'prices' and 'regime_tags' for 365 days.
"""
portfolio_history = []
current_equity = self.initial_capital
print(f"STARTING BACKTEST: {agent.__class__.__name__}")
for t in range(len(market_data['prices'])):
# 1. Update Environment
prices = market_data['prices'][t]
regime = market_data['regime_tags'][t]
# 2. Agent Observes and Acts
# In a multi-step agent, the agent sees 'regime' and projects the horizon
agent.step(prices, regime, forces)
# 3. Record State
current_equity = agent.portfolio.total_value
portfolio_history.append(current_equity)
return pd.Series(portfolio_history)
def generate_backtest_market(seed=42):
np.random.seed(seed)
days = 365
# Storage
prices_history = []
regime_history = []
# Initial State
btc_price = 50000.0
eth_price = 3000.0
for t in range(days):
# --- SEASONAL REGIME LOGIC ---
if t < 100:
# PHASE 1: The "Grind Up" (Bull Market)
# Low volatility, steady growth
regime = {"bull_trend", "low_vol", "momentum"}
btc_drift, btc_vol = 0.001, 0.01
eth_drift, eth_vol = 0.0015, 0.015
elif 100 <= t < 160:
# PHASE 2: The "Flash Crash & Panic" (Bear Market)
# High volatility, sharp decline
regime = {"bear_trend", "high_vol", "aggressive_risk"}
btc_drift, btc_vol = -0.004, 0.04
eth_drift, eth_vol = -0.006, 0.05
else:
# PHASE 3: The "Sideways Chop" (Mean Reversion)
# No trend, random noise, medium volatility
regime = {"chop", "mid_vol", "mean_reversion"}
btc_drift, btc_vol = 0.0, 0.015
eth_drift, eth_vol = 0.0, 0.02
# --- PRICE EVOLUTION (Geometric Brownian Motion) ---
btc_price *= (1 + np.random.normal(btc_drift, btc_vol))
eth_price *= (1 + np.random.normal(eth_drift, eth_vol))
prices_history.append({
"BTC": round(btc_price, 2),
"ETH": round(eth_price, 2),
"USDT": 1.0
})
regime_history.append(regime)
return {
"prices": prices_history,
"regimes": regime_history,
"timeline": pd.date_range(start="2025-01-01", periods=days)
}
# Generate the data
market_data = generate_backtest_market()