Back

Python: indicator on multiple timeframe - default registration causes an issue

My intention is to look at the same indicator (Ichimoku) on different time frames.

I'm writing a strategy in Python and came across the following blocker:

Here is the code:

def Initialize(self):
instr = "AUDJPY"
self.SetStartDate(DateTime(2017, 01, 01))
self.SetEndDate(datetime.now() - timedelta(1))          
symbol = self.AddForex(instr).Symbol
fourHourConsolidator = QuoteBarConsolidator(timedelta(minutes=240))
fourHourConsolidator.DataConsolidated += self.FourHourBarHandler
self.SubscriptionManager.AddConsolidator(instr, fourHourConsolidator)
self.fourHourIchimoku = self.ICHIMOKU(instr, 9, 26, 26, 52, 26, 26)  # the indicator is automatically registered with the default resolution
self.RegisterIndicator(symbol, self.fourHourIchimoku, fourHourConsolidator, None) # this will cause Update to be called after 240 min and will fail.

And after the first 239 minutes, the backtest fails:

2017-01-03 01:00:00 Runtime Error: System.ArgumentException: This is a forward only indicator: ICHIMOKU(9,26)(AUDJPY_min) Input: 2017-01-03 00:00:00Z Previous: 2017-01-03 00:58:00Z

The reason being: Algorithm\QCAlgorithm.Indicators.cs, line 430 the indicator is automatically registered with the default resolution (1 min). Hence once the 240 minutes are reached, Update is called a second time and because the time of the consolidated 240 minutes bar equals the time of the very first minute, it fails on line 77 \Indicators\IndicatorBase.cs

Is there a work around? Instantiating an indicator without having it registered? In C#, I could invoke the constructor directly... 

Thanks,

Jerome

Update Backtest






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.



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.


Yes, you should invoke the constructor directly and then register it:

self.fourHourIchimoku = IchimokuKinkoHyo("", 9, 26, 26, 52, 26, 26)
self.RegisterIndicator(symbol, self.fourHourIchimoku, fourHourConsolidator, None)

 

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.


Hi Alexandre, 

Thanks for your answer. But that's my point: the indicator class hasn't been made available to python. So if I use the suggested syntax I get a 

Algorithm.Initialize() Error: Loader.TryCreatePythonAlgorithm(): Unable to import python module

 

 

0

Could you please try to re-run your algorithm?
We couldn't reproduce that issue. 
Please checkout the attached 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.


Hi Alexandre, thanks again for taking the time around this. I pasted your code in my project and it works! For information, I took my template directly from the github repo and it adds loads of imports and reference, without investigating further, I assume this causes the issue.

link to DataConsolidationAlgorithm.py

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

from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Indicators")
AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
from QuantConnect.Data.Market import *
from QuantConnect.Data.Consolidators import *

 

0

I've been trying to do something similar but within coarse selection, on multiple symbols -- I have been getting random errors.  I'll attach my code:  It runs, however the values are straight 0's when debugged.

 

class BB():
'''15M BBs'''
def __init__(self,symbol, algorithm, history):
self.BB = BollingerBands(20,2, MovingAverageType.Simple) 

self.symbol = symbol
algorithm.AddEquity(self.symbol) #?? Error message indicated I needed to have symbols added... This seems wrong tho
self.consolidator = TradeBarConsolidator(timedelta(minutes=15))
algorithm.RegisterIndicator(symbol, self.BB, self.consolidator)

self.ub = self.BB.UpperBand
self.lb = self.BB.LowerBand

#MA Cons (NEW)
self.MA = SimpleMovingAverage(12)
self.ma_cons = TradeBarConsolidator(timedelta(days=1))
algorithm.RegisterIndicator(symbol, self.MA, self.ma_cons)


#Register / Subscribe to event Don't think this is needed? ^^ that is register
self.consolidator.DataConsolidated += self.OnDataConsolidated
'''Unhid this and OnDataConsolidated'''

#Didn't think I needed this, now I'm not sure?
def OnDataConsolidated(self, sender, bar):
#Assume this would be updated w tradebars?
#self.window.Add(bar.Close)
self.BB.Update(bar.EndTime, bar.Close)
self.MA.Update(bar.EndTime, bar.Close)
if self.BB.IsReady: #Do I need to do this manually?
self.ub = self.BB.UpperBand
self.lb = self.BB.LowerBand
self.MA = self.MA

 

 

0

class BB():
'''15M BBs'''
def __init__(self,symbol, algorithm, history):
self.BB = BollingerBands(20,2, MovingAverageType.Simple) #UltimateOscillator(9, 15, 24)
self.symbol = symbol
algorithm.AddEquity(self.symbol) #?? Doesn't look right, but error said I needed to add?
self.consolidator = TradeBarConsolidator(timedelta(minutes=15))
algorithm.RegisterIndicator(symbol, self.BB, self.consolidator)

self.ub = self.BB.UpperBand
self.lb = self.BB.LowerBand

#MA Cons (NEW)
self.MA = SimpleMovingAverage(12)
self.ma_cons = TradeBarConsolidator(timedelta(days=1))
algorithm.RegisterIndicator(symbol, self.MA, self.ma_cons)

#Register / Subscribe to event Don't think this is needed? ^^ that is register
self.consolidator.DataConsolidated += self.OnDataConsolidated
#Unhid OnDataConsolidated

#Didn't think I needed this, now I'm not so sure.
def OnDataConsolidated(self, sender, bar):
#Must use tradebar to update?
#self.window.Add(bar.Close)
self.BB.Update(bar.EndTime, bar.Close)
self.MA.Update(bar.EndTime, bar.Close)
if self.BB.IsReady: #Do I need to do this manually?
self.ub = self.BB.UpperBand
self.lb = self.BB.LowerBand
self.MA = self.MA

The other post's formatting got messed up -- here we go.

0

Hi Zach,

Please share the full backtest code. This is difficult to debug without it.

Best,
Derek Melchin

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.


I cleaned it up a bit -- and it runs, but I don't think it's updating the values.

0


Here's the initial build (apologies for the MESS).  Really more of a guess + test, and hopefully learn how it works in the process.

0


Hi Zach,

You should remove symbol from the constructor for BollingerBands, which is one cause for the 0's in the values. Furthermore, when working with universes, we should not use AddEquity, which means we should not register indicators, but instead, manually update them using consolidation. However, with the current code, the consolidation won’t work immediately as the universe is not yet subscribed to the symbols you are dealing with. The indicators are initialized in the coarse filter, but you should instead initialize the indicators in the OnSecuritiesChanged method because the universe would be subscribed to those symbols.So here is the summary for changes necessary in the algorithm:

  • Remove symbol from the constructor for BillingerBands
  • Initialize indicators in OnSecuritiesChanged
  • Remove AddEquity and update indicators only using consolidation

As a side note, instead of passing timedelta(days=1) into the consolidator, you can instead pass Resolution.Daily.

Best Regards,
Shile Wen

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.


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