计算十支股票日度收益率的同期相关性(包括pearson和spearman两种,时间窗口为100天)和交错5日的前后相关性python代码
时间: 2024-02-18 13:58:57 浏览: 21
首先,我们需要获取股票的日度收益率数据,这里假设我们已经获取到了,用一个 DataFrame 对象存储,其中每一列是一只股票的日度收益率数据。
接下来,我们可以使用 pandas 库中的 corr() 函数来计算同期相关性,其中参数 method 可以指定相关性的计算方法,包括 pearson 和 spearman 两种,参数 window 可以指定时间窗口大小。
代码示例:
```python
import pandas as pd
# 读取股票日度收益率数据
df = pd.read_csv('stock_returns.csv')
# 计算同期pearson相关性,时间窗口为100天
pearson_corr = df.rolling(window=100, min_periods=1).corr(method='pearson')
# 计算同期spearman相关性,时间窗口为100天
spearman_corr = df.rolling(window=100, min_periods=1).corr(method='spearman')
# 计算交错5日的前后相关性
shifted_df = df.shift(-5)
lag_corr = df.corrwith(shifted_df)
```
在计算交错相关性时,我们将原始数据向后平移 5 天,然后使用 corrwith() 函数计算两个 DataFrame 对象之间的相关性。
注意:这里的计算方法仅供参考,实际应用中需要根据具体情况进行调整。
相关问题
有表格data,包含10 个股票价格时间序列按照时间对齐(每一行为一天,每一列为一只股票价格),现在利用python完成以下操作:4.计算10个股票日度收益率的同期相关性(包括 pearson 和 spearman 两种,时间窗口为100 天) 和交错 5 日的前后相关性。针对同期相关性给出的相关系数矩阵,设定不同阁值,将小于闯值的相关关系删除,构建 10 个股票间相关关系网络,可视化网络。
首先,我们需要导入相关的库和数据:
```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的完整代码。
spearman和pearson相关性的区别在哪
Spearman相关性和Pearson相关性都是用来衡量两个变量之间的关系的统计指标,但它们的计算方法和应用场景有所不同。
Pearson相关性是基于变量之间的线性关系进行计算的。它假设两个变量的关系是线性的,并且可以用一条直线来描述它们之间的关系。Pearson相关系数的取值范围是-1到1之间,-1表示完全负相关,0表示没有相关性,1表示完全正相关。
Spearman相关性则是基于变量之间的等级关系进行计算的。它不需要假设变量之间的关系是线性的,而是通过将变量的值转换为它们的等级来计算它们之间的相关性。Spearman相关系数的取值范围也是-1到1之间,但与Pearson相关系数不同,它可以捕捉到非线性的关系。
因此,Pearson相关性适用于线性关系比较明显的变量,而Spearman相关性适用于等级关系比较明显的变量。