Hi everyone, I'm trying to calculate volatility by dividing ATR by the stock's price, but I keep getting the error that I can't divide AverageTrueRange Object by float. The relevant code and the whole program is attached below. Thanks to anyone who can help!
for ticker in symbols:
self.AddEquity(ticker, Resolution.Minute)
self.tickers[ticker] = self.ATR(ticker, 14, MovingAverageType.Simple, Resolution.Minute)/self.Securities[ticker].Price
class EmotionalFluorescentPinkSalmon(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2018, 1, 1)
self.SetEndDate(2021, 11, 1)
self.SetCash(100000)
self.tickers = {}
symbols = ["AMZN", "MSFT", "AAPL"]
for ticker in symbols:
self.AddEquity(ticker, Resolution.Minute)
self.tickers[ticker] = self.ATR(ticker, 14, MovingAverageType.Simple, Resolution.Minute)/self.Securities[ticker].Price
self.tickers = {k: v for k, v in sorted(self.tickers.items(), key=lambda item: item[1], reverse=True)[:1]}
self.portfolio_targets = []
for stock, volt in self.tickers.items():
self.stock = self.AddEquity(stock, Resolution.Minute).Symbol
self.portfolio_targets.append(self.stock)
self.spy = self.AddEquity("SPY", Resolution.Minute).Symbol
self.SetWarmUp(1, Resolution.Daily)
self.yest_close = self.SMA(self.spy, 1, Resolution.Daily, Field.Close)
"""
Figure out universe selection error
"""
def OnData(self, data):
if self.IsWarmingUp or not self.yest_close.IsReady or not len(data.Bars) > 0:
return
# If SPY is above yesterday's close at 9:45, go long all stocks in ticker_symbols
if self.Time.hour == 9 and self.Time.minute == 45:
for stock in self.portfolio_targets:
price = self.Securities[self.spy].Price
yest_close = self.yest_close.Current.Value
if price < yest_close:
self.SetHoldings(stock, 1/len(self.portfolio_targets))
if self.Time.hour == 15 and self.Time.minute == 45:
self.Liquidate()
Vladimir
Arsal Khan
Try to replace
self.tickers[ticker]=self.ATR(ticker,14,MovingAverageType.Simple, Resolution.Minute)/self.Securities[ticker].Price
by
self.tickers[ticker]=IndicatorExtensions.Over(self.ATR(ticker,14,MovingAverageType.Simple, Resolution.Minute), self.prices[ticker] )
If you are satisfied with my answer, please accept it.
Vladimir
Correction
Try to replace
self.tickers[ticker]=self.ATR(ticker,14,MovingAverageType.Simple, Resolution.Minute)/self.Securities[ticker].Price
by
self.tickers[ticker]=IndicatorExtensions.Over(self.ATR(ticker,14,MovingAverageType.Simple, Resolution.Minute), self.Securities[ticker].Price)
Vladimir
Arsal Khan,
unfortunately I found that IndicatorExtensions.Over() not working properly with self.ATR().
Here is another solution for your setup.
Louis Szeto
Hi Arsal, Vladimir
Using instant price self.Security[symbol].Price in IndicatorExtension.Over would result in dividing a constant rather than the previous day's close. We suggest using self.Identity indicator in Daily resolution to replace that and self.SMA(1). Please check the attached backtest as an example.
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.
Vladimir
Louis Szeto
Thanks for suggestion.
Your version of the code definitely faster (22.55 sec) compared to (56.17 sec) my last version, but it seems to me like my first version it does not switch symbols.
I think that IndicatorExtensions.Over() not working properly with self.ATR().
What would you improve in my latest version?
Vladimir
Louis Szeto,
How to call in OnData() self.atrOverPrice you created in symbolData?
So far, the two ways I have used to get the normalized ATR are identical.
Louis Szeto
Hi Vladimir
For your first reply, self.atr_norm values are calculated by instant price by minute data. So the values differ from the indicator. And your second reply has already proved self.ATR is compatible with IndicatorExtension.
We can access self.atrOverPrice property by calling
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.
Vladimir
I created the "Four Ways to Get Normalized ATR" algorithm.
The results of all four methods are absolutely identical.
The speed of the first three (atr_norm_1, atr_norm_2, atr_norm_3) is very similar
in the range (0.61 sec - 0.64 sec).
The speed of the pure pythonic version (atr_norm_4) is about 4.5 times slower (2.77 sec).
Alexandre Catarino
Hi Vladimir ,
Thank you for the benchmark. It's valuable information for the community.
To summarize, the pure pythonic version (atr_norm_4) requires a historical data request. In Python algorithms, the History method returns a pandas Dataframe, since it's a handy format requested by the community when we added support to Python. However, it has additional computational costs and is consequently slower. The Lean indicators are updated and computed by the C# engine and are faster.
Arsal Khan
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!