Python时间序列#01 – 平稳序列生成和检验

平稳性

严平稳:时间序列 ${r_t}$ 是严平稳的,如果对于所有的 $t$ 和任意正整数 $k$ 和任意 $k$ 个正整数 $(t_1,…,t_k)$, $(r_{t_1},…,r_{t_k})$ 的联合分布在时间的平移变换下保持不变。

弱平稳:时间序列 ${r_t}$ 是弱平稳的,如果 $r_t$ 的均值与 $r_{t-l}$ 的协方差不随时间而改变,其中 $l$ 是任意整数。

平稳性序列的生成

在Python中,可以使用 numpypandas 生成平稳序列:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

def generate_datapoint(params):
    mu = params[0]
    sigma = params[1]
    return np.random.normal(mu, sigma)

# 序列A
params = (0, 1)
T = 100

A = pd.Series(index=range(T))
A.name = 'A'

for t in range(T):
    A[t] = generate_datapoint(params)

plt.plot(A)
plt.xlabel('Time')
plt.ylabel('Value')
plt.legend(['Series A'])
plt.show()

用类似的办法,生成一个非平稳的序列并命名为 B

# 序列B
T = 100

B = pd.Series(index=range(T))
B.name = 'B'

for t in range(T):
    # 注意到序列B的均值会随时间变化
    params = (t*0.1, 1)
    B[t] = generate_datapoint(params)

plt.plot(B)
plt.xlabel('Time')
plt.ylabel('Value')
plt.legend(['Series B'])
plt.plot()

平稳性序列的检验

使用 statsmodels 库中的ADF检验工具检验序列的平稳性:

from statsmodels.tsa.stattools import adfuller

def check_for_stationarity(X, cutoff=0.01):
    pvalue = adfuller(X)[1]
    if pvalue < cutoff:
        print(f'p-value: {pvalue}. 序列{X.name}可能为平稳序列。')
        return True
    else:
        print(f'p-value: {pvalue}. 序列{X.name}可能为非平稳序列。')
        return False

check_for_stationarity(A);
check_for_stationarity(B);

以上代码定义了 check_for_stationarity() 函数,这个函数的第一个参数是待检验的序列,第二个参数是ADF检验的阈值,如果 p-value 小于阈值,则认为序列是平稳序列。

输出结果为:

p-value: 1.601227238375676e-14. 序列A可能为平稳序列。
p-value: 0.7343548250851961. 序列B可能为非平稳序列。

输出结果表明,序列A的 p-value 非常小,小于代码中设定的阈值(0.01)。因此序列A是平稳序列,而序列B是非平稳序列。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注