【问题标题】:How can i plot a rolling correlation coefficient within my plot?如何在我的图中绘制滚动相关系数?
【发布时间】:2021-06-10 11:05:23
【问题描述】:

这是我的代码。通过谷歌,我刚刚找到了一个提示,但它并没有真正起作用,可能是因为两种资产类别之间的滚动(50)相关性。我想在右上角有一个传说中的相关系数。

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime as dt, timedelta as td
from pandas_datareader import data as  pdr
import numpy as np


#'--------------------------------------
#ZUSATZ: automatic request of online data
#--------------------------------------

startyear =2020
startmonth =1
startday = 1

datestring = dt.strftime(dt.now(), "%d/%m/%Y")

start = dt(startyear,startmonth,startday) #Set starting time for datesample
now = dt.now()

asset1 = input("Enter the stock symbol (enter 'quit' to stop):").upper()
asset2 = input("Enter the stock symbol (enter 'quit' to stop):").upper()


a1 = pdr.get_data_yahoo(asset1,start,now).reset_index()
a2 =pdr.get_data_yahoo(asset2,start,now).reset_index()

a1= pd.DataFrame(a1[["Date","Adj Close"]])
a1.columns =["Date " + asset1, "Adj Close " + asset1]

a2= pd.DataFrame(a2[["Date", "Adj Close"]])
a2.columns =["Date " + asset2, "Adj Close " + asset2]

asset = pd.concat([a1,a2], axis=1)

points_to_plot = 300
fig = plt.figure()
fig.suptitle("Correlation " + datestring)
ax1 = fig.add_subplot(1,1,1)
ax1.set_ylabel('Correaltion', fontsize = 12)
ax1.set_xlabel('Day', fontsize = 12)
label1 = ax1.set_xticklabels(ax1.get_xticklabels(), rotation = 90,fontsize=5,alpha=0.5)
ax1.set_title(f"{asset1} & {asset2}, last {points_to_plot} days", fontsize=14)

correlation_line = asset["Adj Close " +asset1].rolling(50).corr(asset["Adj Close " + asset2])[-300:].plot()
plt.legend((correlation_line, 'line-regression r={}'), 'best')

plt.show()

【问题讨论】:

    标签: python-3.x plot correlation


    【解决方案1】:

    以防万一有人感兴趣。我是这样解决的。

    当然,如果有人可以告诉我“老兄,你需要太多代码”,我愿意学习,谢谢。我也很感兴趣是否可以在热图中的折线图上标记 0.79 的相关性。

    如果有人有想法?

    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    from datetime import datetime as dt, timedelta as td
    from pandas_datareader import data as  pdr
    import numpy as np
    import scipy as sc
    
    
    #'--------------------------------------
    #ZUSATZ: automatic request of online data
    #--------------------------------------
    
    
    startyear =2020
    startmonth =1
    startday = 1
    
    datestring = dt.strftime(dt.now(), "%d/%m/%Y")
    
    start = dt(startyear,startmonth,startday) #Set starting time for datesample
    now = dt.now()
    
    asset1 = input("Enter the stock symbol (enter 'quit' to stop):").upper()
    asset2 = input("Enter the stock symbol (enter 'quit' to stop):").upper()
    
    points_to_plot = 300
    
    fig = plt.figure()
    fig.suptitle("Correlation " + datestring)
    ax1 = fig.add_subplot(1,2,1)
    ax2 = fig.add_subplot(1,2,2)
    ax2.set_ylabel("Correaltion",fontsize = 12)
    ax2.set_xlabel("Days", fontsize = 12)
    label1 = ax1.set_xticklabels(ax1.get_xticklabels(), rotation = 90,fontsize=5,alpha=0.5)
    ax2.set_title(f"{asset1} & {asset2}, last {points_to_plot} days", fontsize=14)
    ax1.set_title(f"{asset1} & {asset2}, last {points_to_plot} days", fontsize=14)
    
    a1 = pdr.get_data_yahoo(asset1,start,now).reset_index()
    a2 =pdr.get_data_yahoo(asset2,start,now).reset_index()
    
    a1= pd.DataFrame(a1[["Date","Adj Close"]])
    a1.columns =["Date " + asset1, "Adj Close " + asset1]
    
    a2= pd.DataFrame(a2[["Date", "Adj Close"]])
    a2.columns =["Date " + asset2, "Adj Close " + asset2]
    
    asset = pd.concat([a1,a2], axis=1)
    
    correlation_line = asset["Adj Close " + asset1].rolling(50).corr(asset["Adj Close " + asset2])[-300:].plot()
    
    
    
    df= pd.DataFrame(asset, columns=["Adj Close "+ asset1, "Adj Close " + asset2])
    print(df)
    corrMatrix = df.corr()
    print(corrMatrix)
    
    sns.heatmap(corrMatrix, annot=True, ax=ax1)
    
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2015-10-20
      • 1970-01-01
      • 2017-08-18
      • 2017-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-03
      • 2020-07-30
      相关资源
      最近更新 更多