Problem trying to port Lowpass filter to backtrader... help!
lvaghi last edited by
I am trying to port to backtrader an indicator (Lowpass filter), but I am stuck.
Here you can see the code that works on the usual timeseries (those where
 is the index of the oldest value instead of the current value as is in the
#coding=utf-8 #LOWPASS ''' The lowpass filter is similar to a simple moving average, but with less delay. Each elemt of the lowpass (LP) series is a combination of the last three values of the input data (the current one ant the two preceding) and the last two values of the same LP series. ''' import matplotlib.pyplot as plt import pylab import random import numpy as np import pandas as pd import sys def squarewave(): wave =  for i in range(1,500): if (i/100) %2 == 0: wave.append(10) else: wave.append(-10) return wave class LOWPASS(object): def series(self, l_data,period): a = 2.0 / (1 + period) LP =  LP.append(l_data) LP.append(l_data) swNaN = 1 for x in range(2,len(l_data)): if np.isnan(l_data[x-2]): LP.append(np.nan) else: #print x if swNaN == 1: #initializes LP vith the first element (not NaN) of data series. swNaN = 0 LP[x-1] = LP[x-2] = l_data[x] LP.append((a - 0.25 * a * a) * l_data[x] + 0.5 * a * a * l_data[x-1] \ - (a - 0.75 * a * a) * l_data[x-2] \ + 2 * (1. - a) * LP[x-1] \ - (1. - a) * (1. - a) * LP[x-2]) return LP if __name__ == '__main__': mylist = squarewave() myLOWPASS = LOWPASS() #mylist=[10,20,30,40,50,60,70,80,90,100,101,102,103,104,105,106,107,108,109,110] #mylist= range(1,500,10) + range(501,1500,1) #mylist =  #for i in range(0,1000): # mylist.append(random.randint(1,101)) # mylist.append(100*np.sin(i)) print mylist lowpassed = myLOWPASS.series(mylist,25) print "lowpassed: ", lowpassed df = pd.DataFrame() df['mylist']= mylist df['lowpass']=lowpassed print df df.plot.line() plt.show()
The problem I have when converting this code to backtrader is with the initialization of the LP line:
In backtrader I do not know how to set the first two elements of the LP line to the oldest value of the data
line: obviously my understanding of backtrader is too limited... any help will be appreciated.