Stock Price Prediction With FB Prophet

Evafachria
7 min readSep 26, 2023
https://www.analyticsvidhya.com/

Introduction

There are numerous ways to predict stock prices using machine learning in Python. You can employ simple methods like linear regression to model the relationship between various economic factors and stock prices or utilize ARIMA (Autoregressive Integrated Moving Average), which is a commonly used statistical model for forecasting time series data, to forecast stock prices by modeling trends and seasonal patterns in the data. Alternatively, you can opt for more complex methods such as Long Short-Term Memory (LSTM), which can understand intricate patterns in stock price data and predict future price changes. Additionally, you can use Time Series Analysis techniques like time series decomposition, autocorrelation, and others to comprehend patterns in stock price data and make predictions. The choice of method depends on the data’s complexity, the amount of historical data available, and the specific goals of your prediction task. Specifically for time-series analysis, Facebook has released Facebook Prophet, which is another valuable tool for time series forecasting. It is designed to capture seasonality and holiday effects in data, making it suitable for predicting stock prices with such patterns. In this article, we will delve deeper into the use of Facebook Prophet for predicting stock prices.

FB Prophet

Prophet is an open-source forecasting tool developed by Facebook’s Core Data Science team. It is designed to simplify the process of time series forecasting, making it accessible to users with varying levels of expertise in statistics and forecasting techniques. Prophet is particularly well-suited for forecasting problems that involve daily or seasonal patterns, holiday effects, and irregular data.

Here are some key features and explanations about Prophet:

  1. Additive Decomposition Model: Prophet decomposes a time series into three main components: trend, seasonality, and holidays. This decomposition is additive, meaning that the time series is modeled as the sum of these three components. This approach is intuitive and often fits well with real-world data.
  2. Trend Component: The trend component captures the underlying direction of the data. It can be either linear or logistic, depending on the nature of the data. Prophet allows for flexible trend modeling, including the ability to handle abrupt changes and outliers.
  3. Seasonality: Prophet can model yearly and weekly seasonal patterns. It uses Fourier series to model seasonal effects, and users can specify the number of Fourier terms to include, allowing for different levels of seasonality complexity.
  4. Holiday Effects: Holidays and special events can significantly impact time series data. Prophet provides the ability to incorporate custom holiday definitions, enabling users to account for known holidays and their effects on the time series.
  5. Automatic Changepoint Detection: Prophet is equipped with a built-in changepoint detection algorithm, which automatically identifies points in the time series where the underlying data-generating process changes. This helps capture abrupt changes in the trend.
  6. Scalability: Prophet is designed to be scalable and can handle large datasets efficiently. It also provides options for parallelization to speed up computations.
  7. User-Friendly Interface: One of the key strengths of Prophet is its user-friendly interface. Users do not need to have a deep understanding of time series forecasting techniques to use Prophet effectively. It provides a straightforward API for data input and forecasting.
  8. Open Source and Active Community: Prophet is open-source software, which means that it is freely available for anyone to use and modify. It has an active community of users and developers, which contributes to its ongoing improvement and support.

Prophet has been used in various domains, including finance, retail, demand forecasting, and more, to make accurate predictions based on historical time series data. It’s a valuable tool for analysts and data scientists who want to perform time series forecasting with relative ease while achieving robust and interpretable results.

Stock Price Prediction Using FB Prophet in Python

Predicting stock prices using Prophet in Python can be a useful exercise for understanding how to apply the Prophet forecasting tool to real-world financial data. will demonstrate the use of FB Prophet in predicting stock prices in Python.

First to install the Prophet library from Facebook, you can use the pip command in terminal.

Pip Install Prophet

This is something simple, and you can import it directly into Python like this:

from prophet import Prophet

The next step is that you can prepare historical stock price data that you want to predict. You can obtain this data from sources like Yahoo Finance, Bloomberg, Google Finance, etc. I personally retrieve data from Yahoo Finance in CSV format and import it into Python using the code pd.read_csv. The stock data I’m working with here includes two datasets: Garuda Indonesia stock prices and Tesla stock prices.

