Can we predict stock prices with Prophet?

Facebook recently released a API package allowing access to its forecasting model called prophet. According to the underling post:

It's not your traditional ARIMA-style time series model. It's closer in spirit to a  Bayesian-influenced generalized additive model, a regression of smooth terms. The model is resistant   to the effects of outliers, and supports data collected over an irregular time scale (ingliding presence of missing data) without the need for interpolation. The underlying calculation engine is Stan; the R and Python packages simply provide a convenient interface.  

After reading it, I got really curious about the predictive performance of this method for stock prices. That is, can we predict stock price movements based on prophet? In this post I will investigate this research question using a database of prices for the SP500 components.

Before describing the code and results, it is noteworthy to point out that forecasting stock returns is really hard! There is a significant body of literature trying to forecast prices and to prove (or not) that financial markets are efficient in pricing publicly available information, including historical prices. This is the so called efficient market hypothesis. I have studied it, tried to trade for myself for a while when I was a Msc student, advised several graduate students on it, and the results are mostly the same: it is very difficult to find a trade signal that works well and is sustainable in real life.

This means that most of the variation in prices is due to random factors that cannot be anticipated. The explanation is simple, prices move according to investor’s expectation from available information. Every time that new (random) information, true or not, reaches the market, investor’s update their beliefs and trade accordingly. So, unless, new information or market expectation have a particular pattern, price changes will be mostly random.

Even with a body of evidence against our research, it is still interesting to see how we could apply prophet in a trading setup.

The data

First, let’s download stock prices for some components of the SP500 index since 2010.



