fama-french五因子模型的python代码
时间: 2023-08-11 08:06:55 浏览: 185
以下是使用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
# 计算RMW和CMA因子
data['RMW'] = (2 * data['HighOM']) + data['LowOM'] - data['MediumOM'] * 2
data['CMA'] = (2 * data['SmallInv']) + data['BigInv'] - data['MediumInv'] * 2
# 计算股票的超额收益率
data['ExRet'] = data['Returns'] - data['RF']
# 构建回归模型
X = sm.add_constant(data[['Rm', 'SMB', 'HML', 'RMW', 'CMA']])
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,HighOM,MediumOM,LowOM,BigInv,MediumInv,SmallInv,RF
2000-01-03,-0.046,-0.0099,-0.009,-0.0144,-0.0182,-0.0088,-0.0114,0.0114,-0.0087,-0.0171,-0.013,-0.0079,0.0043,0.0003
2000-01-04,-0.0344,-0.0398,-0.038,-0.0448,-0.024,-0.0367,-0.0464,-0.0033,-0.0347,-0.0259,-0.0308,-0.0399,-0.0627,0.0003
2000-01-05,0.007,-0.0016,-0.0007,-0.0045,-0.0047,-0.0015,-0.0027,0.0043,-0.0101,-0.0064,-0.0024,0.0003,-0.004,0.0003
...
```
代码中使用`pandas`库读取CSV文件,并计算市场收益率、SMB、HML、RMW和CMA因子。然后,使用`statsmodels`库构建OLS回归模型,并输出回归结果。
阅读全文