-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbtr_analyser_example.py
121 lines (97 loc) · 3.69 KB
/
btr_analyser_example.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
110
111
112
113
114
115
116
117
118
119
120
121
'''
Author: www.backtest-rookies.com
MIT License
Copyright (c) 2017 backtest-rookies.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
import backtrader as bt
from datetime import datetime
from collections import OrderedDict
class firstStrategy(bt.Strategy):
def __init__(self):
self.rsi = bt.indicators.RSI_SMA(self.data.close, period=21)
def next(self):
if not self.position:
if self.rsi < 30:
self.buy(size=100)
else:
if self.rsi > 70:
self.sell(size=100)
def printTradeAnalysis(analyzer):
'''
Function to print the Technical Analysis results in a nice format.
'''
#Get the results we are interested in
total_open = analyzer.total.open
total_closed = analyzer.total.closed
total_won = analyzer.won.total
total_lost = analyzer.lost.total
win_streak = analyzer.streak.won.longest
lose_streak = analyzer.streak.lost.longest
pnl_net = round(analyzer.pnl.net.total,2)
strike_rate = (total_won / total_closed) * 100
#Designate the rows
h1 = ['Total Open', 'Total Closed', 'Total Won', 'Total Lost']
h2 = ['Strike Rate','Win Streak', 'Losing Streak', 'PnL Net']
r1 = [total_open, total_closed,total_won,total_lost]
r2 = [strike_rate, win_streak, lose_streak, pnl_net]
#Check which set of headers is the longest.
if len(h1) > len(h2):
header_length = len(h1)
else:
header_length = len(h2)
#Print the rows
print_list = [h1,r1,h2,r2]
row_format ="{:<15}" * (header_length + 1)
print("Trade Analysis Results:")
for row in print_list:
print(row_format.format('',*row))
def printSQN(analyzer):
sqn = round(analyzer.sqn,2)
print('SQN: {}'.format(sqn))
#Variable for our starting cash
startcash = 100000
#Create an instance of cerebro
cerebro = bt.Cerebro()
#Add our strategy
cerebro.addstrategy(firstStrategy)
#Get Apple data from Yahoo Finance.
data = bt.feeds.YahooFinanceData(
dataname='AAPL',
fromdate = datetime(2009,1,1),
todate = datetime(2017,1,1),
buffered= True
)
#Add the data to Cerebro
cerebro.adddata(data)
# Set our desired cash start
cerebro.broker.setcash(startcash)
# Add the analyzers we are interested in
cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="ta")
cerebro.addanalyzer(bt.analyzers.SQN, _name="sqn")
# Run over everything
strategies = cerebro.run()
firstStrat = strategies[0]
# print the analyzers
printTradeAnalysis(firstStrat.analyzers.ta.get_analysis())
printSQN(firstStrat.analyzers.sqn.get_analysis())
#Get final portfolio Value
portvalue = cerebro.broker.getvalue()
#Print out the final result
print('Final Portfolio Value: ${}'.format(portvalue))
#Finally plot the end results
cerebro.plot(style='candlestick')