-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathbacktest.py
executable file
·53 lines (41 loc) · 1.56 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
import backtrader as bt
from backtrader.feeds import PandasData
from datetime import datetime
import pandas as pd
import quantstats as qs
class Addmoredata(PandasData):
lines = ('score','rank','signal',)
params = (('score',5),('rank',6),('signal',7),)
def test(preds,strategy,hold_day=10,cash=1000000):
columns=['high','low','open','close','volume','score','rank','signal']
cerebro = bt.Cerebro()
datas=preds.groupby('symbol')
df_align=pd.DataFrame()
print("loading datas...")
for symbol,data in datas:
newdata=pd.DataFrame()
data['date'] = pd.to_datetime(data['date'], format='%Y-%m-%d')
data=data.set_index('date')
data=data.fillna(0)
for column in columns:
newdata[column]=data[column]
data=Addmoredata(dataname=newdata)
cerebro.adddata(data,name=str(symbol))
print("runing backtest...")
cerebro.addstrategy(strategy,hold_day=hold_day,hold_n=10)
cerebro.addanalyzer(bt.analyzers.TimeReturn, _name = "TimeReturn")
results = cerebro.run()
strat = results[0]
returns=pd.Series(strat.analyzers.TimeReturn.get_analysis())
returns=returns.dropna()
portvalue = cerebro.broker.getvalue()
return returns
def analysis(returns,bench):
myReturns=returns+1
bench['return']=bench['close'].shift(1)/bench['close']
benchReturns=bench['return']
benchReturns.fillna(0)
myReturns=myReturns.cumprod()
benchReturns=benchReturns.cumprod()
qs.extend_pandas()
qs.reports.full(myReturns, benchReturns)