Coarse Selection Function

Having trouble with the course selection function in my algorithm

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

This line of code in my algorithm results in an error code

Update Backtest

That code should work. It needs to be placed in the 'Initialize' method. Ensure you have defined the two functions 'CoarseSelectionFunction' and 'FineSelectionFunction' (you can use whatever names you like actually). Also ensure the two functions return a python list of security symbols.

Attached is a python algorithm that creates a universe. It may give you some ideas on how to debug yuor code?

Good luck.


Really basic question along with some code that would break. What changes would be needed to log price on ordering something like this?

for s in context.universe:
context.Log(' {} {} {}'.format(s, s.Price, weight))
context.SetHoldings(s, weight)

This fixes that item but needs more help. Several questions:

This line seems to make two universes:

context.AddUniverse(context.universe_filter_coarse, context.universe_filter_fine)

... as "universe count: {}" would print two lines.

I'd prefer to be working with 1 universe. To attempt to resolve that, I wanted to define data_df one time and then just be merely populating values, while filtering for the given price range.

There's an error:

" Runtime Error: Specified cast is not valid."

I can't provide a line number.

Appreciate any help!

from QuantConnect.Data.UniverseSelection import *
import pandas as pd
num = 9
data_df = pd.DataFrame(index=[], columns=['Price', 'DollarVolume', 'HasFundamentalData', 'Volume', 'EVToEBITDA'])

class BasicTemplateAlgorithm(QCAlgorithm):
def universe_filter_fine(context, fine_data):
data_df['EVToEBITDA'] = fine_data.ValuationRatios.EVToEBITDA
#for s in fine_data:
# data_df.loc[s, 'EVToEBITDA'] = fine_data[s].ValuationRatios.EVToEBITDA
#context.Log("data is: {}".format(data_df.EVToEBITDA.values))
context.universe = data_df.index.tolist()
#context.Log("fine size is: {}".format(len(context.universe)))
return context.universe

def universe_filter_coarse(context, coarse_data):
# With data_df already initialized globally, this should now just
# populate securities for values matching query instead.
columns = ['Price', 'DollarVolume', 'HasFundamentalData', 'Volume']
column_names = ['price', 'dollar_volume', 'has_fundamentals', 'volume']
data_df = pd.DataFrame.from_records(
[[getattr(s, name) for name in columns] for s in coarse_data],
index=[s for s in coarse_data],
universe = (data_df.
query("(price > 8.0) and (price < 11.0) and has_fundamentals").nsmallest(num, 'price')
#nlargest(num, 'dollar_volume'),
context.Log("coarse size is: {}".format(len(universe)))
context.Log('prc min {} max {}'.format(universe.price.min(), universe.price.max()))
#context.Log(universe.sort_values(by='price', ascending=False).head())
#context.Log(universe.sort_values(by='price', ascending=False).tail())
return universe.index.tolist()

def Initialize(context):
context.universe = []

# Set the initial cash, start, and end dates for backtesting
context.SetStartDate(2011,5, 5)
context.SetEndDate (2011,5,10)

# Subscribe to data for securities returned in universe
context.UniverseSettings.Resolution = Resolution.Daily
context.UniverseSettings.MinimumTimeInUniverse = 0
context.AddUniverse(context.universe_filter_coarse, context.universe_filter_fine)
context.Schedule.On( # Schedule the 'trade' method to run
context.TimeRules.At(9, 30), # market open?

def trade(context):
#for u in context.UniverseManager.Keys:
# context.Log("universe name: {}".format(u))
for u in context.UniverseManager.Values:
context.Log("universe count: {}".format(u.Members.Count))

weight = 1.0 / len(context.universe) if len(context.universe) > 0 else 0.0
context.Log('weight ' + '%.4f' % weight)
for s in context.universe:
if not context.Securities.ContainsKey(s): continue
context.Log(' {} {}'.format(s, '%.2f' % context.Securities[s].Price))
context.SetHoldings(s, weight)

i looked at it for few minutes and i dont know the error for sure but! ich think it is line 34:

return universe.index.tolist()

please clone similar algos that work and change it to your needs.
I replaced your "universe_filter_coarse(context, coarse_data):"  with something from the community and it died later in
""universe_filter_fine" with 

 object has no attribute 'ValuationRatios'


clone Jings algo and adapt it or take something different:





yep it does not enter the


but replacing your


it dies there littlebit later


Thanks for your reply and the great example. I would just wind up breaking Jing's code in order to ask the same question.

To use the platform I'll need to understand something, the basics of how coarse and fine work.
I want to understand rather than to just avoid errors.
To illustrate, I'll try to simplify. The backtest here is mostly error-free with both included, however if use_fine_filter on line 4 is set to 0 there are no orders. Why is that? I dug around and didn't find the answer, maybe I simply missed a great page on it.

The backtest morphed from Dan Whitnable's code above. This is a small start toward my goal of adapting this from Q to QC ...


Update Backtest


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.


This discussion is closed