Search code examples
pythondataframeplotstatisticstrendline

How do I add a trendline to stock price data in Python?


I am attempting to make (i.e. calculate and plot) a trendline for stock price data in python. So far, I have tried using numpy's polyfit function. However, it doesn't work for me, because I can't seem to define the y-axis... At this point, I imagine it is helpful to show the data that I'm dealing with:

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()

Any ideas that could help me would be much appreciated!


Solution

  • 1- Using ployfit to fit a polynomial line (for example with degree 2 , a degree of 1 will be linear line)

    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))
    

    enter image description here

    Or you can get the trend of time series via STL decomposition

    !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