fama-french三因子模型的python代码
时间: 2023-08-11 16:06:55 浏览: 175
以下是使用Python实现Fama-French三因子模型的代码:
```python
import pandas as pd
import numpy as np
import statsmodels.api as sm
# 导入数据
data = pd.read_csv('data.csv')
data.set_index('Date', inplace=True)
# 计算市场收益率
data['Rm'] = data['SP500'].pct_change()
# 计算SMB和HML因子
data['SMB'] = (data['SmallCap'] - data['BigCap']) / 2.0
data['HML'] = (2 * data['HighBM']) + data['LowBM'] - data['MediumBM'] * 2
# 计算股票的超额收益率
data['ExRet'] = data['Returns'] - data['RF']
# 构建回归模型
X = sm.add_constant(data[['Rm', 'SMB', 'HML']])
y = data['ExRet']
model = sm.OLS(y, X)
results = model.fit()
# 输出回归结果
print(results.summary())
```
其中,`data.csv`是包含股票每日收益率、市场收益率和因子数据的CSV文件,格式如下:
```
Date,Returns,SP500,BigCap,SmallCap,HighBM,MediumBM,LowBM,RF
2000-01-03,-0.046,-0.0099,-0.009,-0.0144,-0.0182,-0.0088,-0.0114,0.0003
2000-01-04,-0.0344,-0.0398,-0.038,-0.0448,-0.024,-0.0367,-0.0464,0.0003
2000-01-05,0.007,-0.0016,-0.0007,-0.0045,-0.0047,-0.0015,-0.0027,0.0003
...
```
代码中使用`pandas`库读取CSV文件,并计算市场收益率、SMB和HML因子。然后,使用`statsmodels`库构建OLS回归模型,并输出回归结果。
阅读全文