How To Use Facebook’s Prophet AI to Forecast FB Stock Price

This article is not promoting any trade suggestions or the use of AI in financial decision-making. It is for informational purposes only.

Facebook’s AI Prophet algorithm is being used by machine learning enthusiasts and traders to predict the future price of stocks. The goal of this article is to rebuild a section of Kaggle code for importing and analyzing stock data within Google’s CoLab using Prophet to predict future stock prices. Given Facebook (ticker symbol: FB) has earnings this week what better ticker to test Prophet.

The Prophet predictions above put the close between $315 and $343 for Monday 2021-07-26, which would mean a 7% drop in price from Friday’s close of $369.79 “if” it were to conform to its own Prophet model. To the chagrin of Facebook and investors long, this would erase Fridays’ gain of 4% and then some.

AI forecasting is evermore becoming the vogue way of conducting business. From HR candidate screening and selection to time and sales business projections, machine learning is becoming more dominant. Furthering this, the escapades of DeepMind’s AlphaGo and AlphaZero have given the individual something they can relate to when it comes to difficulties of strategy and problem-solving. Keeping in mind AI uses models for processing and interpreting data, Facebook’s AI model “Prophet” is considered “very good” [Benram] for time-series, sequential data. It is described as “less applicable” when you need to analyze the influence of multiple data sets. Meaning this particular model can not account for the influence of other market forces or anomalies outside the day-to-day changes in price. Nonetheless, the Prophet AI model is being used for predictions on trading websites concerning financial decision-making. While there have been some interesting strides in modeling and subsequent forecasting, are trading decisions based on Facebooks’ Prophet a good idea?

Fro m: Seven Tips for Forecasting Cloud Costs (with FB’s Prophet) by Gad Benram

Working with code published in a blog article by Prateekmaj21 dated May 2021 for Kaggle, the code is re-written here to function with Google’s Colab. The sections changed include importing data using yfinance and adjusting the modeling/test set sizes along with the forward-looking prediction time frame. The code used is at the bottom of this article.

The data sample used begins with the close of 2012-05-18 until the close on 2021-07-23 (2310 data points). 2300 data points were used for modeling and 10 data points or training (more below on reasoning). The prediction output is found in the chart below. The column labels represent the data row (Header label), date (ds), model forecast value (yhat), and the upper and lower confidence intervals (yhat_lower and yhat_upper) respectively.


Some quick data interpretation and comparison:

Per Prophet, if we were going to trade $FB on Monday, July 26 the model predicts the price of Facebook to be between the confidence limits of $315.28 and $343.60. Ideally, the suggested price should be in the vicinity of the yhat value of $329.37. Projections were made for 20 days into the future to include the time frame of Facebooks’ upcoming earnings announcement on July 28th, 2021 after 4 pm. You might be thinking “Great, now I know what is going to happen! Let’s make some money!”, … but not so fast. Don’t go investing your life savings in this “premonition”. Let’s consider a past prediction to see how it measures up.

To examine a prior prediction two graphs overlaid. The black and gold graph lines are actual price closes of FB, with the gold representing data after 2019-09-24. The blue data represents the Prophet modeling, testing and forecast output. The blue data was modeled and tested prior to 2019-07-24 (where the black data ends). The deviation between the gold line and the blue line shows the increasing difference (error) as time advances. The Prophet’s prediction appears to only be reliable for approximately 2-4 weeks (the interface of the three colored lines). Beyond this, only a short time period in 2020 did the prediction and actual data agree again. Given the model can’t handle anomalies, it would be reasonable to pose the question would the actual stock price have come down within the yhat_lower and yhat_upper confidence limits had it not been for the coronavirus pandemic? We will never know. What we do know is the forward-looking 2 year Prophet prediction is nowhere near the price of where FB is today.

As of 2021-07-23 Facebook closed at $369.79, up 4%. The Motley Fool concluded the stellar day was spurred on by three factors:

The social media company’s stock is getting a boost from Snap’s stellar second-quarter results.

Facebook management guided for a likely revenue growth acceleration in Q2.

The tech company reports earnings next week.

Motley Fool

Several observations can be drawn from this trial model, the most immediate being that the predictive model appears only valid in the short term. Price appears (and is known to be) influenced outside the model. The Prophet model cannot account for social or economic effects on price. Events such as the drastic price dip in 2020 due to the coronavirus, or similarly, $FB suggested response to $SNAP’s price change is simply beyond prediction.

