Skip to content

Instantly share code, notes, and snippets.

@a-r-d a-r-d/main.py
Created Feb 22, 2018

Embed
What would you like to do?
Basic sector rebalance monthly algorithm
import numpy as np
class BasicTemplateAlgorithm(QCAlgorithm):
'''Basic template algorithm simply initializes the date range and cash'''
def Initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.SetStartDate(2004, 1, 1) #Set Start Date
self.SetEndDate(2018, 2, 16) #Set End Date
self.SetCash(100000) #Set Strategy Cash
self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage)
self.AddEquity("SPY", Resolution.Daily)
self.load_symbols()
self.rebalance = True
if self.rebalance:
self.Schedule.On(self.DateRules.MonthStart("SPY"), \
self.TimeRules.AfterMarketOpen("SPY"), \
Action(self.trade)
)
else:
self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.AfterMarketOpen("SPY", 30), Action(self.trade))
def OnData(self, data):
pass
def trade(self):
for symbol in self.symbols:
holdings = self.Portfolio[symbol].Quantity
if self.rebalance:
# always monthly rebalance
self.SetHoldings(symbol, symbol.weight)
if holdings <= 0:
self.SetHoldings(symbol, symbol.weight)
def load_symbols(self):
sectors = {
'VOO': 0.25,
'VWO': 0.25,
'BND': 0.25,
'VNQ': 0.15,
'VT': 0.1
}
self.symbols = []
for key, value in sectors.iteritems():
symbol = self.AddEquity(key, Resolution.Daily, Market.USA, True, 1.0).Symbol
symbol.weight = value
self.symbols.append(symbol)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.