Back

Error: "Specified Cast is not valid"

So I'm undertaking my first project that uses universes, rather than simply just feeding the algorithm a fixed set of symbols to work with, and so far it's been a disaster.

The whole day, no matter what I do I get the Error: "Specified Cast is not valid" with no line given, and I'm at my wit's end at this point. All I'm trying to do is take the universe and load it into an array, so I can select ETF's to trade buy on some indicator.

If anybody can help me with this, I will be eternally grateful. Thank you in advance.

Here is my code:

import numpy as np


class RegionalETFrotationAlgorithm(QCAlgorithm):


def Initialize(self):

self.UniverseSettings.Resolution = Resolution.Daily

self.AddUniverse(self.CoarseSelectionFunction)

for universe in self.UniverseManager.Values:
if universe is UserDefinedUniverse:
continue
self.tickers = universe.Members.Keys
for symbol in self.tickers:
self.Debug(symbol.Symbol.Value)


self.changes = None
self.SetStartDate(2008, 1, 1) #Set Start Date
self.SetEndDate(2018, 6 ,1) #Set End Date
self.SetCash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
#self.tickers = ["MDY", "IEV", "EEM", "ILF", "EPP", "DIA"]
self.AddEquity("EDV", Resolution.Daily)
self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol
self.growth = []

for ticker in self.tickers:
self.AddSecurity(SecurityType.Equity, ticker.Symbol.Value, Resolution.Daily)
dictionary = [ticker.Symbol, self.MACD(ticker.Symbol.Value,12, 26, 9, MovingAverageType.Exponential, Resolution.Daily) ]
self.growth.append(dictionary)

#self.etf = self.growth[0]
self.current = []
self.top = []
self.Schedule.On(self.DateRules.MonthStart(self.spy), self.TimeRules.AfterMarketOpen(self.spy,5), Action(self.rebalance))
'''
def OnSecuritiesChanged(self, changes):
self.growth = []
self.changes = changes
for ticker in self._changes:
self.AddSecurity(SecurityType.Equity, ticker.Symbol.Value, Resolution.Daily)
dictionary = [ticker.Symbol, self.MACD(ticker.Symbol.Value,12, 26, 9, MovingAverageType.Exponential, Resolution.Daily) ]
self.growth.append(dictionary)
'''


def OnData(self, data):
if self.changes is None:
return


# if self.etf[1].Current.Value < 0:
# self.rebalance()
if not self.Portfolio.Invested:
self.rebalance()
for etf in self.current:
if etf[1].Current.Value < 0:
self.replace(etf)
pass


def replace(etf):
self.SetHoldings(etf[0], 0)
self.current.remove(etf)
for security in self.top:
if security in self.current:
continue
else:
if security[1].Current.Value > 0:
self.current.append(security)
self.SetHoldings(security, 0.2)


def CoarseSelectionFunction(self, coarse):
list = []
for security in coarse:
if security.HasFundamentalData==False:
list.append(security)
return list

def rebalance(self):
#self.current = self.growth
#self.current.sort(key=self.getMomentum, reverse = True)
#self.etf = self.current[0]

# if self.etf[1].Current.Value > 0:
# if self.Portfolio.Invested and not self.Portfolio[self.etf[0]].Invested:
# self.Liquidate()
# self.SetHoldings(self.etf[0], 1)

# else:
# if self.Portfolio.Invested:
# self.Liquidate()
# self.SetHoldings("EDV", 1)
self.Liquidate()
self.top = []
for etf in self.growth:
if etf[1].Current.Value > 0:
self.top.append(etf)
self.current.sort(key=self.getMomentum, reverse = True)
if len(self.top) ==0:
self.SetHoldings("EDV", 1)
else:
self.SetHoldings(self.top[0], 0.2)
self.SetHoldings(self.top[1], 0.2)
self.SetHoldings(self.top[2], 0.2)
self.SetHoldings(self.top[3], 0.2)
self.SetHoldings(self.top[4], 0.2)



def getMomentum(self,elem):
return elem[1]
Update Backtest







Thanks for attaching the code. There are a few concepts here that are being missed. The first is that in Initialize(), the universe has not been selected yet. As a result, iterating through UniverseManager.Values is not possible. It can be used later in the algorithm. 

The securities should already be subscribed during AddUniverse(), so the line AddEquity() is not needed. When adding indicators, they can be initialized in OnSecuritiesChanged(). The added securities can be accessed via changes.AddedSecurities, and that will keep the indicator from being added more than once into self.growth.

In regards to the error: "Specified Cast is not valid", this following code will fix the issue. The error was coming because coarse was never cast into a list in the beginning so a list was not being returned. 

def CoarseSelectionFunction(self, coarse):
etfs = list(coarse)
return [ x.Symbol for x in etfs if x.HasFundamentalData==False ]

After I solved this issue there ended up being more bugs, however the code below is running and will get you started. One important edit was that the indicators were saved into a list, however they were not mapped to their symbol properly so I went ahead and created that. Now when an indicator needs to be called, just called self.growth[ticker].

0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Update Backtest





0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Loading...

This discussion is closed