Python: Predict stock prices

Saurabh Singh
2 min readAug 16, 2021

Flavour of the scripting in 20’s is Python. It comes with all the best spices of it’s predecessor and many more. It’s simple and has a strong community support due to which it’s growing at such a pace.

However even after with all the spices I love it for it’s implementation in the real-world and you don’t need to be an expert just knowing the right libraries and using them correctly helps you to achieve the end goal. This article is for one such flavour fbprophet.

fbprophet

It’s an open source library released by Facebook that can be used for forecasting time series data. It can help you get the advanced trend which can fit in any time frame like monthly ,yearly ,weekly etc which usually require an individual to have great amount of statistics and data science knowledge.

A single line command and this powerful library is at your exposer.

Install fbprophet :

pip install fbprophet

Let’s try some real-time project like predicting stock prices trend. We can use yfinance (Yahoo Finance) library to get the real-time stock data.

Import Required Libraries :

import yfinance as yf
import pandas as pd
import fbprophet as fb

Using yfinance.downloads we will fetch all the history records of Infosys India stocks, it will provide us a pandas DataFrame.

data = yf.download(tickers='INFY.NS', period='max').sort_index(ascending=False)

Now we need to define a model using fbprophet.Prophet which will be used for prediction.

model = fb.Prophet()

Before providing the data to the model to fit, we will need to rename our target columns to ‘ds’ and ‘y’ its mandatory for Prophet library to work.

Note: ‘ds’ should be the time-series and ‘y’ is the feature column we plan to predict.

data = data.reset_index()
data.rename(columns={'Date':'ds', 'Open' : 'y'}, inplace=True)

Now we can fit the above DataFrame to the model, this will help the model understand the historical data and predict the future :

model.fit(data)

Library also helps you create a future time-series in just one line code :

future_date = model.make_future_dataframe(periods=90)

By default periods parameter takes the days (above command will add next 90 days in the time-series) :

predict = model.predict(future_date)

That’s it, you can plot the predict on a line chart and see trend and various other options. Sample graph plot is shown below :

Infosys Stock Trend Prediction (INFY.NS)

--

--

Saurabh Singh

Cloud Data Engineer | 1 x GCP | 3 x AWS | Big Query | Redshift | Airflow | Python | PySpark | Ab Initio | BI | Analytics |