Hi, newbie in here. I am trying to learn proper way, so working on algorthm framework.
My question is how (and where) do we add the securities when dynamicly select them in the coarse and fine selection. I suppose it is in "OnSecuritiesChanged" in the "AlphaModel". so I am trying to do something like this
def OnSecuritiesChanged(self, algorithm, changes):
#algorithm.Debug("OnSecuritiesChanged MOMA")
if algorithm.IsWarmingUp or not changes.AddedSecurities:
return
algorithm.Debug(len(algorithm.Securities.Keys))
for security in algorithm.Securities.Keys:
algorithm.Debug("Total security list: {}".format(security.Value))
for security in algorithm.ActiveSecurities.Keys:
algorithm.Debug("Active security list: {}".format(security.Value))
for security in changes.RemovedSecurities:
algorithm.AddEquity(security.Symbol, Resolution.Daily)
if security.Invested and algorithm.Securities.ContainsKey(security.Symbol):
algorithm.Debug("Sell security {} on {}".format(symbol, security.Price) )
algorithm.Liquidate(security.Symbol)
for security in changes.AddedSecurities: #and algorithm.ContainsKey(security.Symbol).ToString():
algorithm.AddEquity(security.Symbol, Resolution.Daily)
if not security.Invested and algorithm.Securities.ContainsKey(security.Symbol):
#algorithm.Debug(algorithm.Securities)
symbol = security.Symbol
algorithm.Debug("Buy security {} on {}".format(symbol, security.Price) )
self.momen.append({"symbol":security.Symbol, "indicator":algorithm.MOM(symbol, self.period, Resolution.Daily)})
I put bunch of debug, looks like algorthm is doing some trade in the first day but in the second day it fails with
Runtime Error: This asset symbol (MA 0) was not found in your security list. Please add this security or check it exists before using it with 'Securities.ContainsKey("MA 0")' (Open Stacktrace)
I think the asset should be "MA" not sure why I have additinal space and 0 at the end.
2019-01-01 00:00:00 : Launching analysis for 53653f0387b1df4f72eae3c16862340d with LEAN Engine v2.4.0.0.8998
2019-01-01 00:00:00 : init inside try
2019-01-01 00:00:00 : course selection
2019-01-01 00:00:00 : Fine selection
2019-01-01 00:00:00 : Fine selection result: GE
2019-01-01 00:00:00 : Fine selection result: ABX
2019-01-01 00:00:00 : Fine selection result: MA
2019-01-01 00:00:00 : Fine selection result: NKE
2019-01-01 00:00:00 : Fine selection result: KO
2019-01-01 00:00:00 : Fine selection result: QCOM
2019-01-01 00:00:00 : Fine selection result: ABT
2019-01-01 00:00:00 : Fine selection result: V
2019-01-01 00:00:00 : Fine selection result: MCD
2019-01-01 00:00:00 : Fine selection result: MRK
2019-01-01 00:00:00 : 10
2019-01-01 00:00:00 : Total security list: MCD
2019-01-01 00:00:00 : Total security list: QCOM
2019-01-01 00:00:00 : Total security list: ABX
2019-01-01 00:00:00 : Total security list: V
2019-01-01 00:00:00 : Total security list: NKE
2019-01-01 00:00:00 : Total security list: KO
2019-01-01 00:00:00 : Total security list: MA
2019-01-01 00:00:00 : Total security list: ABT
2019-01-01 00:00:00 : Total security list: MRK
2019-01-01 00:00:00 : Total security list: GE
2019-01-01 00:00:00 : Active security list: MCD
2019-01-01 00:00:00 : Active security list: QCOM
2019-01-01 00:00:00 : Active security list: ABX
2019-01-01 00:00:00 : Active security list: V
2019-01-01 00:00:00 : Active security list: NKE
2019-01-01 00:00:00 : Active security list: KO
2019-01-01 00:00:00 : Active security list: MA
2019-01-01 00:00:00 : Active security list: ABT
2019-01-01 00:00:00 : Active security list: MRK
2019-01-01 00:00:00 : Active security list: GE
2019-01-01 00:00:00 : Buy security ABT on 70.260040424
2019-01-01 00:00:00 : Buy security ABX on 0.0
2019-01-01 00:00:00 : Buy security GE on 7.520964568
2019-01-01 00:00:00 : Buy security KO on 45.078274692
2019-01-01 00:00:00 : Buy security MA on 186.699524524
2019-01-01 00:00:00 : Buy security MCD on 171.166044492
2019-01-01 00:00:00 : Buy security MRK on 73.250521236
2019-01-01 00:00:00 : Buy security NKE on 72.968034489
2019-01-01 00:00:00 : Buy security QCOM on 54.02052998
2019-01-01 00:00:00 : Buy security V on 130.69033029
2019-01-01 00:00:00 : ABT, ABX on GE
2019-01-01 00:00:00 : Warning: all market orders sent using daily data, or market orders sent after hours are automatically converted into MarketOnOpen orders.
2019-01-01 00:00:00 : ABX: The security does not have an accurate price as it has not yet received a bar of data. Before placing a trade (or using SetHoldings) warm up your algorithm with SetWarmup, or use slice.Contains(symbol) to confirm the Slice object has price before using the data. Data does not necessarily all arrive at the same time so your algorithm should confirm the data is ready before using it. In live trading this can mean you do not have an active subscription to the asset class you're trying to trade. If using custom data make sure you've set the 'Value' property.
2019-01-02 10:00:00 : 10
2019-01-02 10:00:00 : Total security list: MCD
Shile Wen
Hi Emrah,
You are calling AddEquity in OnSecuritiesChanged, however, the addition and removal of securities is the responsibility of the universe selection.
I assume you are trying to buy them. For this, I suggest returning insights for each of the active securities inside the Update method of the alpha model (docs) or by using the ConstantAlphaModel.
Typically, the OnSecuritiesChanged method inside an alpha model is used to prepare indicators, e.g. RSI, for newly added symbols.
If the error still persists, please attach the full code to help us identify the problem.
Best,
Shile Wen
Wu
As a beginner, I am trying to understand how all the models work.
Could you help me understand the reason for getting the following error with FooAlphaModel?
Runtime Error: This asset symbol (JPM 0) was not found in your security list. Please add this security or check it exists before using it with 'Securities.ContainsKey("JPM 0")' (Open Stacktrace)
namespace QuantConnect { class QuadTunnelAlphaModel : IAlphaModel, INotifiedSecurityChanges { public IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice data) { List<Insight> ret = new List<Insight>(); foreach(var d in data.Values){//base data = https://www.quantconnect.com/lean/documentation/topic8710.html var symbol=d.Symbol.Value; algorithm.Debug(algorithm.Time.ToString("o") +" symbol: "+symbol+" price = "+d.Price); if(d.Price <92){ var insight = Insight.Price(symbol, TimeSpan.FromMinutes(20), InsightDirection.Up); ret.Add(insight); algorithm.Debug(algorithm.Time.ToString("o") +" added insight"); } } return ret; } public void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes) { if (changes.AddedSecurities.Count > 0) { algorithm.Debug(algorithm.Time.ToString("o") + " Securities added: " + string.Join(",", changes.AddedSecurities.Select(x => x.Symbol.Value))); } if (changes.RemovedSecurities.Count > 0) { algorithm.Debug(algorithm.Time.ToString("o") +" Securities removed: " + string.Join(",", changes.RemovedSecurities.Select(x => x.Symbol.Value))); } } } }
Shile Wen
Hi Wu,
Please attach the full algorithm so we can identify the problem.
Best,
Shile Wen
Wu
namespace QuantConnect { class QuadTunnelAlphaModel : IAlphaModel, INotifiedSecurityChanges { public int periods = 60; public IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice data) { List<Insight> ret = new List<Insight>(); foreach(var d in data.Values){//base data = https://www.quantconnect.com/lean/documentation/topic8710.html var symbol=d.Symbol.Value; algorithm.Debug(algorithm.Time.ToString("o") +" symbol: "+symbol+" price = "+d.Price); if(d.Price <92){ var insight = Insight.Price(symbol, TimeSpan.FromMinutes(20), InsightDirection.Up); ret.Add(insight); algorithm.Debug(algorithm.Time.ToString("o") +" added insight"); } } return ret; } public void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes) { if (changes.AddedSecurities.Count > 0) { algorithm.Debug(algorithm.Time.ToString("o") + " Securities added: " + string.Join(",", changes.AddedSecurities.Select(x => x.Symbol.Value))); } if (changes.RemovedSecurities.Count > 0) { algorithm.Debug(algorithm.Time.ToString("o") +" Securities removed: " + string.Join(",", changes.RemovedSecurities.Select(x => x.Symbol.Value))); } } } }
namespace QuantConnect { public class LiquidValueUniverseSelectionModel : FundamentalUniverseSelectionModel { public LiquidValueUniverseSelectionModel() : base(true, null, null) { } public override IEnumerable<Symbol> SelectCoarse(QCAlgorithm algorithm, IEnumerable<CoarseFundamental> coarse) { IEnumerable<Symbol> ret= new [] { QuantConnect.Symbol.Create("JPM", SecurityType.Equity, Market.USA) }; algorithm.Debug("selectCoarse"); return ret; } public override IEnumerable<Symbol> SelectFine(QCAlgorithm algorithm, IEnumerable<FineFundamental> fine) { IEnumerable<Symbol> ret= fine.Select(f => f.Symbol); algorithm.Debug("SelectFine"); return ret; } } }
using System.Drawing; namespace QuantConnect.Algorithm.CSharp { public class MultidimensionalUncoupledEngine: QCAlgorithm { public override void Initialize() { SetStartDate(2019, 1, 1); //Set Start Date SetEndDate(2020, 1, 15); //Set Start Date SetCash(1000); //Set Strategy Cash UniverseSettings.Resolution = Resolution.Minute; AddUniverseSelection(new LiquidValueUniverseSelectionModel()); SetAlpha(new QuadTunnelAlphaModel()); SetPortfolioConstruction( new EqualWeightingPortfolioConstructionModel() ); SetRiskManagement(new TrailingStopRiskManagementModel()); SetExecution(new ImmediateExecutionModel()); } } }
Wu
Not sure how I attach the whole project. I made a sample project to dulicate the issue and added in the comment above.
Thanks for helping.
Wu
The issue is caused by the UniverseSelectionModel class, but still not sure why this would happen. Can any1 help me understand whats missing in my UniverseSelectionModel class?
Shile Wen
Hi Wu,
When working with securities added by a Universe, we generally want to use the Symbol objects instead of ticker strings. In this case, we want to use the Symbol object for creating the Insight. I've shown this fix in the attached backtest.
Best,
Shile Wen
Wu
Thanks that helped!
Wu
Is there an explaination on why the code would even compile in webIDE.
I checked the class none of them take string. This is a HUGE issue, especially hard for webIDE.
https://github.com/QuantConnect/Lean/blob/master/Common/Algorithm/Framework/Alphas/Insight.csShile Wen
Hi Wu,
Insights can take string arguments, however, this works only for assets added by AddEquity, AddCrypto, etc. hence why there was no illegal argument error.
Best,
Shile Wen
Emrah
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!