import numpy as np
import pandas as pd
from QuantConnect.Securities import Future
class GlobalMarketsMomentum(QCAlgorithm):
def Initialize(self):
# Set the cash we'd like to use for our backtest
# This is ignored in live trading
self.SetCash(100000)
# Start and end dates for the backtest.
# These are ignored in live trading.
self.SetStartDate(2018, 11, 1)
self.SetEndDate(2019, 1, 2)
self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin)
self.etfs = ['SPY', 'VEU', 'TLT', 'IJR', 'SPYG']
for etf in self.etfs:
self.AddEquity(etf, Resolution.Daily)
#self.Securities[etf].FeeModel = ConstantFeeTransactionModel(0)
#self.Securities[etf].SlippageModel = ConstantSlippageModel(0)
self.Schedule.On(self.DateRules.EveryDay('SPY'), self.TimeRules.At(0, 0), Action(self.ScheduleEndOfMonthRebalance))
self.Schedule.On(self.DateRules.EveryDay('SPY'), self.TimeRules.BeforeMarketClose('SPY', 1), Action(self.Rebalance))
# parameters
self.momentum_period = 164
def OnData(self, slice):
pass
def ScheduleEndOfMonthRebalance(self):
month_last_day = DateTime(self.Time.year, self.Time.month, DateTime.DaysInMonth(self.Time.year, self.Time.month))
trading_days = self.TradingCalendar.GetDaysByType(TradingDayType.BusinessDay, self.Time, month_last_day)
# get the last trading day of the month
for x in trading_days:
self.month_last_trading_day = x.Date.date()
def Rebalance(self):
if self.Time.date() != self.month_last_trading_day:
return
# uncomment to rebalance every Fridayy
# if self.Time.date().weekday() != 4:
# return
# get prices from momentum_period calendar days (not trading days) ago, note that the most recent price this will return is from the previous day
# specify symbols as a list so that a DataFrame is returned
historical_prices = self.History(self.etfs, TimeSpan.FromDays(self.momentum_period))
historical_prices = historical_prices.sort_index(ascending=True).loc[(slice(None), historical_prices.index.get_level_values(1)[0]), 'close'].unstack(0) # this gets close data for all symbols for the first date in the dataframe
# get the most recent prices
last_prices = self.History(self.etfs, 1, Resolution.Minute)['close'].unstack(0)