-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbacktest.py
More file actions
206 lines (138 loc) · 5.88 KB
/
Copy pathbacktest.py
File metadata and controls
206 lines (138 loc) · 5.88 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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#!/usr/bin/env python3
import argparse
import json
import sys
import os
from datetime import datetime, timedelta
from dotenv import load_dotenv
load_dotenv()
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from core.backtesting import BacktestEngine
from core.metrics import generate_performance_report, calculate_buy_and_hold
def parse_arguments():
parser = argparse.ArgumentParser(
description='Backtest TradeGraph agents on historical market data',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python backtest.py SPY
python backtest.py NVDA --start 2023-01-01 --end 2024-01-01
python backtest.py AAPL --interval 1d --period 6mo
python backtest.py TSLA --capital 20000 --output results.json
"""
)
parser.add_argument('ticker', type=str,
help='Stock ticker symbol (e.g., SPY, NVDA, AAPL)')
date_group = parser.add_mutually_exclusive_group()
date_group.add_argument('--start', type=str,
help='Start date (YYYY-MM-DD). Requires --end')
date_group.add_argument('--period', type=str, default='1y',
help='Period (e.g., 1y, 6mo, 3mo, 1mo). Default: 1y')
parser.add_argument('--end', type=str,
help='End date (YYYY-MM-DD). Requires --start. Default: today')
parser.add_argument('--interval', type=str, default='1d',
choices=['1d', '1h', '5m', '15m', '30m', '1wk', '1mo'],
help='Data interval. Default: 1d (daily)')
parser.add_argument('--capital', type=float, default=10000.0,
help='Initial capital. Default: $10,000')
parser.add_argument('--output', type=str,
help='Output file path for detailed JSON results (optional)')
parser.add_argument('--verbose', action='store_true',
help='Show detailed trade-by-trade output')
return parser.parse_args()
def validate_dates(args):
if args.start and args.end:
try:
start = datetime.strptime(args.start, '%Y-%m-%d')
end = datetime.strptime(args.end, '%Y-%m-%d')
if start >= end:
print("Error: Start date must be before end date")
sys.exit(1)
return args.start, args.end
except ValueError:
print("Error: Invalid date format. Use YYYY-MM-DD")
sys.exit(1)
elif args.start and not args.end:
print("Error: --start requires --end")
sys.exit(1)
elif args.end and not args.start:
print("Error: --end requires --start")
sys.exit(1)
else:
end = datetime.now()
period_map = {
'1y': 365, '2y': 730, '5y': 1825,
'6mo': 180, '3mo': 90, '1mo': 30,
'1w': 7, '1d': 1
}
period_lower = args.period.lower()
if period_lower not in period_map:
print(f"Error: Invalid period '{args.period}'. Use format like '1y', '6mo', '3mo', etc.")
sys.exit(1)
days = period_map[period_lower]
start = end - timedelta(days=days)
return start.strftime('%Y-%m-%d'), end.strftime('%Y-%m-%d')
def main():
args = parse_arguments()
start_date, end_date = validate_dates(args)
print("\n" + "="*70)
print(" TradeGraph Backtesting Engine")
print("="*70)
print(f"\nTicker: {args.ticker}")
print(f"Period: {start_date} to {end_date}")
print(f"Interval: {args.interval}")
print(f"Initial Capital: ${args.capital:,.2f}")
print()
engine = BacktestEngine(
ticker=args.ticker,
start_date=start_date,
end_date=end_date,
interval=args.interval,
initial_capital=args.capital
)
results = engine.run()
if 'error' in results:
print(f"\nError: {results['error']}")
sys.exit(1)
if engine.historical_data:
bh_results = calculate_buy_and_hold(engine.historical_data, args.capital)
print(f"\n{'='*70}")
print(" BUY-AND-HOLD BENCHMARK")
print(f"{'='*70}")
print(f"Final Equity: ${bh_results['final_equity']:,.2f}")
print(f"Total Return: {bh_results['total_return_pct']:+.2f}%")
print(f"Shares Bought: {bh_results['shares_purchased']:.2f}")
results['benchmark'] = bh_results
report = generate_performance_report(results)
print(report)
if args.verbose and results['trade_log']:
print("\n" + "="*70)
print(" TRADE LOG")
print("="*70)
print(f"{'Date':<12} {'Action':<30} {'Price':<10} {'Equity':<12}")
print("-"*70)
for trade in results['trade_log']:
date_str = trade['timestamp'].strftime('%Y-%m-%d')
action = trade['action'][:28]
price = trade['price']
equity = trade['total_equity']
print(f"{date_str:<12} {action:<30} ${price:<9.2f} ${equity:<11,.2f}")
if args.output:
json_results = results.copy()
json_results['equity_curve'] = [
{**point, 'timestamp': point['timestamp'].isoformat()}
for point in results['equity_curve']
]
json_results['trade_log'] = [
{**trade, 'timestamp': trade['timestamp'].isoformat()}
for trade in results['trade_log']
]
output_dir = os.path.dirname(args.output)
if output_dir and not os.path.exists(output_dir):
os.makedirs(output_dir)
with open(args.output, 'w') as f:
json.dump(json_results, f, indent=2)
print(f"\n✓ Detailed results saved to: {args.output}")
print()
if __name__ == "__main__":
main()