How to Fix Scikit-Learn and Yfinance Stock linear regression error?

Viewed 39

First coding project of this sort. I am trying to use linear regression using data pulled from yfinance to predict future stock prices, but I am having trouble using linear regression after transposing my data's shape.

Here I set the start and end times which I wish to test my data

Start = date.today() - timedelta(365)
Start.strftime('%Y-%m-%d')
#End = date.today() + timedelta(2)
End = date.today() + timedelta(2)
End.strftime('%Y-%m-%d')

outputs:

'2022-07-20'

which is working,

Then, I pull data from yfinance. I think here is where the problem starts. I am trying to utilize other stock's prices to judge whether the stock of my choosing (TESLA in this case) is over or under valued in order to make a prediction on the end price. After pulling the data in this function, I return the pulled data in the form of numpy arrays.

def closing_price(ticker):
    Asset = pd.DataFrame(yf.download(ticker, start=Start,end=End)['Adj Close'])     
    return Asset.to_numpy()

TESLA = closing_price('TSLA')   
GOOGL = closing_price('GOOG')
AMZN = closing_price('AMZN')
MSFT = closing_price('MSFT')
AAPL = closing_price("AAPL")
NFLX = closing_price("NFLX")

I proceed to reshape my arrays such that their shapes roughly match.

X_train = np.array([GOOGL, AMZN, AAPL, NFLX, MSFT])[:, :, 0]
X_train = np.transpose(X_train)
print(X_train.shape)
#TESLA = np.transpose(TESLA)
#print(X_train)
print(TESLA.shape)

which returns

(252, 5)
(252, 1)

However, when I try to use Linear Regression on X_train and TESLA

reg = LinearRegression().fit(X_train, TESLA)

I get this error

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-35-70213f225556> in <module>
----> 1 reg = LinearRegression().fit(X_train, TESLA)

~\anaconda3\lib\site-packages\sklearn\linear_model\_base.py in fit(self, X, y, sample_weight)
    503 
    504         n_jobs_ = self.n_jobs
--> 505         X, y = self._validate_data(X, y, accept_sparse=['csr', 'csc', 'coo'],
    506                                    y_numeric=True, multi_output=True)
    507 

~\anaconda3\lib\site-packages\sklearn\base.py in _validate_data(self, X, y, reset, validate_separately, **check_params)
    430                 y = check_array(y, **check_y_params)
    431             else:
--> 432                 X, y = check_X_y(X, y, **check_params)
    433             out = X, y
    434 

~\anaconda3\lib\site-packages\sklearn\utils\validation.py in inner_f(*args, **kwargs)
     70                           FutureWarning)
     71         kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
---> 72         return f(**kwargs)
     73     return inner_f
     74 

~\anaconda3\lib\site-packages\sklearn\utils\validation.py in check_X_y(X, y, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, estimator)
    793         raise ValueError("y cannot be None")
    794 
--> 795     X = check_array(X, accept_sparse=accept_sparse,
    796                     accept_large_sparse=accept_large_sparse,
    797                     dtype=dtype, order=order, copy=copy,

~\anaconda3\lib\site-packages\sklearn\utils\validation.py in inner_f(*args, **kwargs)
     70                           FutureWarning)
     71         kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
---> 72         return f(**kwargs)
     73     return inner_f
     74 

~\anaconda3\lib\site-packages\sklearn\utils\validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator)
    642 
    643         if force_all_finite:
--> 644             _assert_all_finite(array,
    645                                allow_nan=force_all_finite == 'allow-nan')
    646 

~\anaconda3\lib\site-packages\sklearn\utils\validation.py in _assert_all_finite(X, allow_nan, msg_dtype)
     94                 not allow_nan and not np.isfinite(X).all()):
     95             type_err = 'infinity' if allow_nan else 'NaN, infinity'
---> 96             raise ValueError(
     97                     msg_err.format
     98                     (type_err,

ValueError: Input contains NaN, infinity or a value too large for dtype('float64').

As a result, the following line also does not work, as expected

print(reg.score(X_train, TESLA))
print( reg.coef_)
print(reg.intercept_)

For a full view of my code

import numpy as np
import yfinance as yf
import pandas as pd
from datetime import date, timedelta
from matplotlib import pyplot as plt
from sklearn.linear_model import LinearRegression

Start = date.today() - timedelta(365)
Start.strftime('%Y-%m-%d')
#End = date.today() + timedelta(2)
End = date.today() + timedelta(2)
End.strftime('%Y-%m-%d')

def closing_price(ticker):
    Asset = pd.DataFrame(yf.download(ticker, start=Start,end=End)['Adj Close'])     
    return Asset.to_numpy()

TESLA = closing_price('TSLA')   
GOOGL = closing_price('GOOG')
AMZN = closing_price('AMZN')
MSFT = closing_price('MSFT')
AAPL = closing_price("AAPL")
NFLX = closing_price("NFLX")

X_train = np.array([GOOGL, AMZN, AAPL, NFLX, MSFT])[:, :, 0]
X_train = np.transpose(X_train)
print(X_train.shape)
#TESLA = np.transpose(TESLA)
#print(X_train)
print(TESLA.shape)

reg = LinearRegression().fit(X_train, TESLA)

print(reg.score(X_train, TESLA))
print( reg.coef_)
print(reg.intercept_)

Thank you for reading :)

0 Answers
Related