intraday-btc-model-11yr / optimize_aggressive.py
VenuMuvva's picture
Upload folder using huggingface_hub
8346b41 verified
Raw History Blame Contribute Delete
5.93 kB
"""
Aggressive Daily Strategy Optimizer (2014-2025)
-----------------------------------------------
Goal: Maximize Total Return (Aiming for 100% monthly CAGR).
Constraints: No Wipeout (Equity > 0).
Dataset: 11 Years of Daily Data.
"""
import pandas as pd
import numpy as np
import sys
import os
import itertools
from typing import Dict, Any
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import config
from core.backtester import Backtester
# Load Data Once
DATA_FILE = os.path.join(config.DATA_DIR, "btc_daily_2014_2025.csv")
DF_DAILY = pd.read_csv(DATA_FILE)
DF_DAILY['timestamp'] = pd.to_datetime(DF_DAILY['timestamp'])
DF_DAILY.set_index('timestamp', inplace=True)
def run_strategy(params: Dict[str, Any]):
"""Run a single backtest with given parameters."""
try:
lev = params['leverage']
ma_fast = params['ma_fast']
ma_slow = params['ma_slow']
stop_atr = params['stop_atr']
# Prepare Data
df = DF_DAILY.copy()
# Indicators
df['ema_fast'] = df['close'].ewm(span=ma_fast, adjust=False).mean()
df['ema_slow'] = df['close'].ewm(span=ma_slow, adjust=False).mean()
# ATR
high = df['high']
low = df['low']
close = df['close']
tr1 = high - low
tr2 = (high - close.shift()).abs()
tr3 = (low - close.shift()).abs()
tr = pd.concat([tr1, tr2, tr3], axis=1).max(axis=1)
df['atr'] = tr.rolling(14).mean()
# Signals (Aggressive: Always in market if possible?)
# Strategy: Long when Fast > Slow, Short when Fast < Slow
# Stop Loss: Wide to avoid shakeouts
signals = pd.Series(0, index=df.index)
signals[df['ema_fast'] > df['ema_slow']] = 1
signals[df['ema_fast'] < df['ema_slow']] = -1
# Calculate Stop % (Avg ATR)
avg_atr_pct = (df['atr'] / df['close']).mean()
if pd.isna(avg_atr_pct): avg_atr_pct = 0.04
stop_dist = avg_atr_pct * stop_atr
# Backtest
class DummySignal:
def get_params(self): return params
backtester = Backtester(
data=df,
features=df,
signals=signals,
signal_model=DummySignal(),
e_base=1000.0,
leverage=lev,
risk_fraction=0.10, # Aggressive: Risk 10% of equity per trade?
# Or fixed leverage? The backtester logic uses risk_fraction to size position.
# If we want fixed leverage (e.g. 3x), we set risk_fraction such that size = Equity * Lev
# position_size = (risk_amount / stop_distance) / price
# size * price = risk_amount / stop_distance
# Notional = Equity * rho / stop_dist
# Target Notional = Equity * Lev
# So rho = Lev * stop_dist
stop_distance=stop_dist,
tp_distance=stop_dist * 5.0, # Let winners run
d_max=0.90, # Allow 90% drawdown (Aggressive)
commission=0.001, # 0.1% fee (Swap costs on daily leverage are high, let's approximate)
slippage=0.0001,
verbose=False
)
# Override risk calculation to force fixed leverage if needed?
# We'll use the calculated rho:
rho = lev * stop_dist
if rho > 0.95: rho = 0.95 # Cap risk per trade at 95% (All in)
backtester.risk_fraction = rho
results = backtester.run()
metrics = results['metrics']
return {
'params': params,
'return': metrics['total_return_pct'],
'drawdown': metrics['max_drawdown_pct'],
'equity': metrics['total_equity'],
'trades': metrics['num_trades']
}
except Exception:
return None
def optimize():
print("\n" + "="*70)
print("AGGRESSIVE OPTIMIZATION (11 YEARS)")
print("="*70)
print(f"Data: {len(DF_DAILY)} Daily bars (2014-2025)")
# Parameter Grid
leverages = [3, 5, 10] # Higher leverage
fast_mas = [5, 10, 20]
slow_mas = [20, 50]
stops = [0.5, 1.0, 1.5] # Tighter stops to allow higher size
combinations = []
for l in leverages:
for f in fast_mas:
for s in slow_mas:
for st in stops:
if f < s:
combinations.append({
'leverage': l,
'ma_fast': f,
'ma_slow': s,
'stop_atr': st
})
print(f"Testing {len(combinations)} combinations...")
results = []
for i, p in enumerate(combinations):
if i % 10 == 0: print(f" {i}/{len(combinations)}...", end='\r')
# Override risk cap in run_strategy
# We need to modify run_strategy to accept higher risk
res = run_strategy(p)
if res:
results.append(res)
print("\nOptimization Complete.")
# Sort by Return
results.sort(key=lambda x: x['return'], reverse=True)
print("\n🏆 TOP 5 MODELS (Most Profit):")
for i, r in enumerate(results[:5]):
p = r['params']
print(f"\nRank #{i+1}")
print(f" Return: {r['return']:,.0f}%")
print(f" Final Eq: ${r['equity']:,.0f}")
print(f" Drawdown: {r['drawdown']:.1f}%")
print(f" Config: Lev {p['leverage']}x | MA {p['ma_fast']}/{p['ma_slow']} | Stop {p['stop_atr']}ATR")
if __name__ == "__main__":
optimize()