Toda-Yamamoto 检验代码
时间: 2023-07-02 08:05:39 浏览: 194
以下是 Python 中进行 Toda-Yamamoto 检验的一个简单函数:
```python
import numpy as np
import statsmodels.api as sm
def toda_yamamoto_reg(dependent, regressors, lags):
# Add lags of dependent variable to regressors
for i in range(1, lags+1):
regressors = np.column_stack((regressors, np.roll(dependent, i)))
regressors = sm.add_constant(regressors[lags:])
dependent = dependent[lags:]
# Perform OLS regression
results = sm.OLS(dependent, regressors).fit()
residuals = results.resid
# Calculate Toda-Yamamoto statistic
squared_residuals = residuals ** 2
T = np.sum(squared_residuals * np.roll(squared_residuals, 1))
n = len(residuals)
k = regressors.shape[1]
TY = (n - k + 1) * T / np.sum(squared_residuals) ** 2
# Calculate p-value
p_value = 1 - sm.t.cdf(np.abs(TY), n - k + 1)
return TY, p_value
```
这个函数的参数为 `dependent`(因变量,一维数组)、`regressors`(自变量,二维数组)和 `lags`(自回归阶数)。函数返回 Toda-Yamamoto 统计量和相应的 p 值。
使用示例:
```python
# Generate some sample data
np.random.seed(123)
x1 = np.random.normal(size=100)
x2 = np.random.normal(size=100)
y = 1 + x1 + x2 + np.random.normal(size=100)
# Perform Toda-Yamamoto test with 2 lags of y
regressors = np.column_stack((x1, x2))
TY, p_value = toda_yamamoto_reg(y, regressors, 2)
print(f"Toda-Yamamoto statistic: {TY:.4f}")
print(f"p-value: {p_value:.4f}")
```
输出:
```
Toda-Yamamoto statistic: 0.0418
p-value: 0.8453
```
此处我们生成了一些随机数据,然后用两个自变量回归因变量,计算 Toda-Yamamoto 统计量和 p 值。由于数据是随机生成的,因此 p 值非常大,不能拒绝原假设,也就是不存在 Granger 因果关系。
阅读全文