Back

Average true range on five-second bars

Hello everyone,

my current algorithm is working with five-second bars consolidated from second resolution data. Now I'd like to use an average true range for the five-second bars of the last minute. If I use

self.atr_five_sec[symbol] = self.ATR(symbol, 60, MovingAverageType.Simple, Resolution.Second)

I get a different average true range based on one-second bars. I would need something like

self.atr_five_sec[symbol] = self.ATR(symbol, 12, MovingAverageType.Simple, Resolution.FiveSecond)

but that is not working of course as there is no five-second resolution. How is this being done correctly?

Kind regards,

Christian Lauer

Update Backtest







use the 5 seconds bar as input to create a 5 sec atr indicator

don't bind it to a stock just create it and call the update method:

 

https://www.quantconnect.com/forum/discussion/3342/williamspercentr-for-5-minute-bars/p1/comment-10173
0

Hello Michael,

thank you for your answer. I don't succeed in creating the indicator by mysef like in those examples though. There, only one rolling window is used for tradebars and the indicator is then made from them. In my algorithm I need rolling windows for five-second and five-minute bars (and maybe also one-minute) so I can't just copy the example. I can't use def __init__(self, symbol, barPeriod, windowSize) in my symbolData class as I only need those parameters for that one rolling window of the indicator and not for the others. So I tried to create the indicator like in the example and then bind it to the stocks like usually but that is not working as you said. Here's a simplified version of my algorithm showing how I tried to do it:

from QuantConnect.Data.Market import *
from QuantConnect.Data.Consolidators import *
from datetime import *
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
import decimal as d
import operator


class MyAlgorithm(QCAlgorithm):

def Initialize(self):
self.SetStartDate(2017, 3, 1)
self.SetEndDate(2017, 3, 5)
self.SetCash(100000)

self.symbolData = dict()
self.atr = dict()
self.atr_five_sec = dict()

FiveSecondATRPeriod = 5
RollingWindowSize = 5


EquitySymbols = ["SPY", "SCHW", "SPGI", "AER"]

for ticker in EquitySymbols:

symbol = self.AddEquity(ticker, Resolution.Second).Symbol

consolidator_fiveminute = TradeBarConsolidator(300)
consolidator_fiveminute.DataConsolidated += self.OnFiveMinuteData
self.SubscriptionManager.AddConsolidator(symbol, consolidator_fiveminute)

consolidator_fivesecond = TradeBarConsolidator(5)
consolidator_fivesecond.DataConsolidated += self.OnFiveSecondData
self.SubscriptionManager.AddConsolidator(symbol, consolidator_fivesecond)

self.symbolData[symbol] = SymbolData()

self.atr[symbol] = self.ATR(symbol, 14, MovingAverageType.Simple, Resolution.Daily)

self.atr_five_sec[symbol]= AverageTrueRange(self.CreateIndicatorName(symbol, "atr_five_sec" + str(FiveSecondATRPeriod), Resolution.Second),FiveSecondATRPeriod)

self.Schedule.On(self.DateRules.EveryDay(),
self.TimeRules.At(9, 35, 2),
Action(self.shortly_after_open_market))

def OnFiveMinuteData(self, sender, bar):
self.symbolData[bar.Symbol].fiveminute_rw.Add(bar)

def OnFiveSecondData(self, sender, bar):
self.symbolData[bar.Symbol].fivesecond_rw.Add(bar)
self.symbolData[bar.Symbol.Value].atr_five_sec.Update(bar.Time, bar.Close)

def shortly_after_open_market(self):

for symbol in self.symbolData:
if (self.Securities[symbol].Exchange.ExchangeOpen
):
if self.atr_five_sec[symbol].IsReady:
self.Log(str(symbol)+str(self.atr_five_sec[symbol].Current.Value))

def OnData(self, data):

for symbol in data.Keys:

if data[symbol] is None: continue
window = self.symbolData[symbol].window
window.Add(data[symbol])

class SymbolData(object):

def __init__(self):
self.fivesecond_rw = RollingWindow[TradeBar](2)
self.fiveminute_rw = RollingWindow[TradeBar](79)
self.window = RollingWindow[TradeBar](1)
self.atr_five_sec = None

Kind regards,

Christian

0

I'm still stuck here, so I'd appreciate someone's help!

0

oh hi

sorry i have overseen this.

my guess is that register indicator does not work with ATR indicator.

someone can correct me but you have to do it manually like you are trying to already:

self.symbolData[bar.Symbol.Value].atr_five_sec.Update(bar.Time, bar.Close)

also this line seems to be wrong because it takes a BAR not the close and time.

(that is why i send you that example above: williams R takes also a BAR as input to update that indicator:

self.Data[bar.Symbol.Value].WilliamsPercentR.Update(bar))The documentation says:var atr = ATR(Symbol symbol, int period, MovingAverageType type = null, Resolution resolution = null, Func`2[Data.IBaseData,Data.Market.IBaseDataBar] selector = null)

When you search in the GITHUB respository for ATR you get an example how they test the ATR indicator:

atr comment in the python example

( # ATR and AROON are special in that they accept a TradeBar instance instead of a decimal, we could easily project and/or transform the input TradeBar ) 

0

the thing you are trying to achieve is to combine the following examples together:

1) starting with multiple symbols sample algo

https://github.com/QuantConnect/Lean/blob/master/Algorithm.Python/MultipleSymbolConsolidationAlgorithm.py

2) consolidate second resolution to minute and 5 minute like in this example from minute to 30 minutes to one day to 3 days.

https://github.com/QuantConnect/Lean/blob/master/Algorithm.Python/DataConsolidationAlgorithm.py

3) using symbolclass to hold the stock informations like indicator and windows, init section with consolidator

https://github.com/QuantConnect/Lean/blob/3b8273c079ec47615556ba4b0329113179a6f61a/Algorithm.Framework/Alphas/MacdAlphaModel.py

again i dont believe that register indicator works with ATR maybe i am wrong but i would to it manually like in my williams R example above so i know where and when something happens.

0

Thank you for your answers, Michael. These examples don't help me that much though as I think that my basic structure is already working fine and the only issue is to make the indicator fit into it. Here, I can't just do it as in your WilliamsR example as I tried to explain above. So I corrected the line you mentioned in my code but I still get an error:

Runtime Error: Trying to retrieve an element from a collection using a key that does not exist in that collection throws a KeyError exception. To prevent the exception, ensure that the SPY key exist in the collection and/or that collection is not empty.
at OnFiveSecondData in main.py:line 56
KeyError : ('SPY',) (Open Stacktrace)

 

Kind regards,

Christian

0

hmm keyerror.

are you trying to access a dictionary with SPY as a key?

try something like that maybe:

https://github.com/QuantConnect/Lean/blob/cbd953437f987392f2c2e154adcb7d43d684b7f1/Algorithm.Python/DailyAlgorithm.py#L54

 

if not self.macd.IsReady: returnif not data.ContainsKey("IBM"): return

the thing is that if you would get to this line of code you mentioned that you changed .... it would get a runtime error at this line because the update method was wrong. your algo dies somewhere before this line.

last thing i can offer you is that you can share your algo with me and i can take a look on it. later you can delete me from the list of people sharing the algo with

this keyerror message is something for stackoverflow or google it.

its a python dictionary error message.

0

Update Backtest





0

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.


Loading...

This discussion is closed