Hi, I dont understand why I am getting a KeyError: -1 ?
Any help appreciated.
#
# QuantConnect Basic Template:
# Fundamentals to using a QuantConnect algorithm.
#
# You can view the QCAlgorithm base class on Github:
# https://github.com/QuantConnect/Lean/tree/master/Algorithm
#
from datetime import date
import numpy as np
import pandas as pd
class BasicTemplateAlgorithm(QCAlgorithm):
def Initialize(self):
# Set the cash we'd like to use for our backtest
# This is ignored in live trading
self.SetCash(10000)
# Start and end dates for the backtest.
# These are ignored in live trading.
self.SetStartDate(2015,1,1)
self.SetEndDate(2015,6,1)
# Add assets you'd like to see
self.safe = self.AddEquity("AGG", Resolution.Daily).Symbol
self.tlt = self.AddEquity("TLT", Resolution.Daily).Symbol
self.Log("Safe is: {}".format(type(self.safe)))
self.Log("Safe value: {}".format(self.safe))
self.Log("tlt is: {}".format(type(self.tlt)))
self.Log("tlt value: {}".format(self.tlt))
self._symbols = []
self._symbols.append("SPY"), self._symbols.append("EFA"), self._symbols.append("EEM"), self._symbols.append("GLD")
for stock in self._symbols:
self.AddSecurity(SecurityType.Equity, stock, Resolution.Daily)
def OnData(self, slice):
# Assign the day on the date
today = self.Time
if not (today.month == 12 or today.month == 3 or today.month == 6 or today.month == 9):
return
mom_period = 22
# Find historical price and calculate momentum
histmom = self.History(self._symbols, 22, Resolution.Daily)["close"].unstack(level=0)
# mom = (histmom[-1]/histmom[0]) - 1.0
mom = (histmom.iloc[-1]/histmom.iloc[0]) - 1.0
# mom = mom.dropna()
top_assets = mom.sort_values().index[-4:]
top_assets_values = mom.sort_values()[-4:]
self.Log("History is: {}".format(type(histmom)))
self.Log("mom is: {}".format(type(mom)))
safe_percent = 0
tlt_percent = 0
# Create list to manage Portfolio
currently_holding = []
# Rebalance Securities
for x in range(len(top_assets)):
if top_assets_values[x] > 0:
self.SetHoldings(top_assets[x], 0.45)
currently_holding.append(top_assets[x])
else:
hist = self.History(self.safe, 22, Resolution.Daily)["close"].unstack(level=0)
mom = (hist[-1]/hist[0]) - 1.0
if mom > 0:
safe_percent += 0.45
if self.safe not in currently_holding:
currently_holding.append(self.safe)
else:
tlt_percent +=0.45
if self.tlt not in currently_holding:
currently_holding.append(self.tlt)
top_up = 4 - len(top_assets)
if top_up > 0:
for x in range(top_up):
hist = self.History(self.safe, 22, Resolution.Daily)["close"].unstack(level=0)
mom = (hist[-1]/hist[0]) - 1.0
if mom > 0:
safe_percent += 0.25
if self.safe not in currently_holding:
currently_holding.append(self.safe)
else:
tlt_percent += 0.25
if self.tlt not in currently_holding:
currently_holding.append(self.tlt)
print(safe_percent, tlt_percent)
if safe_percent > 0:
self.SetHoldings(self.safe, safe_percent)
if tlt_percent > 0:
self.SetHoldings(self.tlt, tlt_percent)
print ("2" + str(currently_holding))
def clear(self, data):
today = self.Time
if not (today.month == 12 or today.month == 3 or today.month == 6 or today.month == 9):
return
print("1" + str(currently_holding))
for s in Portfolio:
self.SetHoldings(s, 0)
currently_holding = []