Hi,
I am relatively new to Quantconnect and I am trying to familiarize myself with the ecosystem. I am trying to start with a basic algorithm to get a feel for the framework of an algorithm on this platform and I am a bit confused regarding Insights used in the AlphaModel and PortfolioCreationModel, particularly the Direction property. The documentation is self explanatory in regards to directional signals, but I am unsure how to construct a sginal that will signify an action regardless of which direction I think a symbol will go. Does anyone have any advice for how to create a signal like this?
For example, lets say I want to rebalance a portfolio when there is a drawdown of 10% or more in SPY. If there is a drawdown of 10% or more, then rebalance the portfolio to a predefined weighting (for the sake of example, lets make it 60/40 SPY/TLT). Due to me not understansing the AlphaModel framework, I simply added the logic to the OnData event handler.
class TestAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2019, 1, 1)
self.SetEndDate(2020, 4, 1)
self.SetCash(10000)
symbols = [
Symbol.Create("SPY", SecurityType.Equity, Market.USA),
Symbol.Create("TLT", SecurityType.Equity, Market.USA)]
self.UniverseSettings.Resolution = Resolution.Daily
self.SetUniverseSelection(ManualUniverseSelectionModel(symbols))
def OnData(self, data):
self.highest_high = self.MAX("SPY", 253, Resolution.Daily, Field.High)
self.latest_close = data["SPY"].Close
drawdown = (self.latest_close - self.highest_high) / self.highest_high
if drawdown < -0.10:
self.Log("SPY drawdown is greater than 10%. Rebalancing portfolio")
# rebalance
...
Kyle sn
So jumped the gun on that question as it turns out I was not finished going through Boot Camp lessons. I learned that I was confusing Insights with Indicators. As a result, I think I undserstand the framework better. I am still having an issue making an indicator work.
from clr import AddReference AddReference("System") AddReference("QuantConnect.Algorithm") AddReference("QuantConnect.Common") from System import * from QuantConnect import * from QuantConnect.Algorithm import * import numpy as np class FrameworkAlgorithm(QCAlgorithm): def Initialize(self): self.SetStartDate(2019, 1, 1) self.SetEndDate(2020, 4, 13) self.SetCash(10000) self.spy = self.AddEquity("SPY", Resolution.Daily) self.tlt = self.AddEquity("TLT", Resolution.Daily) self.SetWarmup(timedelta(252)) def OnData(self, data): #self.highest_high = self.MAX("SPY", 252, Resolution.Daily, Field.High) self.highest_high = np.nanmax(self.spy.Close) self.latest_close = self.spy.Close if self.highest_high: self.drawdown = (self.latest_close - self.highest_high) / self.highest_high self.Log("Drawdown: {}".format(self.drawdown)) if not self.Portfolio.Invested: self.SetHoldings("SPY", 0.60) self.SetHoldings("TLT", 0.40) if self.drawdown < -0.10: self.Log("SPY drawdown is greater than 10%. Rebalancing portfolio") self.SetHoldings("SPY", 0.60) self.SetHoldings("TLT", 0.40) ################### ##### LOGGING ##### ################### for sec in data.Bars: symbol = sec.Key if data.Dividends.ContainsKey(symbol): dividend = data.Dividends[symbol] self.Log(f"{self.Time} >> DIVIDEND >> {dividend.Symbol} - {dividend.Distribution} - {self.Portfolio.Cash} - {self.Portfolio[symbol].Price}") def OnEndOfAlgorithm(self): self.Log("{} - TotalPortfolioValue: {}".format(self.Time, self.Portfolio.TotalPortfolioValue)) self.Log("{} - CashBook: {}".format(self.Time, self.Portfolio.CashBook))
Apologies for not knowing how to attach a research notebook, but the below code is from the research environment and it successfully calculates the drawdown. Why does the drawdown calculation work in the research notebookbut not in the algorithm?
spy = qb.AddEquity("SPY", Resolution.Daily) hist = qb.History(["SPY"], 252, Resolution.Daily) close = hist["close"] latest_close = close[-1] print(f"Latest close is: {latest_close}") highest_high = np.nanmax(close) print(f"Highest high is: {highest_high}") drawdown = (latest_close - highest_high) / highest_high print(f"The current SPY drawdown is: {drawdown}")
Derek Melchin
Hi Kyle Unknown,
The drawdown calculation isn’t working in the backtester because the algorithm doesn’t calculate `self.highest_high` correctly. See the attached algorithm for an example on how we can implement this efficiently using the MAX indicator.
As a rule of thumb, indicators should be created in Initialize instead of in OnData. In the example attached below, during OnData, we merely check the current value of the MAX indicator over the trailing 252 trading days. It should also be pointed out that we need to warm up our indicators before using them. We can create the MAX indicator and configure its warm up in Initialize like this:
# Setup highest high indicator
lookback = 252
self.highest_high = self.MAX(self.spy, lookback, Resolution.Daily, Field.High)
self.SetWarmup(lookback, Resolution.Daily)
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.
Kyle sn
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!