首页 > 解决方案 > 绘制连接时间序列中大多数数据点的线

问题描述

我想了解如何绘制最佳拟合线或连接最多点的线;一条线用于局部最小值,另一条线用于局部最大值。

就像这张照片一样: 在此处输入图像描述

以下是查找局部最小值和最大值点的代码

import numpy as np
import pandas as pd  
import matplotlib.pyplot as plt
from pandas_datareader import data as pdr
import fix_yahoo_finance as yf
yf.pdr_override() 

startdate = dt.date(2016, 1, 1)
#enddate = dt.date(2018, 10, 22)
today = dt.date.today()
index_ticker = "^GSPC"
index_df = pdr.get_data_yahoo(index_ticker, start=startdate, end=today)

from scipy.signal import argrelextrema
n=50 # number of points to be checked before and after 

# Find local peaks/bottoms
index_df['min'] = index_df.iloc[argrelextrema(index_df['Adj Close'].values, np.less_equal, order=n)[0]]['Adj Close']
index_df['max'] = index_df.iloc[argrelextrema(index_df['Adj Close'].values, np.greater_equal, order=n)[0]]['Adj Close']

# Plot results
plt.scatter(index_df['Adj Close'].index, index_df['min'], c='r')
plt.scatter(index_df['Adj Close'].index, index_df['max'], c='g')
plt.plot(index_df['Adj Close'].index, index_df['Adj Close'])
plt.show()

我遇到了本教程,https://prappleizer.github.io/Tutorials/Plotting/Plotting.html ,它绘制了一条带有不确定阴影区域的最佳拟合线。

在此处输入图像描述

这是我正在寻找的,但我无法弄清楚如何应用到时间序列上以获得所需的输出,如时间序列图片中所示。

感谢是否有人可以提供建议。谢谢!

标签: pythonlineconnect

解决方案


现在您已经有了局部最小值和最大值,请在每组点上绘制线性回归。使用您最喜欢的 Python 统计包来执行此操作。


推荐阅读