我正在尝试使用python中的Pandas数据帧创建一个递归函数。
我通读了一遍,似乎有几种不同的方法,for/if loop或Dataframe.apply方法;或scipy.signal.lfilter。但是,lfilter
对我不起作用,因为我的递归公式可以是多项式形式。
我要做的递归公式是:
x(t( = A * 出价 + B * x(t-1(^C + 出价Q
我浏览了一些例子,一种可能性是下面的表格。
import pandas as pd
import datetime as dt
import numpy as np
import scipy.stats as stats
import scipy.optimize as optimize
from scipy.signal import lfilter
@xw.func
@xw.ret(expand='table')
def py_Recursive(v, lamda_, AscendType):
df = pd.DataFrame(v, columns=['Bid', 'Ask', 'BidQ', 'AskQ'])
df = df.sort_index(ascending=AscendType)
NewBid = lfilter([1], [1,-2], df['Bid'].astype=(float))
df = df.join(NewBid)
df = df.sort_index(ascending=True)
return df
lamda_
是一个衰减函数,将来可能会使用,AscendType
要么TRUE
要么FALSE
我的输入数据集如下v
v =
763.1 763.3 89 65
762.5 762.7 861 687
772.1 772.3 226 761
770.6 770.8 927 333
777.8 778.0 59 162
786.5 786.7 125 431
784.7 784.9 915 595
776.8 777.0 393 843
777.7 777.9 711 935
771.6 771.8 871 956
770.0 770.2 727 300
768.7 768.9 565 923
所以我无法运行您的代码,但我认为您可以做些什么来递归创建列并使用您给出的公式:
df = pd.DataFrame(v, columns=['Bid', 'Ask', 'BidQ', 'AskQ'])
# initialise your parameters, but they can be a function of something else
A, B, C = 10, 2, 0.5
x0 = 1
#create the column x filled with x0 first
df['x'] = x0
# now change each row depending on the previous one and other information
for i in range(1,len(df)):
df.loc[i,'x'] = A*df.loc[i,'Bid'] + B*df.loc[i-1,'x']**C + df.loc[i,'BidQ']
我正在修补各种方法,下面是一个更完整的代码。
import pandas as pd
import datetime as dt
import numpy as np
import scipy.stats as stats
import scipy.optimize as optimize
from scipy.signal import lfilter
# if using xlwings addin
@xw.func
@xw.ret(expand='table')
df = pd.DataFrame(v, A=10, B=2, C=0.5, columns=['Bid', 'Ask', 'BidQ', 'AskQ'])
# initialise your parameters, but they can be a function of something else
Trend = pd.Series(1, name = 'Trend')
df = df.join(Trend)
#create the column Trend filled with 1 first
# now change each row depending on the previous one and other information
for i in range(1,len(df)):
df.loc[i,'Trend'] = A * df.loc[i,'Bid'] + B * df.loc[i-1,'Trend']**C + df.loc[i,'BidQ']
return df