Back

Trying to get pandas dataframe of historical prices from universe

Hi,

I'm trying to get a pandas dataframe of historical prices for the last year from my universe. 

Right now I'm getting the error: 

During the algorithm initialization, the following exception has occurred: Framework algorithms must specify a portfolio selection model using the 'UniverseSelection' property.

How would I fix this?

Some other questions I have are:

How would I get historical prices from the Universe?

Could I filter based on historical prices in the fine selection function?

 

Here is what I have so far.

from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Orders import *
from QuantConnect.Algorithm import *
from QuantConnect.Algorithm.Framework import *
from QuantConnect.Algorithm.Framework.Alphas import *
from QuantConnect.Algorithm.Framework.Portfolio import *
from QuantConnect.Algorithm.Framework.Selection import *
from datetime import datetime, timedelta

class HistoricalPriceUniverse(QCAlgorithmFramework):

def Initialize(self):

self.UniverseSettings.Resolution = Resolution.Daily

self.SetStartDate(2017, 1, 1)
self.SetEndDate(2017, 2, 1)

self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)

self._changes = None

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

def FineSelectionFunction(self, fine):
# for possible future implimentation
return fine

def OnData(self, data):
# liquidate securities that were removed from universe
for security in self._changes.RemovedSecurities:
self.Liquidate(security.symbol)

# This is where I would like to get dataframe of historical prices for securities
self.Debug(Portfolio.keys)

self._changes = none

# this event fires whenever we have changes to our universe
def OnSecuritiesChanged(self, changes):
self._changes = changes
self.Log(f"OnSecuritiesChanged({self.UtcTime}):: {changes}")

 

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.


Hi,

When using a Framework Algorithm, you need to specify specific models for each aspect -- Universe Selection, Alpha Model, Portfolio Construction, Execution Model, and Risk Management, and so for these algorithms, using self.AddUniverse() won't work. If you want to use Coarse/Fine Universe selection, then you'd want to employ the FineFundamentalSelectionModel. You can see the basic implementation of this in the code I've attached below.

class BasicTemplateFrameworkAlgorithm(QCAlgorithmFramework):

def Initialize(self):

# Set requested data resolution
self.UniverseSettings.Resolution = Resolution.Minute

self.SetStartDate(2018, 9, 27) #Set Start Date
self.SetEndDate(2019, 3, 27) #Set End Date
self.SetCash(100000) #Set Strategy Cash

self.__numberOfSymbols = 100
self.__numberOfSymbolsFine = 5
self.SetUniverseSelection(FineFundamentalUniverseSelectionModel(self.CoarseSelectionFunction, self.FineSelectionFunction, None, None))

self.SetAlpha(NullAlphaModel())

self.SetPortfolioConstruction(NullPortfolioConstructionModel())

self.SetExecution(NullExecutionModel())

self.SetRiskManagement(NullRiskManagementModel())


# sort the data by daily dollar volume and take the top 'NumberOfSymbols'
def CoarseSelectionFunction(self, coarse):
# sort descending by daily dollar volume
sortedByDollarVolume = sorted(coarse, key=lambda x: x.DollarVolume, reverse=True)

# return the symbol objects of the top entries from our sorted collection
return [ x.Symbol for x in sortedByDollarVolume[:self.__numberOfSymbols] ]

# sort the data by P/E ratio and take the top 'NumberOfSymbolsFine'
def FineSelectionFunction(self, fine):
# sort descending by P/E ratio
sortedByPeRatio = sorted(fine, key=lambda x: x.ValuationRatios.PERatio, reverse=True)

# take the top entries from our sorted collection
return [ x.Symbol for x in sortedByPeRatio[:self.__numberOfSymbolsFine] ]


def OnOrderEvent(self, orderEvent):
if orderEvent.Status == OrderStatus.Filled:
# self.Debug("Purchased Stock: {0}".format(orderEvent.Symbol))
pass

 

1

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