有表格data,包含10 个股票价格时间序列按照时间对齐(每一行为一天,每一列为一只股票价格),现在利用python完成以下操作:4.计算10个股票日度收益率的同期相关性(包括 pearson 和 spearman 两种,时间窗口为100 天) 和交错 5 日的前后相关性。针对同期相关性给出的相关系数矩阵,设定不同阁值,将小于闯值的相关关系删除,构建 10 个股票间相关关系网络,可视化网络。
时间: 2023-11-27 21:52:05 浏览: 66
首先,我们需要导入相关的库和数据:
```python
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.stats import pearsonr, spearmanr
data = pd.read_csv("data.csv", index_col=0)
```
接下来,我们可以计算每个股票的日度收益率并使用rolling函数计算同期相关性和交错5日前后相关性:
```python
returns = data.pct_change()
rolling_pearson = returns.rolling(window=100).corr().iloc[1::2, 0].unstack()
rolling_spearman = returns.rolling(window=100).corr(method='spearman').iloc[1::2, 0].unstack()
shifted_returns = returns.shift(-5)
shifted_pearson = returns.corrwith(shifted_returns).iloc[1::2].unstack()
shifted_spearman = returns.corrwith(shifted_returns, method='spearman').iloc[1::2].unstack()
```
然后,我们可以使用seaborn库中的heatmap函数可视化相关系数矩阵:
```python
sns.heatmap(rolling_pearson, cmap="coolwarm", center=0, annot=True, fmt=".2f")
plt.title("Rolling Pearson Correlation (window=100)")
plt.show()
sns.heatmap(rolling_spearman, cmap="coolwarm", center=0, annot=True, fmt=".2f")
plt.title("Rolling Spearman Correlation (window=100)")
plt.show()
sns.heatmap(shifted_pearson, cmap="coolwarm", center=0, annot=True, fmt=".2f")
plt.title("Shifted Pearson Correlation (lag=5)")
plt.show()
sns.heatmap(shifted_spearman, cmap="coolwarm", center=0, annot=True, fmt=".2f")
plt.title("Shifted Spearman Correlation (lag=5)")
plt.show()
```
最后,我们可以根据设定的阈值删除小于阈值的相关关系,然后使用networkx和matplotlib库可视化股票间的相关关系网络:
```python
import networkx as nx
threshold = 0.5
corr_matrix = returns.corr()
# Remove correlations below threshold
corr_matrix[corr_matrix < threshold] = 0
# Create graph from correlation matrix
graph = nx.from_numpy_matrix(corr_matrix.values)
# Set node labels to be stock names
labels = {i: corr_matrix.columns[i] for i in range(len(corr_matrix.columns))}
nx.relabel_nodes(graph, labels, copy=False)
# Draw graph with spring layout
plt.figure(figsize=(10, 10))
pos = nx.spring_layout(graph, k=0.2, iterations=50)
nx.draw(graph, pos=pos, with_labels=True, node_size=1000, font_size=16, font_weight='bold')
plt.show()
```
以上就是完成操作4和5的完整代码。
阅读全文