Hi,
I can't finish the task "Tracking Security Changes", because of following error message:
Runtime Error: Error running OnEndOfAlgorithm(): Object reference not set to an instance of an object
I tried really hard to find the problem, but now I run out of ideas
Code (I'm not able to add it via backtest);
using System.Reflection;
namespace QuantConnect
{
public partial class BootCampTask : QCAlgorithm
{
public override void Initialize()
{
SetStartDate(2016, 12, 28);
SetEndDate(2017, 3, 1);
SetCash(100000);
UniverseSettings.Resolution = Resolution.Hour;
SetUniverseSelection(new MyUniverseSelectionModel());
SetAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromDays(1), 0.025, null));
SetPortfolioConstruction(new SectorWeightingPortfolioConstructionModel(Resolution.Daily));
SetExecution(new ImmediateExecutionModel());
}
}
public class MyUniverseSelectionModel : FundamentalUniverseSelectionModel
{
public MyUniverseSelectionModel()
: base(true)
{
}
public override IEnumerable<Symbol> SelectCoarse(QCAlgorithm algorithm, IEnumerable<CoarseFundamental> coarse)
{
return
(from c in coarse
where c.HasFundamentalData && c.Price > 0
orderby c.DollarVolume descending
select c.Symbol).Take(100);
}
public override IEnumerable<Symbol> SelectFine(QCAlgorithm algorithm, IEnumerable<FineFundamental> fine)
{
var technology = new List<FineFundamental>();
technology.AddRange(
(from f in fine
where f.AssetClassification.MorningstarSectorCode == MorningstarSectorCode.Technology
orderby f.MarketCap descending
select f).Take(3)
);
var financialServices = new List<FineFundamental>();
financialServices.AddRange(
(from f in fine
where f.AssetClassification.MorningstarSectorCode == MorningstarSectorCode.FinancialServices
orderby f.MarketCap descending
select f).Take(2)
);
var consumerDefensive = new List<FineFundamental>();
consumerDefensive.AddRange(
(from f in fine
where f.AssetClassification.MorningstarSectorCode == MorningstarSectorCode.ConsumerDefensive
orderby f.MarketCap descending
select f).Take(1)
);
var selection = new List<Symbol>();
selection.AddRange(technology.Select(f => f.Symbol));
selection.AddRange(financialServices.Select(f => f.Symbol));
selection.AddRange(consumerDefensive.Select(f => f.Symbol));
return selection;
}
}
public class SectorWeightingPortfolioConstructionModel : EqualWeightingPortfolioConstructionModel
{
private readonly Dictionary<int, List<Symbol>> symbolBySectorCode = new Dictionary<int, List<Symbol>>();
private readonly Dictionary<Insight, double> result = new Dictionary<Insight, double>();
private decimal sectorBuyingPower = 0;
public SectorWeightingPortfolioConstructionModel(Resolution resolution)
: base(resolution)
{
}
public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
{
foreach (var security in changes.AddedSecurities)
{
//1. When new assets are added to the universe, save the Morningstar Sector Code for each security to the variable sectorCode
var sectorCode = security.Fundamentals?.AssetClassification.MorningstarIndustryGroupCode;
//2. If there is a sectorCode and it is not in the symbolBySectorCode dictionary, save the values as a list
// and append the security symbol as the value in the symbolBySectorCode dictionary
if (sectorCode.HasValue)
{
List<Symbol> symbols;
if (!symbolBySectorCode.TryGetValue(sectorCode.Value, out symbols))
{
symbolBySectorCode[sectorCode.Value] = new List<Symbol>();
}
symbolBySectorCode[sectorCode.Value].Add(security.Symbol);
}
}
foreach (var security in changes.RemovedSecurities)
{
//3. For securities that are removed, save their MorningStar sector code to sectorCode
var sectorCode = security.Fundamentals?.AssetClassification.MorningstarIndustryGroupCode;
//4. If the saved sectorCode is in the symbolBySectorCode dictionary, remove the sectorCode.
// If the saved symbol is a value in the symbolBySectorCode dictionary, remove the symbol
if (sectorCode.HasValue)
symbolBySectorCode.Remove(sectorCode.Value);
}
// We use the super() function to avoid using the base class name explicity
base.OnSecuritiesChanged(algorithm, changes);
}
}
}
.Thx,Sven
Sven Bardos
Line 107: Should read:
symbolBySectorCode[sectorCode.Value].Remove(security.Symbol);
But still the same error.
Sven Bardos
I have resetted the lesson and removed all the non-compilable code. Same behavior.
Sven Bardos
When doing the exercise with PY I get:
45 | 18:34:27:
During the algorithm initialization, the following exception has occurred: TypeError : object.__init__() takes no parameters
at __init__
super().__init__(rebalance)
File "main.py" in main.py:line 39
TypeError : object.__init__() takes no parameters
If I look into the LEAN source code I see an error with:
SetPortfolioConstruction(new SectorWeightingPortfolioConstructionModel());
Missing parameter for SectorWeightingPortfolioConstructionModel() in file SectorWeightingFrameworkAlgorithm.cs
and SectorWeightingPortfolioConstructionModel inherits from EqualWeightingPortfolioConstructionModel which happens to be the same class that is inherited from in the exercise.
My conclusion: It's a bug.
Derek Melchin
Hi Sven,
We were unable to reproduce the errors above. To display the solution files for the bootcamp lessons, click the Solution button at the bottom of the lesson.
For further assistance with the Python bug, please attach a backtest which reproduces the error.
Best,
Derek Melchin
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.
Michael Hintz
I've got the same error! also with solution.py
Michael Hintz
https://www.quantconnect.com/backtest/150751/7859844/1f606a1c0364f2392f678bd9257380e2-log.txt
Sven Bardos
"Glad" I'm not the only one. I have tried it from time to time, but no luck for me. Don't know what's going on here.
Sven Bardos
Maybe a localization problem? Germany?
Derek Melchin
Hi all,
We've tested both the C# and Python versions of the bootcamp lesson and were not able to reproduce the issue. See the attached backtest for reference.
Best,
Derek Melchin
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.
Youssef Biaz
I have the same error, even after copy-pasting solution.py into main.py. My guess is somehow the parent EqualWeightingPortfolioConstructionModel class isn't being loaded in correctly, since it goes all the way to "object" to look for a constructor that takes an additional parameter
https://www.quantconnect.com/backtest/95558/7901161/0b1897b37ac371b06ece5fb6c66e389d-log.txt
UPDATE: btw, for those who simply want to pass the tutorial, just remove the rebalance parameter from the super().__init__() line and use its default constructor. Since the default value for rebalance is Daily anyway, it shouldn't change anything. It's probably still worthwhile to understand why this error occurs, but I'm just putting this in as a quick fix for those who want to move on (it fixed it for me)
Sven Bardos
@Youssef Biaz, yes I think your explorations fit to mine. See Comment-31346
Alexandre Catarino
Hi,
I ran both C# and Python versions of "Tracking Security Changes" lesson and I could not reproduce the issues.
For the C# case, I compared the Sven Bardos' code posted above against the solution, and the solution has the following statement at line 109. Please check out Derek's backtest, since it has the current solution.
symbolBySectorCode[sectorCode.Value].Remove(security.Symbol);
We have changed the C# lesson to accept the parameterless case:
SetPortfolioConstruction(new SectorWeightingPortfolioConstructionModel());
it was not an issue, since the lesson required the parameter.
For the Python case, I don't have a code to compare with, but I would recommend adding the following import:
from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
which is included in the solution (see attached backtest below). It was included recently by me since I had a report with the same issue. With this import, `SectorWeightingPortfolioConstructionModel` will inherit from the Python version of EWPCM instead of the C# version.
Sven Bardos
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!