python - 在 python 中运行多个 OLS 回归

标签 python excel pandas finance

我需要运行大量 OLS 回归 (~1.600)。我为大约 1,600 个观察值中的每一个收集了 60 个数据点。

我使用的是 Fama & French 5 因子模型,其中每个观测值的 60 个数据点与样本中的日期相匹配。例如。我在数据框中有从开始日期 ['2010-1-1'] 到结束日期 ['2015-1-1'] 的五个因素参数。

我需要针对给定股票的股票 yield 运行这些参数。现在,由于五个因子参数收集在一个数据框中,大约有 96.000 行 (1600*60) 和五列(每个因子),我需要选择前 60 个观测值,使用 OLS 对一组返回值运行这些观测值,存储估计系数,然后为因子参数和股票 yield 选择接下来 60 个观测值。

我尝试过使用切片:

start = 0
stop = 59

empty_list = []

for i in my_data:
    coef = my_date[i][start:stop]
    # run regression with the coef slice and store them in a dataframe
    start += 60
    stop += 60

但是,我似乎无法让它发挥作用。对于如何解决这个问题有什么建议吗?

最佳答案

使用groupby + np.arange()//60

from statsmodels.api import formula
import pandas as pd

df = pd.DataFrame(
    np.random.randn(96000, 6),
    columns=['f1', 'f2', 'f3', 'f4', 'f5', 'r']

)

f = 'r ~ f1 + f2 + f3 + f4 + f5'

def regress(df, f):
    return formula.ols(f, df).fit().params

results = df.groupby(np.arange(len(df)) // 60).apply(regress, f=f)

results.head()

   Intercept        f1        f2        f3        f4        f5
0  -0.108910  0.205059  0.006981  0.088200  0.064486 -0.003423
1   0.155242 -0.057223 -0.097207 -0.098114  0.163142 -0.029543
2   0.014305 -0.123687 -0.120924  0.017383 -0.168981  0.090547
3  -0.254084 -0.063028 -0.092831  0.137913  0.185524 -0.088452
4   0.025795 -0.126270  0.043018 -0.064970 -0.034431  0.081162

关于python - 在 python 中运行多个 OLS 回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43452712/

相关文章:

基于Python的网络游戏

python - Mongoengine update_one+upsert 与不推荐使用的 get_or_create

python - 是在 PyTables 中添加列以创建新表并复制的唯一方法吗?

python - 如何从 csv 中读取字节作为字节?

Excel INDEX 和 MATCH 获取值

python - pandas Series 和整个 DataFrame 之间的相关性

python - 如何获得与python pandas模块中的Data.Frame相同的data.frame?

Python Pandas - 具有不同列的 Concat 数据框忽略列名

Excel 排名平局问题

vba - 在 Visual Basic (VBA) 中传递对象引用