-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathbacktest.py
109 lines (67 loc) · 3.15 KB
/
backtest.py
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
import pandas as pd
import sqlalchemy
sql_obj = sqlalchemy.create_engine('postgresql://krh:krh@123@localhost:5432/krh')
df_1min = pd.read_sql_table('tatamotor_1min', sql_obj, parse_dates={'date': {'format': '%Y-%m-%d %H:%M:%S'}})
df_5mins = pd.read_sql_table('tatamotor_5mins', sql_obj, parse_dates={'date': {'format': '%Y-%m-%d %H:%M:%S'}})
df_time_frames=[df_5mins]
df_time_frames[0].head()
#############################################################
####### Manin ###############
import backtrader as bt
from strategy.ReversalAction import ReversalAction
from analyzer import printTradeAnalysis, printSQN
import datetime
import numpy as np
if __name__=='__main__':
ticker_name="TATAMOTOR-STK-NSE"
cerebro=bt.Cerebro()
#Add data
for df in df_time_frames:
data=bt.feeds.PandasData(dataname=df,
datetime=0,
fromdate=datetime.datetime(2021, 2, 1),
)
#cerebro.resampledata(data,timeframe=bt.TimeFrame.Minutes,
# compression=2,
# )
cerebro.adddata(data)
#Set Caah
cerebro.broker.setcash(1000000)
#Add stratedgy to Cerebro
sr_levels=np.array([339.01,324.11,319.38,312.96,304.37,299.17,295.17,293.48,291.24,283.31])
cerebro.addstrategy(ReversalAction,
short_period=50,
long_period=200,
sr_levels=sr_levels,
reversal_tol_factor=.8,
breakout_tol_factor=.5,
order_time="14:30",
closing_time="15:10",
show_trades= False,
show_trade_object=False,
strike_at="sr_price",
order_at="mid_bar_price",
target_percentage=1.8,
stop_percentage=1.2,
execute_breakout=True,
allow_shorting=True,
cerebro=cerebro)
#Adding Anylizer
cerebro.addanalyzer(bt.analyzers.PyFolio, _name='PyFolio')
cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="ta")
cerebro.addanalyzer(bt.analyzers.SQN, _name="sqn")
# Adding Observer
cerebro.addobserver(bt.observers.DrawDown, plot=True, subplot=False)
#RUN Cerebro Engine
strategies=cerebro.run()
# Capture results
firstStrat = strategies[0]
# print the analyzers
printTradeAnalysis(firstStrat.analyzers.ta.get_analysis())
printSQN(firstStrat.analyzers.sqn.get_analysis())
portfolio_stats = firstStrat.analyzers.getbyname('PyFolio')
returns, positions, transactions, gross_lev = portfolio_stats.get_pf_items()
returns.index = returns.index.tz_convert(None)
import quantstats
report_name=ticker_name.split("-")[0]
quantstats.reports.html(returns, output=str(report_name+'.html'), title=report_name)