Repository navigation
Expand file tree
/
Copy pathsolution.py
More file actions
345 lines (267 loc) · 11.8 KB
/
Copy pathsolution.py
File metadata and controls
345 lines (267 loc) · 11.8 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
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import yfinance as yf
import pandas as pd
import backtrader as bt
def task_1(ticker_symbol, start_date, end_date):
df = yf.download(ticker_symbol,
start=start_date,
end=end_date,
auto_adjust=False,
multi_level_index=False)
df.index = pd.to_datetime(df.index)
df = df[['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume']]
data_feed = bt.feeds.PandasData(
dataname=df,
open=0,
high=1,
low=2,
close=4,
volume=5,
openinterest=-1
)
return data_feed
def task_2(data, cash, commission, slippage_percentage):
"""
In this task, you are asked to create a cerebro using BackTrader.
After initializing the cerebro, you need to add data, set initial cash and commission fee properly.
The data, cash, and commission have been given as the argument of the function.
Finally, you should return the cerebro.
:param data: a bt.feeds.PandasData object;
:param cash: initial cash
:param commission: commission fee for the broker.
:param slippage_percentage: percentage of slippage.
:return: the cerebro.
"""
# Enter your code here.
cerebro = bt.Cerebro()
cerebro.adddata(data)
cerebro.broker.set_cash(cash)
cerebro.broker.setcommission(commission)
cerebro.broker.set_slippage_perc(slippage_percentage)
return cerebro
def task_3():
import backtrader as bt
class TripleMovingAverageStrategy(bt.Strategy):
params = (
('short_period', 10),
('medium_period', 50),
('long_period', 100),
)
def __init__(self):
self.short_ma = bt.indicators.SimpleMovingAverage(self.data.close, period=self.params.short_period)
self.medium_ma = bt.indicators.SimpleMovingAverage(self.data.close, period=self.params.medium_period)
self.long_ma = bt.indicators.SimpleMovingAverage(self.data.close, period=self.params.long_period)
self.order = None
def next(self):
if self.order:
return
if not self.position:
if self.short_ma > self.medium_ma and self.medium_ma > self.long_ma:
self.order = self.buy()
elif self.short_ma < self.medium_ma and self.medium_ma < self.long_ma:
self.order = self.sell()
else:
if self.position.size > 0:
self.sell(exectype=bt.Order.StopTrail, trailpercent=0.02)
else: # short
self.buy(exectype=bt.Order.StopTrail, trailpercent=0.02)
########################################
## DO NOT CHANGE THE FOLLOWING FUNCTIONS (provided)
########################################
def log(self, txt, dt=None):
dt = dt or self.datas[0].datetime.date(0)
print('%s, %s' % (dt.isoformat(), txt))
def notify_order(self, order):
if order.status in [order.Submitted, order.Accepted]:
return
if order.status in [order.Completed]:
if order.isbuy():
self.log('BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
(order.executed.price, order.executed.value, order.executed.comm))
else:
self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
(order.executed.price, order.executed.value, order.executed.comm))
self.bar_executed = len(self)
elif order.status in [order.Canceled, order.Margin, order.Rejected]:
self.log('Order Canceled/Margin/Rejected')
self.order = None
def notify_trade(self, trade):
if not trade.isclosed:
return
self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %(trade.pnl, trade.pnlcomm))
def stop(self):
self.log('(MA Periods are %2d, %2d, %2d) Ending Value %.2f' %
(self.params.short_period, self.params.medium_period, self.params.long_period, self.broker.getvalue()))
return TripleMovingAverageStrategy
def task_4():
"""
You will use Backtrader to implement a BollignerBands overbought and oversold strategy by
creating a strategy class that inherit bt.strategy.
This strategy uses:
1. A lookback window (20 days).
2. A standard deviation multiplier (3).
The object should include two functions:
1. def __init__(self)
2. def next(self)
Compute these BollingerBands using the close prices (self.data.close).
You will need the indicator: bt.indicators.BollingerBands. You can find its introduction here:
https://www.backtrader.com/docu/indautoref/#bollingerbands
The entry condition should follow the BollignerBands overbought and oversold strategy.
The exit condition should be:
Exit if the price crosses above (greater than) the upper bound for a long position;
Exit if the price crosses below (less than) the lower bound for a short position.
:return: a strategy class that inherit bt.strategy.
"""
class BollingerBandsStrategy(bt.Strategy):
params = (
('period', 20),
('devfactor', 3),
)
def __init__(self):
self.bb = bt.indicators.BollingerBands(
self.data.close,
period=self.params.period,
devfactor=self.params.devfactor
)
def next(self):
if not self.position:
if self.data.close[0] < self.bb.lines.bot[0]:
self.buy()
elif self.data.close[0] > self.bb.lines.top[0]:
self.sell()
else:
if self.position.size > 0:
if self.data.close[0] > self.bb.lines.top[0]:
self.close()
elif self.position.size < 0:
if self.data.close[0] < self.bb.lines.bot[0]:
self.close()
########################################
## DO NOT CHANGE THE FOLLOWING FUNCTION.
########################################
def log(self, txt, dt=None):
''' Logging function for this strategy'''
dt = dt or self.datas[0].datetime.date(0)
print('%s, %s' % (dt.isoformat(), txt))
def notify_order(self, order):
if order.status in [order.Submitted, order.Accepted]:
# Buy/Sell order submitted/accepted to/by broker - Nothing to do
return
# Check if an order has been completed
# Attention: broker could reject order if not enough cash
if order.status in [order.Completed]:
if order.isbuy():
self.log(
'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
(order.executed.price,
order.executed.value,
order.executed.comm))
self.buyprice = order.executed.price
self.buycomm = order.executed.comm
else: # Sell
self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
(order.executed.price,
order.executed.value,
order.executed.comm))
self.bar_executed = len(self)
elif order.status in [order.Canceled, order.Margin, order.Rejected]:
self.log('Order Canceled/Margin/Rejected')
self.order = None
def notify_trade(self, trade):
if not trade.isclosed:
return
self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
(trade.pnl, trade.pnlcomm))
return BollingerBandsStrategy
def task_5(cerebro, strategy_class, stake):
"""
Add the strategy class to cerebro.
Add a FixedSize sizer according to the stake.
:param cerebro: a cerebro object
:param strategy_class: a strategy class returned by task 3 or 4.
:param stake: sizer.
:return: the cerebro.
"""
# Enter your code here.
cerebro.addstrategy(strategy_class)
cerebro.addsizer(bt.sizers.FixedSize, stake=stake)
return cerebro
def task_6(cerebro):
"""
Run the cerebro and return the cash after the running.
:param cerebro: a cerebro object
:return: cash
"""
# Enter your code here.
cerebro.run()
return cerebro.broker.getvalue()
def task_7(cerebro, stake):
"""
In this task, you are asked to optimize the TMA strategy (with grid search) you have implemented in Task 3.
Given a cerebro, you need to create a TMA strategy class (by calling the function task_3()), add the strategy to the cerebro, and set the sizer.
The parameters you optimize are the short period, the medium period, and the long period.
Short period can select among three values 5, 10 and 20.
Medium period can select among three values 50, 100 and 150.
Long period can select among three values 200, 250 and 300.
You need to run the cerebro with maxcpu set to be 1 and see which combination yield the highest profit in the end.
Return two objects. The first is your username. The second is a dictionary with the best parameters and the best value from the grid search.
Please use the trading data given by the get_periods.py using your username.
E.g.,
best_result = {}
best_result["short_period"] = 5
best_result["medium_period"] = 50
best_result["long_period"] = 200
best_result["value"] = 95624.37
:return: wangyzh", best_result
:param cerebro: a cerebro object
:param stake: sizer.
:return: Your MWS username, best_result.
"""
'''
short_periods = [5, 10, 20]
medium_periods = [50, 100, 150]
long_periods = [200, 250, 300]
for short in short_periods:
for medium in medium_periods:
for long_ in long_periods:
# Reset cerebro
cerebro = task_2(data=data, cash=1e6, commission=0.001, slippage_percentage=0.01)
data = bt.feeds.PandasData(dataname=data) # Replace with your data
cerebro.addstrategy(TMA_Strategy, short_period=short, medium_period=medium, long_period=long_)
cerebro.addsizer(bt.sizers.FixedSize, stake=stake)
# Run backtest
cerebro.run(maxcpus = 1)
end_value = cerebro.broker.getvalue()
print(short, medium, long_, end_value)
'''
TMA_Strategy = task_3()
cerebro.optstrategy(
TMA_Strategy,
short_period=[5, 10, 20],
medium_period=[50, 100, 150],
long_period=[200, 250, 300],
)
cerebro.addsizer(bt.sizers.FixedSize, stake=stake)
results = cerebro.run(maxcpus=1)
best_result = {}
best_result["short_period"] = 5
best_result["medium_period"] = 100
best_result["long_period"] = 250
best_result["value"] = 997975.23
return "sgrgavan", best_result
def task_8():
"""
Write your own code to get the total_compound_return and the sharpe ratio of
the Bolliger Band Overbought/Oversold strategy in task 4 using your trading period. Once you
get these ratios, change their values in the risk_adjusted_returns dictionary.
Return two objects. The first is your username. The second is the risk_adjusted_returns dictionary.
Please use the trading data given by the get_periods.py using your username.
E.g.,
returns = {}
returns["total_compound_return"] = 0
returns["sharpe_ratio"] = 0
return "wangyzh", returns
"""
returns = {}
returns["total_compound_return"] = -0.0012
returns["sharpe_ratio"] = -4.445588934420236
return "sgrgavan", returns