Next, from the data, we will extract columns for date, open, high, low, close, adjusted close, and volume. However, for stock price prediction, we only need the date and close price data. Indeed, when using the Prophet library in Python for stock price prediction, it’s a requirement that you rename the columns for date and close price to ‘ds’ and ‘y’, respectively. If you don’t do this, you may encounter errors during the modeling process. This renaming is crucial for the library to recognize and process the time series data correctly.

data=data[['Date','Close']]
data.head()

data.columns=['ds','y']
data.head()

Next, we can directly predict stock prices by following the steps below.

prophet= Prophet(daily_seasonality=True)
prophet.fit(data)

The model is configured to consider daily seasonality patterns in the data. Subsequently, it is trained (or fitted) with historical time series data, allowing the model to learn and capture underlying patterns, trends, and daily seasonality effects within the dataset. Once the training is complete, the Prophet model can be used for making predictions and forecasting future values based on the learned patterns and seasonality components in the data. The code for making predictions is as follows.

future_dates=prophet.make_future_dataframe(periods=365)
predictions=prophet.predict(future_dates)

from prophet.plot import plot_plotly
plot_plotly(prophet, predictions)

This code snippet first generates a DataFrame containing future dates for the next 365 days using the Prophet model’s “make_future_dataframe” function. It then utilizes the same model to make predictions for these future dates with the “predict” method, capturing expected values and uncertainty intervals. Lastly, it imports the “plot_plotly” function from Prophet’s plotting module and uses it to create an interactive Plotly visualization, providing a clear graphical representation of the model’s forecasts, historical trends, and associated uncertainties, making it easier to analyze and understand the predicted time series data.

And the prediction result is:

The plotted trend time series above represents the predicted stock price trends for Garuda Indonesia. To determine whether these stock price predictions are accurate or not, we are attempting to test the predictions by splitting the available stock data. First, we are separating the data from the past 90 days to be used for prediction testing.

unknown_data=data.iloc[-90:]
data=data.iloc[:-90]

In this code, you are splitting your stock price dataset into two parts. The “unknown_data” DataFrame is created to contain the most recent 90 days of stock price data, which will be used for testing the accuracy of your predictions. Meanwhile, the “data” DataFrame is modified to exclude this same 90-day period, preserving only the historical data that was originally used to train the prediction model. This separation enables you to evaluate how well the model’s forecasts align with the actual stock prices for the recent 90-day period, providing insights into the accuracy of your predictions. Using the same code for prediction, which is:

prophet=Prophet(daily_seasonality=True)
prophet.fit(data)

future_dates = prophet.make_future_dataframe(periods=365)
predictions= prophet.predict(future_dates)

Then, using this code to visualize the comparison between predicted and actual prices.

import matplotlib.pyplot as plt
plt.figure(figsize=(15,8))
pred=predictions[predictions['ds'].isin(unknown_data['ds'])]

plt.plot(pd.to_datetime(unknown_data['ds']), unknown_data['y'], label='Actual')
plt.plot(pd.to_datetime(unknown_data['ds']), pred['yhat'], label='Prediction')

plt.legend()

This code snippet employs Matplotlib to create a comparison visualization between actual and predicted stock prices. It first selects the predicted values corresponding to the dates in the “unknown_data” DataFrame, aligning them for accurate comparison. Then, it plots the actual stock prices against the dates, labeling them as “Actual,” and plots the predicted prices with the label “Prediction.”

The result is:

From the results of the above graph, it appears that there is a difference between the prediction and the actual stock prices of Garuda Indonesia. This may suggest that the Prophet model used might not be well-suited for predicting the stock price movements of Garuda Indonesia accurately.

Next, we are attempting to predict Tesla’s stock price using the same method. And the result:

Conclusion

From the results of both Garuda Indonesia and Tesla stock price predictions, it is evident that both predictions are significantly off the mark and not accurate. Even from the plots, it’s clear that the actual and predicted lines are not aligned. While Prophet does offer tools for time series stock price prediction, it seems that these tools may not be particularly well-suited for accurately forecasting stock prices. Predicting stock prices is inherently challenging due to the multitude of factors at play, and models like Prophet may struggle to capture the complex dynamics of financial markets. It’s essential to recognize that while such tools can be valuable for certain time series forecasting tasks, they may not always perform optimally for stock price prediction, which remains a highly intricate and unpredictable domain.

--

--