Similar AI statistical predictive models are tantalizing, but they also have limitations. Like Facebooks’ Prophet, AI cannot reliably account for a stock’s long-term price action or performance any more than they can an individuals’ worth as an employee. There are simply too many variables and influences. While impressive, two things are apparent from the AlphaGo experiment (watch the AlphaGo documentary here) – DeepMind has some brilliant data scientists, and AI remains anonymously fallible. Each of these projects was a composite decision-making process that statistically empowered DeepMind’s AI. DeepMind may have only lost a single game to the champion Lee Sedol, but the power of thought thru the mind of Lee Sedol proved far more intriguing. DeepMind played Go by exhausting all the possible predictable 2D-dimensional moves. Lee Sedol I suspect won that single match because he possessed intuition, creativity and thought beyond what AI is capable of – at least until it has been trained to model for it. Statistics and outside-the-box thinking are not generally thought of as compatible trains of thought.

To answer the question of usability, a person should consider AIs’ application – understandably the greater the number of variables the more difficulty in an accurate prediction. Using Facebooks’ Prophet on a singular security, without considering other factors such as sector and market dynamics, social sentiment, and the effects of governmental decisions on the economy, make such predictions difficult. Using AI will require a trader/investor to have an understanding of confidence limits, probability of outcome, and other statistics when considering risk versus reward arguments. AI in general as a sole source of decision-making currently is haphazard at best without an understanding of risk management. One of the best case uses is to utilize Prophet is in conjunction with other trading tools in the decision-making process. Tradytics (<- link) is one such website demonstrating the use of AI-based tools in conjunction with other trading metrics. In fact, Tradytics encourages users of their services to reference all their tools to make the best possible informed trading decision. Individuals interested should research further before making any decisions based on Artificial Intelligence and Machine Learning. As always, trading is risky and all your money can be lost. This is not trading advice and is for entertainment and informational purposes only.

Follow-up Tueday 27 July 2021

Let’s give some reflection on the past two days of trading, in consideration of objective, pessimistic, contrarianism, – price is not making any great leaps to conform to within the limits of the Prophet algorithm. Monday price action reflected roughly an additional gain of +0.8% ($369.79 to $372.46); only to be followed by Tuesday’s decline of -1.25% (the model projected the change in price for Monday/Tuesday to be -3.24% and + 0.13% respectfully). The actual price of $FB remains considerably higher than the upper confidence limit of the model’s prediction ($342.94).

It was suggested in the Prateekmaj21 blog that while price didn’t conform with the confidence limits of their experimental projections that the increase in actual price was trending in the same direction as the Prophet model. There remain factors outside the consideration of the model influencing Prophet’s ability to account for. It will be interesting to see the results over the course of the next few days, keeping in mind the computed prediction by Prophet may still be a coincidence.

Generalized, non-optimized, Colab Prophet code:

The following code should work within Google Colab. Copy, paste and Shazam, you’re using AI (use at your own risk):

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

#pip install pystan==

!pip install prophet

from prophet import Prophet

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 as web
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

import matplotlib.dates as mdates

#getting the stock data using yahoo finance this section was re-written to use yfinance

!pip install yfinance
import yfinance as yf
# replace “FB” with the security of your interest
tick = yf.Ticker(‘FB’)

df = tick.history(period=”max”, auto_adjust=True)






data=data.rename(columns={“Date”: “ds”, “Close”: “y”})

#now it is usable for FB Prophet




#len(data) returns the length of a list, string, dictionary, or any other iterable data format in Python
# divide the len(data) result between your df_train and df_test – it is best to make sure the data does not overlap
# example: if len(data) returns 2310, training with 2300 of those values and testing with 10 would look like
# df_train=data[0:2300]
# df_test=data[2301:2310]
# try with various intervals to test results


m = Prophet()

# set the value for “periods= ” to the number of days you want to explore into the future from the end of the df_train data set
future = m.make_future_dataframe(periods=20)

forecast = m.predict(future)

forecast[[‘ds’, ‘yhat’, ‘yhat_lower’, ‘yhat_upper’]].tail()

fig1 = m.plot(forecast)

fig2 = m.plot_components(forecast)


df.set_index(“Date”, inplace=True)

plt.figure(figsize=(24, 16))
plt.title(‘CLOSE’, fontsize = 20)
plt.ylabel(‘Stock Value’)

Please like, share and comment.

Featured image attribution: “dinero facebook” by clasesdeperiodismo is licensed under CC BY-SA 2.0

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *