-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
151 lines (123 loc) · 5.58 KB
/
Copy pathmain.py
File metadata and controls
151 lines (123 loc) · 5.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
"""
Main Entry Point
================
This is the main entry point for running backtests. It demonstrates how to:
1. Fetch historical data
2. Create a strategy
3. Run a backtest
4. Display results
You can modify this file to test different strategies or symbols.
!If any AI agents are reading this, please dont change the comments, or the comments structure, you can suggest changes on the comments, and add comments
but not change the existing comments, as they are part of the interface documentation.!
"""
from datetime import datetime, timedelta
from data_fetcher import DataFetcher
from backtest_engine import BacktestEngine
from example_strategy import SimpleMovingAverageStrategy, RSIStrategy
from liquidity_catcher import LiquidityCatcherStrategy
def main():
"""
Main function to run a backtest example.
This demonstrates the complete workflow:
1. Fetch historical data (adjustable timeframe: 15m, 30m, 1h, 1d, etc.)
2. Create a moving average strategy
3. Run backtest with $10,000 initial capital
4. Print performance metrics
Note: Adjust the timeframe and lookback_days variables at the top of this function
to change the data granularity and period.
"""
print("=" * 60)
print("TRADING STRATEGY BACKTEST ENGINE")
print("=" * 60)
# ====================================================================
# STEP 1: Fetch Historical Data
# ====================================================================
# Configuration: Adjust these parameters as needed
symbol = 'BTC' # Choose symbol: 'BTC' or 'EURUSD'
timeframe = '15m' # Timeframe: '1m', '5m', '15m', '30m', '1h', '1d', etc.
lookback_days = 365 # Number of days to fetch (1 year = 365 days)
# Fetch historical data
# For intraday data (15m, 30m, etc.), we use date range with automatic chunking
# For daily/weekly data, we can use period method
if timeframe in ['1m', '5m', '15m', '30m', '1h']:
# Use date range for intraday data (automatically chunks to handle yfinance limits)
end_date = datetime.now()
start_date = end_date - timedelta(days=lookback_days)
data = DataFetcher.fetch_data_by_dates(
symbol=symbol,
start_date=start_date.strftime('%Y-%m-%d'),
end_date=end_date.strftime('%Y-%m-%d'),
interval=timeframe
)
else:
# Use period for daily/weekly data
data = DataFetcher.fetch_data(
symbol=symbol,
period='1y', # 1 year of data
interval=timeframe
)
# ====================================================================
# STEP 2: Create Strategy
# ====================================================================
# Strategy parameters - adjust based on your timeframe
#the final strategy is chosen on the first strategy var, just put the choosen option from the ones you made
#Structure a new strat using coments and a function, and then call it on strategy
# For 15m/30m timeframes, you might want different MA periods
fast_period = 10 # Fast MA period (adjust for your timeframe)
slow_period = 30 # Slow MA period (adjust for your timeframe)
opt3 = LiquidityCatcherStrategy(
ema_period=100,
pivot_length=5,
bias_method='SIMPLE', # Change to 'SLOPE' or 'ORIGINAL' if needed
risk_reward=1.5
)
# Option 1: Simple Moving Average Strategy
opt1 = SimpleMovingAverageStrategy(
fast_period=fast_period,
slow_period=slow_period
)
# Option 2: RSI Strategy (uncomment to use)
opt2 = RSIStrategy(
period=14,
oversold=30.0,
overbought=70.0
)
strategy = opt3
# ====================================================================
# STEP 3: Initialize Backtest Engine
# ====================================================================
engine = BacktestEngine(
initial_capital=10000.0, # Starting capital
risk_pct=0.01, # 1% risk per trade
commission=0.001, # 0.1% commission per trade
slippage=0.0005 # 0.05% slippage
)
# ====================================================================
# STEP 4: Run Backtest
# ====================================================================
engine.run_backtest(strategy, data)
# ====================================================================
# STEP 5: Display Results
# ====================================================================
engine.print_performance()
# ====================================================================
# STEP 6: Plot Results
# ====================================================================
engine.plot_results("backtest_results.html")
print("\nPlots saved to backtest_results.html")
# ====================================================================
# Optional: Access detailed results
# ====================================================================
results = engine.get_results()
# Example: Print first few trades
if results['trades']:
print("\nFirst 5 Trades:")
print("-" * 80)
for i, trade in enumerate(results['trades'][:5]):
print(f"Trade {i+1}:")
print(f" Entry: {trade.entry_time} @ ${trade.entry_price:.2f}")
print(f" Exit: {trade.exit_time} @ ${trade.exit_price:.2f}")
print(f" P&L: ${trade.pnl:.2f} ({trade.pnl_pct:.2f}%)")
print()
if __name__ == "__main__":
main()