- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在计算股票 yield 的自相关函数。为此,我测试了两个函数,即 Pandas 内置的 autocorr
函数和 statsmodels.tsa
提供的 acf
函数。这是在以下 MWE 中完成的:
import pandas as pd
from pandas_datareader import data
import matplotlib.pyplot as plt
import datetime
from dateutil.relativedelta import relativedelta
from statsmodels.tsa.stattools import acf, pacf
ticker = 'AAPL'
time_ago = datetime.datetime.today().date() - relativedelta(months = 6)
ticker_data = data.get_data_yahoo(ticker, time_ago)['Adj Close'].pct_change().dropna()
ticker_data_len = len(ticker_data)
ticker_data_acf_1 = acf(ticker_data)[1:32]
ticker_data_acf_2 = [ticker_data.autocorr(i) for i in range(1,32)]
test_df = pd.DataFrame([ticker_data_acf_1, ticker_data_acf_2]).T
test_df.columns = ['Pandas Autocorr', 'Statsmodels Autocorr']
test_df.index += 1
test_df.plot(kind='bar')
我注意到他们预测的值并不相同:
造成这种差异的原因是什么,应该使用哪些值?
最佳答案
Pandas 和 Statsmodels 版本的区别在于均值减法和归一化/方差除法:
autocorr
只是将原始系列的子系列传递给 np.corrcoef
。在该方法中,这些子序列的样本均值和样本方差用于确定相关系数acf
则相反,使用整体系列样本均值和样本方差来确定相关系数。对于较长的时间序列,差异可能会变小,但对于较短的时间序列,差异会很大。
与 Matlab 相比,Pandas autocorr
函数可能对应于对(滞后)系列本身进行 Matlabs xcorr
(cross-corr),而不是 Matlab 的 autocorr
,它计算样本自相关(从文档中猜测;我无法验证这一点,因为我无法访问 Matlab)。
请参阅此 MWE 以获得说明:
import numpy as np
import pandas as pd
from statsmodels.tsa.stattools import acf
import matplotlib.pyplot as plt
plt.style.use("seaborn-colorblind")
def autocorr_by_hand(x, lag):
# Slice the relevant subseries based on the lag
y1 = x[:(len(x)-lag)]
y2 = x[lag:]
# Subtract the subseries means
sum_product = np.sum((y1-np.mean(y1))*(y2-np.mean(y2)))
# Normalize with the subseries stds
return sum_product / ((len(x) - lag) * np.std(y1) * np.std(y2))
def acf_by_hand(x, lag):
# Slice the relevant subseries based on the lag
y1 = x[:(len(x)-lag)]
y2 = x[lag:]
# Subtract the mean of the whole series x to calculate Cov
sum_product = np.sum((y1-np.mean(x))*(y2-np.mean(x)))
# Normalize with var of whole series
return sum_product / ((len(x) - lag) * np.var(x))
x = np.linspace(0,100,101)
results = {}
nlags=10
results["acf_by_hand"] = [acf_by_hand(x, lag) for lag in range(nlags)]
results["autocorr_by_hand"] = [autocorr_by_hand(x, lag) for lag in range(nlags)]
results["autocorr"] = [pd.Series(x).autocorr(lag) for lag in range(nlags)]
results["acf"] = acf(x, unbiased=True, nlags=nlags-1)
pd.DataFrame(results).plot(kind="bar", figsize=(10,5), grid=True)
plt.xlabel("lag")
plt.ylim([-1.2, 1.2])
plt.ylabel("value")
plt.show()
Statsmodels 使用 np.correlate
对其进行优化,但这基本上是它的工作原理。
关于python - pandas ACF 和 statsmodel ACF 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36038927/
是否有 statsmodels API 可以从 statsmodels 时间序列模型中检索预测区间? 目前,我正在使用以下方法手动计算预测区间: 这是我的代码。首先,获取一些示例数据... ! pyt
我有:statsmodels 0.5.0(正式名称为 scikits.statsmodels) Pandas 0.12.0。(全部从源安装) 我收到这个错误: File "/home/userna
所有内容的格式都与 Statsmodels 网站上的一样,但是 Spyder 以某种方式返回了这个: TypeError: ztest_ind() got multiple values for ar
所有内容的格式都与 Statsmodels 网站上的一样,但是 Spyder 以某种方式返回了这个: TypeError: ztest_ind() got multiple values for ar
谁能给我解释一下 statsmodel.formula.api 中的 ols 和 statsmodel.api 中的 ols 之间的区别? 使用 ISLR 文本中的广告数据,我使用两者运行了一个 ol
我用python处理一个线性回归模型,json数据如下: {"Y":[1,2,3,4,5],"X":[[1,43,23],[2,3,43],[3,23,334],[4,43,23],[232,234,
我正在使用 Python 中的 statsmodels MixedLM 包估计一个混合线性模型。拟合模型后,我现在想进行预测,但很难理解“预测”方法。 statsmodels 文档 (http://w
使用状态模型的逻辑回归模型: log_reg = st.logit(formula = 'label ~ pregnant + glucose + bp + insulin + bmi + pedig
我有一个包含 3 列的数据框 ['X', 'Y', 'Z'] 我想研究一下 X 和 Y影响Z的分布。为此,我想使用 nadaraya watson 的非参数回归器。在 statsmodels 中有一个
我正在尝试使用 statsmodel 中的 statsmodels.discrete.conditional_models.ConditionalLogit 类。 在jupyter笔记本中导入模块时,
我安装 statsmodels: apt-get install python python-dev python-setuptools python-numpy python-scipy curl
import statsmodels.formula.api as sm import numpy as np import pandas url = "http://vincentarelbundo
我正在尝试在 x-y 数据的简单测试集上使用 statsmodels 中的稳健线性模型。然而,作为 model.params 的返回值,我只得到一个值。如何获得拟合的斜率和截距?最小示例(其中我试图从
我正在使用库statsmodels.tsa.stattools.grangercausalitytests来测试两个时间序列之间的相似性。我知道列表 a 和 b 都是合法列表,没有任何 None 或
以下代码使用 statsmodels 拟合了一个过度简化的广义线性模型 model = smf.glm('Y ~ 1', family=sm.families.NegativeBinomial(),
在Python库Statsmodels中,可以用print(results.summary())打印出回归结果,如何打印出超过的摘要一张表中的一个回归,以便更好地比较? 线性回归,代码取自 stats
我有一个 pandas DataFrame,其行包含多种类型的数据。我想使用 statsmodels.formula.api 根据这些数据拟合一个模型,然后做出一些预测。对于我的应用程序,我想一次预测
我正在尝试使用 statsmodels 中的 logit 模块对包含 bool 值(“默认”)目标变量和两个特征(“fico_interp”、“home_ownership_int”)的数据集执行逻辑
这个问题类似于confidence and prediction intervals with StatsModels但有一个额外的细微差别: 我的数据是异方差的,我想使用 statsmodels 提
我正在使用 Pandas 的混合物和 StatsModels绘制时间序列分解图。我关注了this answer但是当我调用 plot() 时,它似乎在绘制一个副本。 我的 DataFrame 看起来像
我是一名优秀的程序员,十分优秀!