all.stocks <- GetSP500Stocks()$ticker
my.stocks <- sample(all.stocks, 20) <- as.Date('2015-01-01') <- Sys.Date()
df.stocks <- BatchGetSymbols(my.stocks, 
## Running BatchGetSymbols for:
##    Downloading data for benchmark ticker | Found cache file
## DLTR | yahoo (1|20) | Found cache file - Well done!
## COP | yahoo (2|20) | Found cache file - Looking good!
## KIM | yahoo (3|20) | Found cache file - Well done!
## MO | yahoo (4|20) | Found cache file - You got it!
## HES | yahoo (5|20) | Found cache file - Looking good!
## HRL | yahoo (6|20) | Found cache file - Feels good!
## ROP | yahoo (7|20) | Found cache file - OK!
## EXPE | yahoo (8|20) | Found cache file - Nice!
## JPM | yahoo (9|20) | Found cache file - Feels good!
## BR | yahoo (10|20) | Found cache file - Youre doing good!
## MCK | yahoo (11|20) | Found cache file - Got it!
## TTWO | yahoo (12|20) | Found cache file - Feels good!
## CSX | yahoo (13|20) | Found cache file - Well done!
## FE | yahoo (14|20) | Found cache file - Boa!
## PNC | yahoo (15|20) | Found cache file - Good stuff!
## MSI | yahoo (16|20) | Found cache file - Good stuff!
## CNC | yahoo (17|20) | Found cache file - You got it!
## EQT | yahoo (18|20) | Found cache file - Well done!
## EFX | yahoo (19|20) | Found cache file - Feliz que nem lambari de sanga!
## NWL | yahoo (20|20) | Found cache file - Good stuff!

Now, let’s understand how prophet works. I was happy to see that the interface is quite simple, you offer a time series with input y and a date vector with ds. If no further custom option is set, you are good to go. My only complain with prophet is that that the function outputs lots of messages. They really should add a quiet option, so that the user doesn’t have to use capture.output to silent it. Have a look in the next example with a dummy series:


df.est <- data.frame(y = rnorm(100), ds = Sys.Date() + 1:100)

m <- prophet(df = df.est)
## Disabling yearly seasonality. Run prophet with yearly.seasonality=TRUE to override this.
## Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.
## Initial log joint probability = -15.856
## Optimization terminated normally: 
##   Convergence detected: absolute parameter change was below tolerance

The next step is to think about how to structure a function for our research problem. Our study has two steps, first we will set a training (in-sample) period, estimate the model and make forecasts. After that, we use the out-of-sample data to test the accuracy of the model.

The whole procedure of estimating and forecasting will be encapsulated in a single R function. This is not the best way of doing it but, for our simple example, it will suffice. My function will take as input a dataframe and the number of out-of-sample forecasts. Based on the adjusted closing prices, we calculate returns and feed 1:(nrow(df)-nfor) rows for the estimation. The last nfor rows are used for testing the accuracy of the model. For example, if I have a vector with 1000 returns and nfor=5, I use observations from 1:995 for estimating the model and 996:1000 for testing the forecasts. The function returns a dataframe with the predictions for each horizon, its error, among other things. Here’s the function definition:

est.model.and.forecast <- function(, nfor=5){
  # Estimated model using prophet and forecast it
  # Args:
  # - A dataframe with columns price.adjusted and
  #   nfor - Number of out-of-sample forecasts
  # Returns:
  #   A dataframe with forecasts and errors for each horizon.
  my.ticker <-$ticker[1]
  #cat('\nProcessing ', my.ticker) <- %>%
    select(, ret.adjusted.prices)
  names( <- c('ds', 'y')
  idx <- nrow( - nfor
  df.est <-[1:idx, ]
  df.for <-[(idx + 1):nrow(, ]
    m <- prophet(df = df.est)
  # forecast 50 days ahead (it also includes non trading days)
  df.pred <- predict(m,
                                           periods = nfor + 50))
  df.pred$ds <- as.Date(df.pred$ds)
  df.for <- merge(df.for, df.pred, by = 'ds')
  df.for <- select(df.for, ds, y, yhat)
  # forecast statistics
  df.for$eps <- with(df.for,y - yhat)
  df.for$abs.eps <- with(df.for,abs(y - yhat))
  df.for$perc.eps <- with(df.for,(y - yhat)/y)
  df.for$nfor <- 1:nrow(df.for)
  df.for$ticker <- my.ticker

Let’s try it out using the by function to apply it for each stock in our sample. All results are later combined in a single dataframe with function

out.l <- by(data = df.stocks,
            INDICES = df.stocks$ticker, 
            FUN = est.model.and.forecast, nfor = 5)

my.result <-, out.l)

Lets have a look in the resulting dataframe:

##               ds           y         yhat         eps    abs.eps  perc.eps
## BR.1  2018-10-22  0.01128591 0.0007299612  0.01055595 0.01055595 0.9353210
## BR.2  2018-10-23 -0.01183634 0.0019596670 -0.01379600 0.01379600 1.1655636
## BR.3  2018-10-24 -0.03764540 0.0008153671 -0.03846077 0.03846077 1.0216591
## BR.4  2018-10-25  0.03680654 0.0006084042  0.03619814 0.03619814 0.9834702
## BR.5  2018-10-26 -0.02083691 0.0011457469 -0.02198266 0.02198266 1.0549864
## CNC.1 2018-10-22 -0.01029557 0.0026125491 -0.01290812 0.01290812 1.2537548
##       nfor ticker
## BR.1     1     BR
## BR.2     2     BR
## BR.3     3     BR
## BR.4     4     BR
## BR.5     5     BR
## CNC.1    1    CNC

In this object you’ll find the forecasts (yhat), the actual values (y), the absolute and normalized error (abs.eps, perc.eps).

For ou first analysis, let’s have a look on the effect of the forecasting horizon over the absolute error distribution.


p <- ggplot(my.result, aes(x=factor(nfor), 
p <- p + geom_boxplot()


We do find some positive dependency. As the horizon increases, the forecasting algorithm makes more mistakes. Surprisingly, this pattern is not found for nfor=5 and nfor=4. It might be interesting to add more data and check if this effect is robust.

Encopassing test

A simple and powerful test for verifying the accuracy of a prediction algorithm is the encompassing test. The idea is to estimate the following linear model with the real returns (\(R_t\)) and its predictions (\(\hat{R} _t\)).

\[y_t = \alpha + \beta\hat{y_t} + \epsilon _t\]

If the model provides good forecasts, we can expect that \(\alpha\) is equal to zero (no bias) and \(\beta\) is equal to 1. If both conditions are true, we have that \(R_t = \hat{R} _t + \epsilon _t\)$, meaning that our forecasting model provides an unbiased estimator of the predicted variable. In a formal research, we could use a Wald test to verify this hypothesis jointly.

First, lets find the result of the encompassing test for all forecasts.

lm.model <- lm(formula = y ~yhat, data = my.result)
## Call:
## lm(formula = y ~ yhat, data = my.result)
## Residuals:
##       Min        1Q    Median        3Q       Max 
## -0.132266 -0.014443 -0.001316  0.017713  0.093339 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)   
## (Intercept) -0.010946   0.003233  -3.386  0.00102 **
## yhat         1.195046   0.821047   1.456  0.14872   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## Residual standard error: 0.03184 on 98 degrees of freedom
## Multiple R-squared:  0.02116,    Adjusted R-squared:  0.01117 
## F-statistic: 2.119 on 1 and 98 DF,  p-value: 0.1487

As you can see, it didn’t work very well. The constant is significant, which indicates a bias. The value of 1.1950463 is not very close to 1. But, it could be the case that the different horizon have different results. A longer horizon, with bad forecasts, will be affecting short horizons with good forecasts. Lets use dplyr to separate our model according to nfor.

models <- my.result %>%
  group_by(nfor) %>%
  do(ols.model = lm(data = ., formula = y ~ yhat ))

We report the results with texreg::screenreg.

## ============================================================
##              Model 1   Model 2   Model 3    Model 4  Model 5
## ------------------------------------------------------------
## (Intercept)  -0.01 **  -0.01 **  -0.03 ***   0.01    -0.01  
##              (0.00)    (0.00)    (0.00)     (0.01)   (0.01) 
## yhat          1.55     -0.58      0.09       2.35     2.13  
##              (0.87)    (1.19)    (1.26)     (2.86)   (1.57) 
## ------------------------------------------------------------
## R^2           0.15      0.01      0.00       0.04     0.09  
## Adj. R^2      0.10     -0.04     -0.06      -0.02     0.04  
## Num. obs.    20        20        20         20       20     
## RMSE          0.01      0.02      0.02       0.05     0.03  
## ============================================================
## *** p < 0.001, ** p < 0.01, * p < 0.05

Well, the R2 shows some evidence that shorter horizons have better results in the encompassing test. But, we got some negative betas! This means that, for some horizons, it might be better to take the opposite suggestion of the forecast!

Trading based on forecasts

In a practical trading applications, it might not be of interest to forecast actual returns. If you are trading according to these forecasts, you are probably more worried about the direction of the forecasts and not its nominal error. A model can have bad nominal forecasts, but be good in predicting the sign of the next price movement. If this is the case, you can still make money even though your model fails in the encompassing test.

Let’s try it out with a simple trading strategy for all different horizons:

  • buy in end of day t if forecast in t+1 is positive and sell at the end of t+1
  • short-sell in the end of day t when forecast for t+1 is negative and buy it back in the end of t+1

The total profit will be given by:

my.profit <- sum(with(my.result, (yhat>0)*y + (yhat<0)*-y))
## [1] 0.4983155

Not bad! Doesn’t look like much, but remember that we have a few trading days and this return might be due to a sistematic effect in the market. Let’s see how this result compares to random trading signals.

n.sim <- 10000

monkey.ret <- numeric(length = n.sim)
for (i in seq(n.sim)) {
  rnd.vec <- rnorm(length(my.result$y))
  monkey.ret[i] <- sum( (rnd.vec>0)*my.result$y + (rnd.vec<0)*-my.result$y )

temp.df <- data.frame(monkey.ret, my.profit)
p <- ggplot(temp.df, aes(monkey.ret)) 
p <- p + geom_histogram()
p <- p + geom_vline(aes(xintercept =  my.profit),size=2)
p <- p + labs(x='Returns from random trading signals')
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

The previous histogram shows the total return from randomnly generated signals in 10^{4} simulations. The vertical line is the result from using prophet. As you can see, it is a bit higher than the average of the distribution. The total return from prophet is lower than the return of the naive strategy in 7.07 percent of the simulations. This is not a bad result. But, notice that we didnt add trading or liquidity costs to the analysis, which will make the total returns worse.

The main results of this simple study are clear: prophet is bad at point forecasts for returns, specially for longer horizons, but does quite better in directional predictions. It might be interesting to test it further, with more data, adding trading costs, other forecasting setups, and see if the results hold.

Marcelo S. Perlin
Associate Professor of Finance


comments powered by Disqus