Working with Stock Market Time Series Data using Facebook Prophet

Prateek Majumder 30 Oct, 2022 • 5 min read

This article was published as a part of the Data Science Blogathon

Time series data consists of a  set of observations in which the data varies with time. Time-series data analysis consists of working with this data and gather actionable insight from the data. Examples of time-series data would be Prices of Petrol with time, Rainfall over time, Stock prices over time.

 

Importance of working with Time Series data

Time series data helps in various business cases, like predicting sales over time, forecasting visitors to a website, or the number of users. Such things help in optimizing various aspects of an organization. Often, the data points taken in Time series analysis have internal relations or some unseen structure like a trend or seasonal variations. These are often not visible with just a look at the data. A detailed study is needed in those cases. The observed data can be used for various purposes and can be modeled according to our needs.

Stock Market Time Series using Facebook Prophet 1
Time Series Data

Applications of Time Series Analysis

There are various applications of Time Series Analysis and Time Series Models, some of them are :

  1. Sales Forecasting
  2. Economic Forecasting
  3. Weather Forecasting
  4. Stock Market Analysis
  5. Product Demand Analysis
  6. Population Growth/ Census

and others.

Today, we will be looking at the stock market analysis part. Stock Markets are always uncertain and erratic, it takes years of study and a lot of experience to understand the trend of the market. As the stock market involves a lot of work, a large number of participants and numerous factors make predictions about stock market trends very tough. The stock price of a company fluctuates a lot during the day, let alone the whole week. All these things make decisions very tough to make, in the case of the stock market. So, let us try working with Facebook Prophet, and see if it solves our problems.

What is Facebook Prophet?

Facebook Prophet is an open-source forecasting method implemented in Python and R. It provides automated forecasts. Prophet is used in many applications relating to time series data and to gather sample time forecast data. In the case of such models, getting exact future data is never possible, but we can somehow get the future trend.

You can install Prophet using :

pip install prophet

Getting some Stock Market stock market data

We shall be web scraping Facebook’s stock data using Yahoo Finance. Yahoo Finance makes it very easy to extract stock data, hence my choice here. If necessary you can make any other choice. With Yahoo Finance, we get the data as simple as using dataframes, which can be easily worked in Python.

Let us proceed with the code, I will leave a link to the complete code at the end of the blog.

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from prophet import Prophet

Some important libraries are imported, more libraries to be imported.

import warnings
warnings.filterwarnings('ignore')  # Hide warnings
import datetime as dt
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
import pandas_datareader.data as web
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.dates as mdates

Now all important libraries are imported.

#getting the stock data using yahoo finance
start = dt.datetime(2010, 1, 1)
end = dt.datetime(2016,1,1)
df = web.DataReader("FB", 'yahoo', start, end)  # Collects data
#prices in USD

We took data from 2010 to the end of 2015. This is marked by using (2010,1,1) at the start date-time and using (2016,1,1) at the end date. This way, taking the time frame is done and it is quite easy to proceed with Yahoo Finance.

And stock code for Facebook is FB and yahoo for Yahoo finance. A point to be noted is that one can use any Company stock data or any other type of time-series data.

Facebook Prophet data

This is how the data looks like, you can find more about these stock terminologies by checking out this article. We are interested in the Date and Adjusted Close values here. As, Date will count as the Time Series data index and Adj Close will be our time series data. In the data, stock values are mentioned as the closing price and the adjusted closing price. The closing price is the raw price, which is just the cash value of the last transacted price before the closure of the stock market for the day. The adjusted closing price factors in anything that might affect the stock price after the market closes.

Now, to get the date as a column.

df.reset_index(inplace=True)
data=df[["Date","Adj Close"]]
data=data.rename(columns={"Date": "ds", "Adj Close": "y"})
#now it is usable for FB Prophet

data.head()

Now, the data can be used in FB Prophet.

Facebook Prophet time series

Now the data has length 911.

911

We split the data into train and test parts.

df_train=data[0:500]
df_test=data[500:911]

After this, we create the Prophet model. And use the training data to train the model.

m = Prophet()
m.fit(df_train)
prophet forecaster

Now, let us make some predictions.

future = m.make_future_dataframe(periods=411)
forecast = m.predict(future)
forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()

This is what is generated. A data frame with the time index and other values.

what is yhat

“ds” indicates the Date data, “yhat” indicates the predicted time series data. “yhat_lower” and “yhat_upper” indicate the probable lower and upper limit of how much the value can go.

 Let us plot the data.

fig1 = m.plot(forecast)

The plot looks as such.

plot

We had data till 2014-06, after that the data generated is generated by the Prophet model. Let us plot the other components.

Prophet model

According to the model, the trend of the curve is almost upward, and that has been the case for FB stock. Facebook has been a profitable company, and hence stock prices rise up.

Let us compare it to the real stock data of FB in that time period.

time period

We can see that, for the case of Facebook stock, there was an increase in the period. We can assume that FB prophet cannot obviously predict accurate stock values, but can predict an overall trend in time series data.

 

Conclusion

With better research and better tuning, more accurate results can be predicted. FB Prophet can be used to do efficient Time Series analysis, as it provides fast and simple to use methods for this purpose.

Get the full code on Kaggle.

Stock Price Prediction with FB Prophet

Connect with me on Linkedin

Thank You.

The media shown in this article on Stock Market Time Series using Facebook Prophet are not owned by Analytics Vidhya and is used at the Author’s discretion. 

 

Prateek Majumder 30 Oct 2022

Prateek is a final year engineering student from Institute of Engineering and Management, Kolkata. He likes to code, study about analytics and Data Science and watch Science Fiction movies. His favourite Sci-Fi franchise is Star Wars. He is also an active Kaggler and part of many student communities in College.

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Clear

Related Courses

Time Series
Become a full stack data scientist