如何绘制标准偏差误差线?

2024-05-16 00:53:30 发布

您现在位置:Python中文网/ 问答频道 /正文

使用scipy,我可以绘制标准偏差线。我如何复制上面95%的同一行和下面95%的另一行

请看下面两张图片,了解我的意思:

enter image description here

enter image description here

我的代码:

import datetime as date
import matplotlib.pyplot as plt
%matplotlib inline
import datetime
from scipy import stats

Ins_Name = "EURUSD=X"
#Ins_Name = "AAPL"
df = yf.download(Ins_Name,'2019-05-01','2020-01-03')

df.reset_index(inplace=True)
df['date_ordinal'] = pd.to_datetime(df['Date']).apply(lambda date: date.toordinal())
DateVariance = [datetime.date(2019, 5, 1), datetime.date(2020, 1, 3)]

x_reg = df.date_ordinal
y_reg = df.Close
slope, intercept, r_value, p_value, std_err = stats.linregress(x_reg, y_reg)
print("slope: %f    intercept: %f     STD Error: %f" % (slope, intercept, std_err))

sns.set()
#plt.figure(figsize=(26, 10))
fig, ax = plt.subplots(figsize=(15,7))
ax = plt.plot(x_reg,intercept + slope*x_reg, color='b')
#ax = sns.lmplot('date_ordinal', 'Close', data=df, fit_reg=True, aspect=2, ) #Scatter PLot
ax = sns.regplot(data=df,x='date_ordinal',y=df.Close,ci=1,fit_reg=False,scatter_kws={"color": "red"}, line_kws={"color": "black"}, marker='x') #scatterplot
#sns.jointplot('date_ordinal', df.Close, data=df, kind="reg",ylim=[1.089,1.15],xlim=DateVariance, height=12,color='red',scatter_kws={"color": "red"}, line_kws={"color": "black"})

ax.set_xlabel('Interval', fontsize=25)
ax.set_xlim(DateVariance)
ax.set_ylabel('Price', fontsize=25)
ax.set_title('Mean reversion of ' + Ins_Name + ' Close Prices',fontsize= 45,color='black')
new_labels = [datetime.date.fromordinal(int(item)) for item in ax.get_xticks()]
ax.set_xticklabels(new_labels)

Tags: nameimportdfclosedatetimedatepltreg
1条回答
网友
1楼 · 发布于 2024-05-16 00:53:30

我认为函数stats.linregress()不是您想要的。它只返回斜率上的不确定性,而不是y截距,如果我理解你的问题,这就是你想要的

我会像下面那样使用scipy.optimize.curve_fit()

import datetime as date
import matplotlib.pyplot as plt
import datetime
from scipy.optimize import curve_fit
import yfinance as yf
import pandas as pd
import numpy as np
import seaborn as sns

def fline(x, *par):
    return par[0] + par[1]*x

Ins_Name = "EURUSD=X"
#Ins_Name = "AAPL"
df = yf.download(Ins_Name,'2019-05-01','2020-01-03')

df.reset_index(inplace=True)
df['date_ordinal'] = pd.to_datetime(df['Date']).apply(lambda date: date.toordinal())
DateVariance = [datetime.date(2019, 5, 1), datetime.date(2020, 1, 3)]

x_reg = df.date_ordinal
x_trans = x_reg - x_reg[0]

y_reg = df.Close
pi = [1.1, -0.0001] # initial guess. Could use linregress to get these values
# Perform curve fitting here
popt, cov = curve_fit(fline, x_trans, y_reg, p0=pi) # returns the values and the covariance (error) matrix
yInterceptSigma = np.sqrt(cov[0,0])
print(x_reg)
print(x_reg - x_reg[0])
print(popt)
print(cov)

sns.set()
#plt.figure(figsize=(26, 10))
fig, ax = plt.subplots(figsize=(15,7))
ax = plt.plot(x_reg, fline(x_trans, *popt), color='b')
# +/- 2sigma gives ~95% CI
plt.plot(x_reg, fline(x_trans, *[popt[0] + 2 * yInterceptSigma, popt[1]]), ' b') # +2sigma on the yintercept
plt.plot(x_reg, fline(x_trans, *[popt[0] - 2 * yInterceptSigma, popt[1]]), ' b') # -2sigma on teh yintercept
#ax = sns.lmplot('date_ordinal', 'Close', data=df, fit_reg=True, aspect=2, ) #Scatter PLot
ax = sns.regplot(data=df,x='date_ordinal',y=df.Close,ci=1,fit_reg=False,scatter_kws={"color": "red"}, line_kws={"color": "black"}, marker='x') #scatterplot
#sns.jointplot('date_ordinal', df.Close, data=df, kind="reg",ylim=[1.089,1.15],xlim=DateVariance, height=12,color='red',scatter_kws={"color": "red"}, line_kws={"color": "black"})

ax.set_xlabel('Interval', fontsize=25)
ax.set_xlim(DateVariance)
ax.set_ylabel('Price', fontsize=25)
ax.set_title('Mean reversion of ' + Ins_Name + ' Close Prices',fontsize= 45,color='black')
new_labels = [datetime.date.fromordinal(int(item)) for item in ax.get_xticks()]
ax.set_xticklabels(new_labels)

plt.show()

它给出了以下曲线图: enter image description here

相关问题 更多 >