Hi QuantConnect Community,
I'm enountering an issue with the CoarseSelectionFunction while running a Python code for a mean reversion high-frequency trading strategy - this applied to CBOT exchange listed futures using InteractiveBrokers on margin & using an optimizer plus insights towards trading signals.
Please find below the error message.
During the algorithm initialization, the following exception has occurred: Trying to dynamically access a method that does not exist throws a TypeError exception. To prevent the exception, ensure each parameter type matches those required by the 'method'>) method. Please checkout the API documentation. at Initialize self.SetUniverseSelection(ManualUniverseSelectionModel(self.CoarseSelectionFunction)) at Python.Runtime.PythonException.ThrowLastAsClrException() at Python.Runtime.PyObject.Invoke(PyTuple args in main.py: line 22 No method matches given arguments for .ctor: ()
I understand the error message occurrs during the initialization of the algorithm - this when calling the SetUniverseSelection method with a ManualUniverseSelectionModel object that takes a CoarseSelectionFunction method as a parameter. Also that the CoarseSelectionFunction method has a parameter type mismatch or perhaps is not implemented correctly.
Yet, I couldn't find anything in the QuantConnect documentation helpful in identifying the correct parameter types and the CoarseSelectionFunction method.
It would be great if you could please advice on how I could correct this - thank you.
Regards,
Marcello Cultrera
from datetime import timedelta
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Brokerages import *
from QuantConnect.Data import *
from QuantConnect.Data.Market import *
from QuantConnect.Orders import *
from QuantConnect.Securities import *
from QuantConnect.Algorithm.Framework.Alphas import *
from QuantConnect.Algorithm.Framework.Portfolio import *
from QuantConnect.Algorithm.Framework.Execution import *
from QuantConnect.Algorithm.Framework.Risk import *
from QuantConnect.Algorithm.Framework.Selection import *
from QuantConnect.Optimizer import *
class MeanReversionAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2022, 1, 1)
self.SetEndDate(2022, 1, 31)
self.SetCash(100000)
self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin)
self.SetUniverseSelection(ManualUniverseSelectionModel(self.CoarseSelectionFunction))
self.UniverseSettings.Resolution = Resolution.Minute
self.SetAlpha(MeanReversionAlphaModel())
self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel())
self.SetExecution(ImmediateExecutionModel())
self.SetRiskManagement(MaximumDrawdownPercentPerSecurity(0.01))
# Set up the optimizer
self.optimizer = PortfolioOptimizer(self)
self.optimizer.Settings.TargetPercentage = 0.1
self.optimizer.Settings.MaximumSharpeRatio = 2
self.optimizer.Settings.MaximumDrawdown = 0.05
self.optimizer.Settings.MaximumPortfolioTurnover = 0.05
self.optimizer.Settings.MaximumAllocation = 0.2
self.optimizer.Settings.MinimumAllocation = -0.2
self.optimizer.Settings.MaximumShortAllocation = -0.1
self.optimizer.Settings.MaximumLongAllocation = 0.1
def CoarseSelectionFunction(self, coarse):
symbols = ["ZC", "ZS", "ZW"]
return [Symbol.Create(x, SecurityType.Future, Market.CBOT) for x in symbols]
class MeanReversionAlphaModel(AlphaModel):
def __init__(self, lookback=20):
self.lookback = lookback
self.symbolDataBySymbol = {}
def Update(self, algorithm, data):
insights = []
for symbol, symbolData in self.symbolDataBySymbol.items():
if not data.Bars.ContainsKey(symbol) or not symbolData.IsReady:
continue
price = data.Bars[symbol].Close
symbolData.Update(price)
if symbolData.IsOversold():
insights.append(Insight.Price(symbol, timedelta(minutes=1), InsightDirection.Up))
elif symbolData.IsOverbought():
insights.append(Insight.Price(symbol, timedelta(minutes=1), InsightDirection.Down))
return insights
def OnSecuritiesChanged(self, algorithm, changes):
for security in changes.RemovedSecurities:
symbolData = self.symbolDataBySymbol.pop(security.Symbol, None)
if symbolData is not None:
symbolData.Dispose()
addedSymbols = [x.Symbol for x in changes.AddedSecurities if x.Symbol not in self.symbolDataBySymbol]
history = algorithm.History(addedSymbols, self.lookback, Resolution.Minute)
for symbol in addedSymbols:
symbolData = SymbolData(symbol, self.lookback, history)
self.symbolDataBySymbol[symbol] = symbolData
class SymbolData:
def __init__(self, symbol, lookback, history):
self.symbol = symbol
self.lookback = lookback
self.history = history
self.IsReady = False
def Update(self, price):
self.prices.append(price)
if len(self.prices) > self.lookback:
self.prices.pop(0)
self.IsReady = True
def IsOversold(self):
if not self.IsReady:
return False
return self.prices[-1] < np.mean(self.prices) - 2 * np.std(self.prices)
def IsOverbought(self):
if not self.IsReady:
return False
return self.prices[-1] > np.mean(self.prices) + 2 * np.std(self.prices)
def Dispose(self):
pass
def Optimize(self):
self.optimizer.Optimize(self.PortfolioConstructionModel, self.alphaModel, self.riskManagementModel)
MARCELLO CULTRERA
Just realised the BrokerageName.InteractiveBrokers brokerage model is only available for live trading & not for backtesting unless there's a paid subscription with QuantConnect to access Interactive Brokers data during backtests.
MARCELLO CULTRERA
Added symbols switching from the ManualUniverseSelectionModel object taking a CoarseSelectionFunction method as a parameter towards defining instead the futures contract symbols for the second and third contract months (as a reference).
self.contract_months = [2, 3]
self.symbol = "ZS" # CBOT Soybean Oil futures symbol
Now as the strategy is finally initialised - the Algorithm Id:(2eaa47598e9e780d879e3b43f72911eb) completed in 0.32 seconds at 0k data points per second. Processing total of 147 data points.
69
|
6:55:10
:
Initializing algorithm...
70
|
6:55:10
:
Launching analysis for 2eaa47598e9e780d879e3b43f72911eb with LEAN Engine v2.5.0.0.15593
71
|
6:55:10
:
Algorithm '2eaa47598e9e780d879e3b43f72911eb' completed
72
|
6:55:10
:
Algorithm Id:(2eaa47598e9e780d879e3b43f72911eb) completed in 0.32 seconds at 0k data points per second. Processing total of 147 data points.
73
|
6:55:11
:
Backtest deployed in 7.184 seconds
74
|
6:58:51
:
Built project 'Trend Following HFT' in Cloud for Lean Engine 2.5.0.0.15593, with Id '30abb5-f0e5b2'
MARCELLO CULTRERA
# Add symbols to the universe
self.symbol = 'ZL' # CBOT Soybean Oil futures symbol
# self.AddFutureContract(Futures.Grains.SoybeanOil, timedelta(days=30))
# self.symbol = self.AddFutureContract(Futures.Grains.SoybeanOil, timedelta(days=60))
Yet no data. Much appreciated if someone could share some advice on what's missing.
MARCELLO CULTRERA
Completed in 2.02 seconds at 84k data points per second. Processing a total of 168,390 data points.
Yet - no data.
|
12:44:18
:
Launching analysis for 632ae3d5e91504fb1e32b32d96590f02 with LEAN Engine v2.5.0.0.15593
23
|
12:44:18
:
Algorithm '632ae3d5e91504fb1e32b32d96590f02' completed
24
|
12:44:18
:
Algorithm Id:(632ae3d5e91504fb1e32b32d96590f02) completed in 2.02 seconds at 84k data points per second. Processing total of 168,390 data points.
25
|
12:44:24
:
Backtest deployed in 13.067 seconds
Louis Szeto
Hi MARCELLO
ManualUniverseSelectionModel is not meant to pick up canonical symbols like Future and Option (the class not the particular contract). Check out this example on how to select Futures, and this example on selecting both Futures and Equity.
Best
Louis
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.
MARCELLO CULTRERA
Thank you Louis!
MARCELLO CULTRERA
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!