如何在 Python 中为股票价格数据添加趋势线?

问题描述

我正在尝试在 python 中制作(即计算和绘制)股票价格数据的趋势线。 到目前为止,我已经尝试使用 numpy 的 polyfit 函数。但是,它对我不起作用,因为我似乎无法定义 y 轴...此时,我想显示我正在处理的数据会很有帮助:

import yfinance as yf
import matplotlib.pyplot as plt

#get the price data for the stock
data = yf.download("AAPL","1990-01-01","2021-01-01")

#plot the data
plt.plot(data["Adj Close"])
plt.show()

任何可以帮助我的想法将不胜感激!

解决方法

1- 使用 ployfit 拟合多项式线(例如度数 2 ,度数 1 将是线性线)

import numpy as np 
import seaborn as sns

# create numpy array to fint regression line
x = np.arange(data["Adj Close"].size)
fit = np.polyfit(x,data["Adj Close"],deg=2)
fit_function = np.poly1d(fit)

sns.lineplot(data=data["Adj Close"]);
#Linear regression plot
sns.lineplot(x=data["Adj Close"].index,y=fit_function(x))

Readonly

或者可以通过STL分解得到时间序列的趋势

!pip install stldecompose

from stldecompose import decompose

decomp = decompose(data["Adj Close"].values)
trend = decomp.trend

sns.lineplot(data=data["Adj Close"]);
sns.lineplot(x=data["Adj Close"].index,y=trend)

enter image description here

,

你可以试试这个:

import yfinance as yf
import matplotlib.pyplot as plt

#get the price data for the stock
data = yf.download("AAPL","1990-01-01","2021-01-01")

data["index"]=data.index 
data.reset_index(drop=True,inplace=True)

data.index= data["index"]

#plot the data
plt.plot(data.index,data["Adj Close"])
plt.show()

结果是(示例仅适用于 2020 年和 2021 年):

Output of the code above