How to do it...

Execute the following steps to decompose the gold prices time series using Facebook's Prophet and create forecasts for one year ahead.

  1. Import the libraries and authenticate with Quandl:
import pandas as pd
import seaborn as sns
import quandl
from fbprophet import Prophet

QUANDL_KEY = '{key}' # replace {key} with your own API key
quandl.ApiConfig.api_key = QUANDL_KEY
  1. Download the daily gold prices and rename the columns:
df = quandl.get(dataset='WGC/GOLD_DAILY_USD',
start_date='2000-01-01',
end_date='2005-12-31')

df.reset_index(drop=False, inplace=True)
df.rename(columns={'Date': 'ds', 'Value': 'y'}, inplace=True)
  1. Split the series into the training and test sets:
train_indices = df.ds.apply(lambda x: x.year) < 2005
df_train = df.loc[train_indices].dropna()
df_test = df.loc[~train_indices].reset_index(drop=True)
  1. Create the instance of the model and fit it to the data:
model_prophet = Prophet(seasonality_mode='additive')
model_prophet.add_seasonality(name='monthly', period=30.5,
fourier_order=5)
model_prophet.fit(df_train)
  1. Forecast the gold prices and plot the results:
df_future = model_prophet.make_future_dataframe(periods=365)
df_pred = model_prophet.predict(df_future)
model_prophet.plot(df_pred)

The resulting plot is as follows:

The black dots are the actual observations of the gold price. The blue line representing the fit does not match the observations exactly, as the model smooths out the noise in the data (also reducing the chance of overfitting). An important feature is that Prophet quantifies uncertainty, which is represented by the blue intervals around the fitted line.

  1. Inspect the decomposition of the time series:
model_prophet.plot_components(df_pred)

The decomposition is presented in the following plot:

Upon closer inspection, we can see that the overall trend is increasing and that the gold price seems to be higher during the beginning and the end of the year, with a dip in the summer. On the monthly level, there is some movement, but the scale is much smaller than in the case of the yearly pattern. There is not a lot of movement in the weekly chart (we do not look at weekends as there are no prices for weekends), which makes sense because, with a decrease in the time scale, the noise starts to wash out the signal. For this reason, we might disable the weekly level altogether.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.195.225