Created
February 22, 2018 01:42
-
-
Save a-r-d/5d271f01c29f15b8b68a4409e62c282c to your computer and use it in GitHub Desktop.
Basic sector rebalance monthly algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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