用A股数据进行fama5因子模型的实证(使用python,输出代码)
时间: 2024-02-24 13:56:10 浏览: 187
用Python做股市数据分析
好的,以下是用A股数据进行fama5因子模型的实证的Python代码:
首先需要导入需要的库:
```python
import pandas as pd
import numpy as np
import statsmodels.api as sm
from statsmodels import regression
import matplotlib.pyplot as plt
```
然后需要获取A股的数据,这里以获取上证50成分股的数据为例:
```python
import akshare as ak
# 获取上证50成分股代码
stock_zh_a_spot_df = ak.stock_zh_a_spot()
sz50_codes = stock_zh_a_spot_df[stock_zh_a_spot_df['名称'].str.contains('上证50')]['代码'].tolist()
# 获取上证50成分股的日线行情数据
start_date = '2010-01-01'
end_date = '2021-06-30'
sz50_df = pd.DataFrame()
for code in sz50_codes:
data = ak.stock_zh_a_daily(code=code, start_date=start_date, end_date=end_date)
data['code'] = code
sz50_df = pd.concat([sz50_df, data], axis=0)
sz50_df = sz50_df.reset_index(drop=True)
```
接下来需要计算每只股票的收益率和市场收益率:
```python
# 计算每只股票的收益率
sz50_df['return'] = sz50_df.groupby('code')['收盘价'].apply(lambda x: x.pct_change())
# 获取沪深300指数的日线行情数据
hs300_df = ak.stock_zh_index_daily(symbol='沪深300指数', start_date=start_date, end_date=end_date)
hs300_df['return'] = hs300_df['close'].pct_change()
# 合并每只股票的收益率和市场收益率
sz50_df = pd.merge(sz50_df, hs300_df[['date', 'return']], on='date')
```
然后需要计算每只股票的市值、市值因子、动量因子、市场因子和价值因子:
```python
# 计算每只股票的市值
sz50_df['market_cap'] = sz50_df['收盘价'] * sz50_df['总股本']
# 计算每只股票的市值因子
sz50_df['market_cap_factor'] = pd.qcut(sz50_df['market_cap'], 10, labels=False) + 1
# 计算每只股票的动量因子
sz50_df['momentum_factor'] = sz50_df.groupby('code')['return'].rolling(12).sum().groupby('code').shift(1)
# 计算每只股票的市场因子
sz50_df['market_factor'] = sz50_df['return'] - sz50_df['return'].mean()
# 计算每只股票的价值因子
sz50_df['book_to_market'] = sz50_df['每股净资产'] / sz50_df['收盘价']
sz50_df['value_factor'] = pd.qcut(sz50_df['book_to_market'], 10, labels=False, duplicates='drop') + 1
```
最后,使用多元线性回归模型计算每只股票的alpha、beta、市值因子系数、动量因子系数、市场因子系数和价值因子系数:
```python
# 使用多元线性回归模型计算每只股票的alpha、beta、市值因子系数、动量因子系数、市场因子系数和价值因子系数
results = []
for code in sz50_codes:
data = sz50_df[sz50_df['code'] == code][['return', 'market_cap_factor', 'momentum_factor', 'market_factor', 'value_factor']]
data = data.dropna()
if len(data) >= 120:
X = sm.add_constant(data[['market_cap_factor', 'momentum_factor', 'market_factor', 'value_factor']])
y = data['return']
model = regression.linear_model.OLS(y, X).fit()
results.append((code, model.params[0], model.params[1], model.params[2], model.params[3], model.params[4], model.params[5]))
# 输出每只股票的alpha、beta、市值因子系数、动量因子系数、市场因子系数和价值因子系数
results_df = pd.DataFrame(results, columns=['code', 'alpha', 'beta', 'market_cap_factor', 'momentum_factor', 'market_factor', 'value_factor'])
results_df.to_csv('fama5_factors.csv', index=False)
```
以上就是用A股数据进行fama5因子模型的实证的Python代码。
阅读全文