class X(QCAlgorithm):
def Initialize(self):
self.params = {
"symbol": "USO",
"long_ratio": +1.0,
"short_ratio": -0.8,
"macd_signal_tolerance": 0.0024,
"resolution": Resolution.Daily,
}
self.SetStartDate(2012, 1, 1)
self.SetEndDate(2019, 1, 1)
self.SetCash(10000)
self.AddEquity(self.params["symbol"], self.params["resolution"])
self.SetBenchmark(self.params["symbol"])
# define our daily macd(12,26) with a 9 day signal
self.__macd = self.MACD(self.params["symbol"], 12, 26, 9, MovingAverageType.Exponential, self.params["resolution"])
self.__previous = datetime.min
self.PlotIndicator("MACD", True, self.__macd, self.__macd.Signal)
self.PlotIndicator(self.params["symbol"], self.__macd.Fast, self.__macd.Slow)
def OnData(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
# wait for our macd to fully initialize
if not self.__macd.IsReady: return
# only once per day
if self.__previous.date() == self.Time.date(): return
# define a small tolerance on our checks to avoid bouncing
# tolerance = 0.0025
tolerance = self.params["macd_signal_tolerance"]
holdings = self.Portfolio[self.params["symbol"]].Quantity
if holdings != 0:
msg = "Holdings no zero: " + str(holdings)
self.Debug(msg)
signalDeltaPercent = (self.__macd.Current.Value - self.__macd.Signal.Current.Value)/self.__macd.Fast.Current.Value
# if our macd is greater than our signal, then let's go long
if holdings <= 0 and signalDeltaPercent > tolerance: # 0.01%
# longterm says buy as well
self.SetHoldings(self.params["symbol"], self.params["long_ratio"])
# of our macd is less than our signal, then let's sell our longs and go short
elif holdings >= 0 and signalDeltaPercent < -tolerance:
# self.Liquidate(self.params["symbol"])
self.SetHoldings(self.params["symbol"], self.params["short_ratio"])
self.__previous = self.Time