You are currently viewing Time series Forecast of Yahoo Finance Data
Yahoo Finance is a site that offers financial news, information, and analysis about businesses, markets, and industries.

Time series Forecast of Yahoo Finance Data

Yahoo Finance is the far the most popular source of information on stock market data and most financial information. It is a site that offers financial news, information, and analysis about businesses, markets, and industries. Additionally, users can access stock quotes, stock charts, and other financial data to track their portfolios and get individualized financial advice. Yahoo Finance also provides tools like financial calculators and other resources to assist consumers in making educated investing decisions. 

Prerequisites

To follow this article you will need the following installed and activated on your PC. Also, feel free to fork the GitHub Repo for the code and other necessary materials.

yfinance Library

The yfinance library in Python allows you to easily interact with Yahoo Finance API, to retrieve historical financial data such as stock market information, financial statement,s and stock quotes. The library provides you numerous access to data such as historical prices, dividends, and splits for a given stock.

The yfinance can be installed in your Python IDE with a simple command as  pip install yfinance.

Now, that the yfinance library is installed let’s go into the project at hand.

Disclaimer: I am not a financial expert. Therefore, this article is for educational purposes and only aims to show how to connect to Yahoo Finance API data using the Python library.

Import all Necessary Libraries

The following libraries are needed for the project in order to pull price data directly from the Yahoo finance library and create a predicting model of it.

https://gist.github.com/kiddojazz/187b947b309324c6385f9b5e16c03751

 

Get Ticker Data from the Yahoo Finance site

A ticker symbol in finance refers to a unique identifier used in identifying publicly traded companies and their stocks. 

Stocks are usually listed on various stock exchange platforms such as the NASDAQ stock exchange, NYSE (New York Stock Exchange), Tokyo Stock Exchange (TSE),  London Stock Exchange (LSE)  and so much more.

Create a Ticker variable

Let’s pull Google financial data from the Yahoo finance API using the yfinance library, with the start date of 1st January 2010 to today’s date. The Google ticker name is “GOOGL” .

https://gist.github.com/kiddojazz/3ba5c72deadd2e5cafe3259f3837b324

Visualization

Create a line chart to check the trend of Google prices which changes over a continuous interval or period of time.

https://gist.github.com/kiddojazz/3e72d899d0a7bc9852e2dbce83cc9df6

Create a New DataFrame of the “Close” Column

Drop other columns except for the close column, as our analysis will be based on it.

https://gist.github.com/kiddojazz/65c9ce625e0bc8756c13d8aefba7ffda

Standardize our Data

Data standardization involves the transformation of data so that it has a mean of zero and a standard deviation. The purpose of standardizing data is to give it a uniform scale across all measurement units so that it can be compared and modeled consistently.

We will be using the Min-Max scaling, which is a technique that scales the data by transforming the data to be between a specific range, for example, between 0 and 1.

https://gist.github.com/kiddojazz/4104276888ecd08ea5dafd6b310050a6

Create Training Model

The data will be split into x_train and y_train.

https://gist.github.com/kiddojazz/e0791337ef3059272fd776bcf22618a4

#Convert the x_train and y_train to NumPy arrays
x_train, y_train = np.array(x_train), np.array(y_train)

 

https://gist.github.com/kiddojazz/b8b88977fbc0bac6a359571415ed73a0

Create your Model

The model used for this forecast will be the LSTM model. Long Short-Term Memory(LSTM) Network is an advanced, recurrent neural network capable of learning order dependence in sequence prediction problems. In addition, it can resolve the RNN’s vanishing gradient issue.

Let’s build the LSTM Model

Let’s start by importing all necessary models for the Neural Network.

from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.layers import Dense, LSTM
from tensorflow.keras.models import Sequential

 

Create a Simple LSTM Model

https://gist.github.com/kiddojazz/a0e39230b6f8eb62664d10b8b273daba

Compile Model

Before training a model in TensorFlow Keras, the learning process is set up using the compile() method. It takes some arguments like optimizer and loss.

  • Optimizer: The optimization algorithm to be utilized during training. Common choices include ‘adam’, ‘sgd’, and ‘rmsprop’.
  • Loss: The loss function to be utilized during training can be specified using this option. Mean squared error, category cross-entropy, and binary cross-entropy are popular options.

https://gist.github.com/kiddojazz/4096db9fa0ed3213a414eb12d8a21f57

Fit Model

At this stage, we are going to train the model using the “fit()”.

https://gist.github.com/kiddojazz/df5892d153ab548c198e926b37fb356b

Create a test data

We need to spit the test data from the training data. The test data will be used to test how accurately the model was created.

https://gist.github.com/kiddojazz/e58a4bfaf18e5b59dc35d1061a98a30b

Convert Data to Numpy Array

We need to convert data to NumPy array because it allows for efficient numerical operations on the data.

https://gist.github.com/kiddojazz/3d2ba81e97a3402b761a140c87cf86cb

https://gist.github.com/kiddojazz/f1c1641d70907679da9692b4745a8771

 

https://gist.github.com/kiddojazz/0613b2ef15b06e37ea9445db5a5bc374

Prediction Chart

We create a line chart to compare the predicted and validation model. You will notice the model performs well.

https://gist.github.com/kiddojazz/4dfe0bbaf84bf8046f7511c5cadbd30b

https://gist.github.com/kiddojazz/ddfaac1dfe4436de5d5376c7559d182f

Conclusion

In this article, you learned how to connect Python to Yahoo Finance API to pull historical finance data. Additionally, we created a model using Tensorflow Keras to forecast based on historical data.

For this project, I will mention the model is not 100% accurate and will advise further improvements like the use of hyperparameters tuning or the use of a pre-trained model to get higher accuracy.

Feel free to connect with me on LinkedIn: Temidayo Omoniyi & Twitter: Kiddojazz.

Leave a Reply