-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfilename.py
85 lines (65 loc) · 2.76 KB
/
filename.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
import logging
import os
import pandas as pd
import backtrader as bt
import yfinance as yf
class StatsTest(bt.Strategy):
"""
Test Strategy to check some statistics
This strategy should be used with TestData.csv
TestData.csv will rise from 1 dollar to 101 dollars over 20 bars then fall
from 101 to 1 over the next 20 bars. (40 bar round trip). The pattern will
repeat in a loop until the end of the data set.
The first two bars close/open at 1 dollar to ease testing with market orders
"""
def __init__(self):
self.logger = logging.getLogger(__name__)
self.date = self.datas[0].datetime.date
self.dataclose = self.datas[0].close
self.buy_bars = [1, 21, 41, 61]
self.close_bars = [20, 40, 60, 80]
self.sell_bars = []
self.log(logging.INFO, 'Strategy Initialized!')
def next(self):
bar = len(self.data)
if bar in self.buy_bars:
print('Buying On Bar {} Price = {}'.format(bar, self.dataclose[0]))
self.buy(stake=1)
self.log(logging.INFO, 'Buy @ {}'.format(self.dataclose[0]))
elif bar in self.close_bars:
print('Closing On Bar {} Price = {}'.format(bar, self.dataclose[0]))
self.close(stake=1)
self.log(logging.INFO, 'Exit @ {}'.format(self.dataclose[0]))
else:
pass
def log(self, level, message):
self.logger.log(level, '{} - {}'.format(self.date(0), message))
class ExampleBacktest(ob.Backtest):
def get_symbols(self):
return ['AAPL', 'MSFT', 'TestData']
def get_parameters(self, strategy, symbols):
return {'param1': 10, 'param2': 20}
def run(self, symbols, cash, strategy, **params):
path_dir = os.path.dirname(os.path.realpath(__file__))
# Setup Cerebro
#cerebro = ob.Backtest.setup_cerebro(cash)
cerebro = bt.Cerebro()
cerebro.broker.setcash(cash)
# Add Data
for s in symbols:
df = pd.read_csv(os.path.join(path_dir, '{}.csv'.format(s)), parse_dates=True, index_col=0)
data = bt.feeds.PandasData(dataname=df)
cerebro.adddata(data)
data = bt.feeds.PandasData(dataname=yf.download('TSLA', '2018-01-01', '2018-01-10'))
cerebro.adddata(data)
# Strategy
cerebro.addstrategy(strategy, **params)
cerebro.addanalyzer(bt.analyzers.PyFolio, _name='pyfolio')
cerebro.addanalyzer(bt.analyzers.DrawDown, _name='drawdown')
cerebro.addanalyzer(bt.analyzers.SQN, _name='SQN')
cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name='trades')
#cerebro.adddata(data)
# Backtest
results = cerebro.run()
pnl = cerebro.broker.getvalue() - cash
return pnl, results[0]