How to change the start date of the Moving Average
-
This might be a silly question but I was wondering if it is possible to change the start date of the moving average. For example I am trying to calculate the returns of a strategy for one year in the market using an EMA of p=100 and therefore it takes too long to kick in!
As shown below: !
I understand that it takes 100 days for the moving average to begin so what I'm essentially asking is can I begin the moving average calculation 100 days before the start of my trading? I'm using the 'Buy and Buy More' article's code essentially.
-
@james-scarr I think you'll find the answer here Look for
addminperiod
-
@run-out Thanks for trying to help me out again - I really appreciate it :)
Unfortunately from what I can understand the addminperiod seems to only work for increasing the time lag before beginning a moving average. I suppose there is simply not enough data for a moving average of 100 to be computed with the above example.
class ExponentialMovingAverage(bt.Indicator): lines = ('EMA',) params = (('period', 100),) def __init__(self): self.addminperiod(self.params.period-100) def next(self): datasum = math.fsum(self.data.get(size=self.p.period)) self.lines.EMA[0] = datasum / self.p.period
The above code simply results in a float division by zero error. I believe the solution will lie in preventing trades taking place before a certain time period. (Beginning the simulation in 2018 but only buying shares in 2019 to calculate the return in the year of 2019).
The good news is that since my last attempt I have created an algorithm that performs on average 2.5% better per year than dollar-cost averaging I think! :D
-
@run-out I've simply added an if statement in the notify_timer function to only buy when it is past a certain date and this has solved my problem. Not the smartest solution probably but at least it works! :)
-
@james-scarr It is a smart solution and I was not smart for omitting that in my answer. Cheers,