Own indicator: "if function" with min max is very slow
I am having a hard time creating / adapting an indicator.
I made it in the most slow way and I wonder whether there is a better solution.
The idea is to have an if positive RoC the 1 else 0.
class Momentumplus_org(bt.Indicator): lines = ('trend',) params = (('period', 190), ('rperiod', 30)) def __init__(self): self.addminperiod(self.params.period) self.roc = bt.ind.ROC(self.data, period=self.p.rperiod) def next(self): returns = np.log(self.data.get(size=self.p.period)) x = np.arange(len(returns)) slope, _, rvalue, _, _ = linregress(x, returns) annualized = (1 + slope) ** 252 test = math.ceil(self.roc) rate = bt.Min(1, bt.Max(0, test)) self.lines.trend = annualized * (rvalue ** 2) * rate
This takes a hell of a time to get calculated. I tried to get the test and rate into the init ...
I also tried to keep the original design:
def momentum_func(the_array): r = np.log(the_array) slope, _, rvalue, _, _ = linregress(np.arange(len(r)), r) annualized = (1 + slope) ** 252 return annualized * (rvalue ** 2) class Momentum(bt.ind.OperationN): lines = ('trend',) params = dict(period=50) func = momentum_func
But I couldn't make it work with two parameters...
Are there better ways than math.ceil / min / max?
Thank you very much in advance!
are you sure it is slow where you said it was? Have you profiled the code?
I used cProfile to do it. https://towardsdatascience.com/how-to-profile-your-code-in-python-e70c834fad89
There is a execution difference of 20% but it does not seem to come from min max or ceil, I assume it is due to the roc calculation in the init.
Thank you chrunchypickle!