Linear regression between two price with time series

Viewed 80

Do you know how to calculate linear regression between two points in time? For example between two prices for Amazon. I am asking because all simple examples are with numbers on x axis and values on y axis and this solution from :

How to calculate the coordinates of the line between two points in python?

will not work because time on x axis .

Can we use some numpy function? Is there any trick?

If we have code:

import yfinance as yf
import datetime

start = datetime.datetime(2021,9,1)
end = datetime.datetime(2021,9,2)
test_point = datetime.datetime(2021,10,15)
Amazon = yf.Ticker("AMZN")
df = Amazon.history(start=start, end=end)
print(df)  

Code above will give us df :

                  Open         High          Low        Close   Volume  Dividends  Stock Splits
Date
2021-08-31  3424.800049  3472.580078  3395.590088  3470.790039  4356400          0             0
2021-09-01  3496.399902  3527.000000  3475.239990  3479.000000  3629900          0             0

Let`s say: I want to calculate the slope and intercept of the line between low prices.

In python 3.10 should be https://docs.python.org/3/library/statistics.html#statistics.linear_regression as linear regression and there is example with a years. I am looking something similar for python3.8

1 Answers

The easiest then would be to choose a "goalpost" date, and create a feature time_elapsed for "The number of days since goalpost" and then you can easily do LS on that variable.

goalpost = datetime.datetime(2021, 8, 31)
df["time_elapsed"] = (df.index -  goalpost).dt.days

E.g. if your goalpost is 2021-08-31 then the time_elapsed column would be

           time_elapsed    other_cols...
Date
2021-08-31            0              ...
2021-09-01            1              ...  

From here, you can use a Linear regression package (like something from sklearn, statsmodels, or even the one you shared), or you can code your own regression. In the case of Simple Linear regression (one variable Y, one variable X), the formulas are pretty simple: https://en.wikipedia.org/wiki/Ordinary_least_squares#Simple_linear_regression_model

Related