I am recieving the following error:
Runtime Error: One or more errors occurred. Specified cast is not valid.
The goal of my program is to use a rolling window of an input variable and and output variable which here is the price to create a prediction for the price. This is my program:
#All appropriate variables are imported before this line
# Demonstration of using coarse and fine universe selection together to filter down a smaller universe of stocks.
class FrameworkAlgorithm(QCAlgorithm):
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(2014,1,1) #Set Start Date
self.SetEndDate(2015,1,1) #Set End Date
self.SetCash(50000) #Set Strategy Cash
self.UniverseSettings.Resolution = Resolution.Daily
self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)
self.AddEquity("SPY", Resolution.Daily)
self.SetBenchmark("SPY")
self.__numberOfSymbols = 100
self.__numberOfSymbolsFine = 30
self._changes = None
self.Schedule.On(self.DateRules.MonthStart("SPY"), self.TimeRules.AfterMarketOpen("SPY"), Action(self.Rebalancing))
self.splotName = 'Strategy Info'
sPlot = Chart(self.splotName)
sPlot.AddSeries(Series('Leverage', SeriesType.Line, 0))
self.AddChart(sPlot)
self.historicalPERatio = {}
self.historicalPricetoCashRatio={}
#self.historicalTotalDebtEquityRatioGrowth = {}
self.FCFRatio = {}
#self.historicalEquityPerShareRatio = {}
#self.historicalEVToEBITDA = {}
self.CFOPerShare = {}
self.Y = {}
self.rollingWindowSize = 90;
self.averages = { };
def CoarseSelectionFunction(self, coarse):
x = list(coarse)
CoarseWithFundamental = [x for x in coarse if (x.HasFundamentalData) and (float(x.Price) > 5)]
filtered = [x for x in CoarseWithFundamental if x.HasFundamentalData
and x.Volume > 0
and x.Price > 0]
# sort descending by daily dollar volume
sortedByDollarVolume = sorted(filtered, key=lambda x: x.DollarVolume, reverse=True)
#HasFundamentalData = sorted(coarse, key=lambda x: HasFundamentalData, reverse=True)
top = sortedByDollarVolume[:self.__numberOfSymbols]
# return the symbol objects of the top entries from our sorted collection
return top
def FineSelectionFunction(self, fine):
self.r = [x for x in fine if x.ValuationRatios.PERatio]
for x in self.r:
if x.Symbol not in self.historicalPERatio.keys():
# Set up rolling window for new ticker
self.historicalPERatio[x.Symbol] = RollingWindow[Decimal](self.rollingWindowSize)
self.historicalPERatio[x.Symbol].Add(x.ValuationRatios.PERatio) #your job is to find the decimal current version for all the following variables
#self.prices_y[x.Symbol] = list(history.loc[x.Value]['close'])[1:]
self.r = [x for x in fine if PredictionEngine(x.historicalPERatio, x.Y ).predictionScore() > float(x.Price) or PredictionEngine(x.historicalPERatio , x.Y ).predictionScore() < float(x.Price)]
#self.a = (x for x in self.r
r = self.r
topFine = sorted(self.r, key=lambda x: x.ValuationRatios.PERatio, reverse = False)
self.topFine = [x.Symbol for x in topFine]
self.symbols = [i.Symbol for i in topFine]
self.y = self.History(self.symbols, self.rollingWindowSize, Resolution.Daily)
for i in self.symbols:
self.Debug(i.Symbol)
#self.Debug(self.symbols)
#[x.Symbol for x in self.r]
return self.symbols
def OnData(self, data):
print("asdf")
symbols = self.symbols
for x in symbols:
if PredictionEngine(x.historicalPERatio,x.y).predictionScore() > float(x.Price):
self.SetHoldings(security, 0.1)
print("Security")
self.Debug(security)
#self.historicalPERatio[x.Symbol]
self._changes = None
#self.Debug("asdf")
# if we have no changes, do nothing
#if self.changes == None: return
# liquidate removed securities
#for security in self._changes.RemovedSecurities:
#if security.Invested:
#for security in self.symbols:
#self.SetHoldings(security, 0.1*finalFactor)
def Rebalancing(self):
print("b")
for security in self.Portfolio.Values:
if PredictionEngine(security.historicalPERatio,security.y).predictionScore() < float(security.Price)*1.08 and security.Invested:
self.Liquidate(security.Symbol)
class PredictionEngine(object):
def __init__(self):
self.historicalPERatio = historicalPERatio
self.y = Y
def predictionScore(self):
vector_factor_direction= 0
scalar = StandardScaler()
p = 1
pe = pd.DataFrame(self.historicalPERatio)
#after this line is where I do all the magical things needed to predict prices
return predictions
Douglas Stridsberg
Hi Subarno,
Welcome to QC! Please use the Insert Code Snippet button () to insert code so that it becomes highlighted and easier to read.
I wasn't able to narrow down exactly where the error occurs, but looking at the stack trace, my hunch is that it's in one of your Universe Selection functions. The error itself likely suggests you're trying to cast something into a data type it cannot be cast to, which can happen when you're comparing, say, a string and a float. Because I don't know the return of your PredictionEngine.predictionScore() call, I can't really say what's happening.
In general, I have two pieces of advice:
Xin Wei
Hi Subarno,
The universe selection function returns a list of symbols. So, you may need to replace 'top' with '[x.Symbol for x in top]' in your coarse selection function.
Also, please post a backtest in the future so that we can better assist you.
I hope this helps.
Subarno Sen
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.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!