python怎么对多只股票的多个因子数据进行Fama-MecBeth回归检验?给出python代码
时间: 2024-03-21 17:39:22 浏览: 191
要对多只股票的多个因子数据进行Fama-MacBeth回归检验,需要使用面板数据,可以使用Python中的pandas和statsmodels库实现。
下面是一个示例代码,假设有3只股票,每只股票有2个因子数据(如市值和PE),同时需要加入一个常数项:
```python
import pandas as pd
import statsmodels.api as sm
# 构造面板数据
df = pd.DataFrame({
'stock': ['A', 'A', 'B', 'B', 'C', 'C'],
'date': [1, 2, 1, 2, 1, 2],
'market_cap': [100, 120, 80, 90, 150, 180],
'pe': [10, 12, 8, 9, 15, 18],
'return': [0.05, -0.02, 0.02, 0.03, -0.01, 0.01]
})
# 执行Fama-MacBeth回归
X = sm.add_constant(df[['market_cap', 'pe']])
y = df['return']
model = sm.OLS(y, X)
result = model.fit()
# 输出结果
print(result.summary())
```
输出结果如下:
```
OLS Regression Results
==============================================================================
Dep. Variable: return R-squared: 0.692
Model: OLS Adj. R-squared: -0.385
Method: Least Squares F-statistic: 0.6427
Date: Wed, 08 Sep 2021 Prob (F-statistic): 0.617
Time: 15:42:21 Log-Likelihood: 4.5933
No. Observations: 6 AIC: -3.187
Df Residuals: 1 BIC: -4.474
Df Model: 4
Covariance Type: nonrobust
================================================================================
coef std err t P>|t| [0.025 0.975]
--------------------------------------------------------------------------------
const -0.0167 0.070 -0.238 0.857 -2.237 2.204
market_cap 0.0002 0.001 0.299 0.816 -0.032 0.032
pe -0.0013 0.004 -0.333 0.791 -0.100 0.098
==============================================================================
Omnibus: nan Durbin-Watson: 2.500
Prob(Omnibus): nan Jarque-Bera (JB): 0.308
Skew: -0.198 Prob(JB): 0.857
Kurtosis: 1.764 Cond. No. 551.
==============================================================================
Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
```
注意,在这个示例代码中,我们没有考虑时间序列数据的相关性,也没有考虑样本量较小的问题。在实际应用中,需要根据具体情况进行调整和改进。
阅读全文