[英]Recursion: IIR filter with `scipy.lfilter`
Given some data x
: 给出一些数据
x
:
from pandas_datareader.data import DataReader as dr
x = np.squeeze(dr('DTWEXB', 'fred').dropna().values)
I want to calculate another vector y
as follows: 我想计算另一个向量
y
如下:
Where alpha equals 0.03, in this case. 在这种情况下, alpha等于0.03。
Can I do this with scipy.lfilter?
我可以用
scipy.lfilter?
做到这scipy.lfilter?
. 。 Similar question here , but in that case the starting value of the result is 0 and that is throwing something off.
类似的问题在这里 ,但在这种情况下,结果的起始值是0,这是抛出一些东西。
My attempt: 我的尝试:
from scipy.signal import lfilter
a = 0.03
b = 1 - a
y0 = x[0]
y = lfilter([a], [y0, -b], x)
The results should be: 结果应该是:
true_y = np.empty(len(x))
for k in range(0, len(true_y)):
if k == 0:
true_y[k] = x[0]
else:
true_y[k] = a*x[k] + b*true_y[k-1]
print(true_y)
[ 101.1818 101.176862 101.16819314 ..., 120.9813121 120.92484874
120.85786628]
The correct arguments for the coefficients of the transfer function are [a]
and [1, -b]
. 传递函数系数的正确参数是
[a]
和[1, -b]
。
To handle your desired initial condition, you can create the correct initial state for the filter using scipy.signal.lfiltic
: 要处理所需的初始条件,可以使用
scipy.signal.lfiltic
为过滤器创建正确的初始状态:
zi = lfiltic([a], [1, -b], y=[x[0]])
Then call lfilter
with the zi
argument: 然后使用
zi
参数调用lfilter
:
y, zo = lfilter([a], [1, -b], x, zi=zi)
Here are an x
, y
(computed using lfilter
with zi
), and your true_y
: 这是一个
x
, y
(使用带有zi
lfilter
计算)和你的true_y
:
In [37]: x
Out[37]: array([ 3., 1., 2., 0., -1., 2.])
In [38]: y
Out[38]:
array([ 3. , 2.94 , 2.9118 , 2.824446 , 2.70971262,
2.68842124])
In [39]: true_y
Out[39]:
array([ 3. , 2.94 , 2.9118 , 2.824446 , 2.70971262,
2.68842124])
Take the z-transform of your filter, that gives you the values for the numerator b
and denominator a
: 采用滤波器的z变换,它给出分子
b
和分母a
:
alpha
y(z) = ------------------ x(z)
1 - (1-alpha) z^-1
So you run 所以你跑
import scipy.signal
x[0] /= alpha
y = scipy.signal.lfilter([alpha], [1, - 1 + alpha], x)
Which yields 哪个收益率
array([ 101.1818 , 101.176862 , 101.16819314, ..., 120.9813121 ,
120.92484874, 120.85786628])
Note I have scaled x[0]
to account for the initial condition you wanted. 注意我已缩放
x[0]
以考虑您想要的初始条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.