forked from OPCODE-Open-Spring-Fest/QuantResearch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprofile_backtest.py
More file actions
55 lines (40 loc) · 1.29 KB
/
Copy pathprofile_backtest.py
File metadata and controls
55 lines (40 loc) · 1.29 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
"""Simple profiler to identify hotspots in backtest."""
import cProfile
import pstats
import sys
from io import StringIO
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
from quant_research_starter.backtest.vectorized import VectorizedBacktest
from quant_research_starter.data import SampleDataLoader
def profile_backtest():
"""Profile the backtest to identify hotspots."""
loader = SampleDataLoader()
prices = loader.load_sample_prices()
signals = prices.pct_change(20).fillna(0)
profiler = cProfile.Profile()
profiler.enable()
backtest = VectorizedBacktest(
prices=prices,
signals=signals,
initial_capital=1_000_000,
transaction_cost=0.001,
)
backtest.run(weight_scheme="rank")
profiler.disable()
s = StringIO()
stats = pstats.Stats(profiler, stream=s)
stats.sort_stats("cumulative")
stats.print_stats(20)
print("Top 20 functions by cumulative time:")
print(s.getvalue())
stats.sort_stats("tottime")
stats.print_stats(20)
print("\nTop 20 functions by total time:")
s2 = StringIO()
stats = pstats.Stats(profiler, stream=s2)
stats.sort_stats("tottime")
stats.print_stats(20)
print(s2.getvalue())
if __name__ == "__main__":
profile_backtest()