from datetime import datetime
import decimal
import numpy as np
class DynamicBreakoutAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2010,1,1)
self.SetEndDate(2010,6,30)
self.SetCash(100000)
self.numdays = 20
self.ceiling,self.floor = 60,20
self.buypoint, self.sellpoint= None, None
self.longLiqPoint, self.shortLiqPoint, self.yesterdayclose= None, None, None
self.bband = {}
for ticker in ["EURUSD", "GBPUSD"]:
symbol = self.AddForex(ticker, Resolution.Hour, Market.Oanda).Symbol
self.bband[symbol] = self.BB(symbol, self.numdays, 2, MovingAverageType.Simple, Resolution.Daily)
self.Schedule.On(self.DateRules.EveryDay(symbol), self.TimeRules.BeforeMarketClose(symbol,1),Action(self.SetSignal))
self.SetBenchmark(symbol)
def SetSignal(self):
for symbol, bband in self.bband.items():
close = self.History(symbol, 31, Resolution.Daily)['close']
todayvol = np.std(close[1:31])
yesterdayvol = np.std(close[0:30])
deltavol = (todayvol - yesterdayvol) / todayvol
self.numdays = int(round(self.numdays * (1 + deltavol)))
if self.numdays > self.ceiling:
self.numdays = self.ceiling
elif self.numdays < self.floor:
self.numdays = self.floor
self.high = self.History(symbol, self.numdays, Resolution.Daily)['high']
self.low = self.History(symbol, self.numdays, Resolution.Daily)['low']
self.buypoint = max(self.high)
self.sellpoint = min(self.low)
historyclose = self.History(symbol, self.numdays, Resolution.Daily)['close']
self.longLiqPoint = np.mean(historyclose)
self.shortLiqPoint = np.mean(historyclose)
self.yesterdayclose = historyclose.iloc[-1]
# wait for our BollingerBand to fully initialize
if not all([bband.IsReady for symbol, bband in self.bband.items()]): return
holdings = self.Portfolio[symbol].Quantity
if self.yesterdayclose > self.Bolband.UpperBand.Current.Value and self.Portfolio[symbol].Price >= self.buypoint:
self.SetHoldings(symbol, .1)
elif self.yesterdayclose < self.Bolband.LowerBand.Current.Value and self.Portfolio[symbol].Price <= self.sellpoint:
self.SetHoldings(symbol, -.1)
if holdings > 0 and self.Portfolio[symbol].Price <= self.shortLiqPoint:
self.Liquidate(symbol)
elif holdings < 0 and self.Portfolio[symbol].Price >= self.shortLiqPoint:
self.Liquidate(symbol)
self.Log(str(self.yesterdayclose)+(" # of days ")+(str(self.numdays)))
def OnData(self,data):
return
Hi All
Encountered error backtest running the above algo.
I have copied the entire algo for the DynamicBreakout in the strategy and tried to add more than 1 forex pair into the algo and changed some part of it (variable name and also assign a dictionery to the BB) but it failed to run.
Hope anyone can point out the problem with this code as im still figuring out what is the problem.
Thanks in advance.
Derek Melchin
Hi You Leong Law,
To resolve the issue, in `SetSignal`, we need to add
bb = self.bband[symbol]
and replace `self.Bolband` with `bb`. See the attached backtest for reference.
Continuing the development of this algorithm, we recommend replacing the `History` calls in `SetSignal` with indicators. The algorithm will run much faster if we use the STD, MAX, MIN, and SMA indicators.
Best,
Derek Melchin
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
You Leong Law
Many Thanks Derek,
Will take up your advice and try it with the indicators function :)
You Leong Law
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!