forecaster.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  1. # Copyright (c) 2017-present, Facebook, Inc.
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the BSD-style license found in the
  5. # LICENSE file in the root directory of this source tree. An additional grant
  6. # of patent rights can be found in the PATENTS file in the same directory.
  7. from __future__ import absolute_import
  8. from __future__ import division
  9. from __future__ import print_function
  10. from __future__ import unicode_literals
  11. from collections import defaultdict
  12. from datetime import timedelta
  13. import pickle
  14. from matplotlib import pyplot as plt
  15. from matplotlib.dates import DateFormatter, MonthLocator
  16. from matplotlib.ticker import MaxNLocator
  17. import numpy as np
  18. import pandas as pd
  19. # fb-block 1 start
  20. import pkg_resources
  21. # fb-block 1 end
  22. try:
  23. import pystan
  24. except ImportError:
  25. print('You cannot run prophet without pystan installed')
  26. raise
  27. # fb-block 2
  28. class Prophet(object):
  29. def __init__(
  30. self,
  31. growth='linear',
  32. changepoints=None,
  33. n_changepoints=25,
  34. yearly_seasonality=True,
  35. weekly_seasonality=True,
  36. holidays=None,
  37. seasonality_prior_scale=10.0,
  38. holidays_prior_scale=10.0,
  39. changepoint_prior_scale=0.05,
  40. mcmc_samples=0,
  41. interval_width=0.80,
  42. uncertainty_samples=1000,
  43. ):
  44. if growth not in ('linear', 'logistic'):
  45. raise ValueError("growth setting must be 'linear' or 'logistic'")
  46. self.growth = growth
  47. self.changepoints = pd.to_datetime(changepoints)
  48. if self.changepoints is not None:
  49. self.n_changepoints = len(self.changepoints)
  50. else:
  51. self.n_changepoints = n_changepoints
  52. self.yearly_seasonality = yearly_seasonality
  53. self.weekly_seasonality = weekly_seasonality
  54. if holidays is not None:
  55. if not (
  56. isinstance(holidays, pd.DataFrame)
  57. and 'ds' in holidays
  58. and 'holiday' in holidays
  59. ):
  60. raise ValueError("holidays must be a DataFrame with 'ds' and "
  61. "'holiday' columns.")
  62. holidays['ds'] = pd.to_datetime(holidays['ds'])
  63. self.holidays = holidays
  64. self.seasonality_prior_scale = float(seasonality_prior_scale)
  65. self.changepoint_prior_scale = float(changepoint_prior_scale)
  66. self.holidays_prior_scale = float(holidays_prior_scale)
  67. self.mcmc_samples = mcmc_samples
  68. self.interval_width = interval_width
  69. self.uncertainty_samples = uncertainty_samples
  70. # Set during fitting
  71. self.start = None
  72. self.y_scale = None
  73. self.t_scale = None
  74. self.changepoints_t = None
  75. self.stan_fit = None
  76. self.params = {}
  77. self.history = None
  78. @classmethod
  79. def get_linear_model(cls):
  80. # fb-block 3
  81. # fb-block 4 start
  82. model_file = pkg_resources.resource_filename(
  83. 'fbprophet',
  84. 'stan_models/linear_growth.pkl'
  85. )
  86. # fb-block 4 end
  87. with open(model_file, 'rb') as f:
  88. return pickle.load(f)
  89. @classmethod
  90. def get_logistic_model(cls):
  91. # fb-block 5
  92. # fb-block 6 start
  93. model_file = pkg_resources.resource_filename(
  94. 'fbprophet',
  95. 'stan_models/logistic_growth.pkl'
  96. )
  97. # fb-block 6 end
  98. with open(model_file, 'rb') as f:
  99. return pickle.load(f)
  100. def setup_dataframe(self, df, initialize_scales=False):
  101. """Create auxillary columns 't', 't_ix', 'y_scaled', and 'cap_scaled'.
  102. These columns are used during both fitting and prediction.
  103. """
  104. if 'y' in df:
  105. df['y'] = pd.to_numeric(df['y'])
  106. df['ds'] = pd.to_datetime(df['ds'])
  107. df = df.sort_values('ds')
  108. df.reset_index(inplace=True, drop=True)
  109. if initialize_scales:
  110. self.y_scale = df['y'].max()
  111. self.start = df['ds'].min()
  112. self.t_scale = df['ds'].max() - self.start
  113. df['t'] = (df['ds'] - self.start) / self.t_scale
  114. if 'y' in df:
  115. df['y_scaled'] = df['y'] / self.y_scale
  116. if self.growth == 'logistic':
  117. assert 'cap' in df
  118. df['cap_scaled'] = df['cap'] / self.y_scale
  119. return df
  120. def set_changepoints(self):
  121. """Generate a list of changepoints.
  122. Either:
  123. 1) the changepoints were passed in explicitly
  124. A) they are empty
  125. B) not empty, needs validation
  126. 2) we are generating a grid of them
  127. 3) the user prefers no changepoints to be used
  128. """
  129. if self.changepoints is not None:
  130. if len(self.changepoints) == 0:
  131. pass
  132. else:
  133. too_low = min(self.changepoints) < self.history['ds'].min()
  134. too_high = max(self.changepoints) > self.history['ds'].max()
  135. if too_low or too_high:
  136. raise ValueError('Changepoints must fall within training data.')
  137. elif self.n_changepoints > 0:
  138. # Place potential changepoints evenly throuh first 80% of history
  139. max_ix = np.floor(self.history.shape[0] * 0.8)
  140. cp_indexes = (
  141. np.linspace(0, max_ix, self.n_changepoints + 1)
  142. .round()
  143. .astype(np.int)
  144. )
  145. self.changepoints = self.history.ix[cp_indexes]['ds'].tail(-1)
  146. else:
  147. # set empty changepoints
  148. self.changepoints = []
  149. if len(self.changepoints) > 0:
  150. self.changepoints_t = np.sort(np.array(
  151. (self.changepoints - self.start) / self.t_scale))
  152. else:
  153. self.changepoints_t = np.array([0]) # dummy changepoint
  154. def get_changepoint_matrix(self):
  155. A = np.zeros((self.history.shape[0], len(self.changepoints_t)))
  156. for i, t_i in enumerate(self.changepoints_t):
  157. A[self.history['t'].values >= t_i, i] = 1
  158. return A
  159. @staticmethod
  160. def fourier_series(dates, period, series_order):
  161. """Generate a Fourier expansion for a fixed frequency and order.
  162. Parameters
  163. ----------
  164. dates: a pd.Series containing timestamps
  165. period: an integer frequency (number of days)
  166. series_order: number of components to generate
  167. Returns
  168. -------
  169. a 2-dimensional np.array with one row per row in `dt`
  170. """
  171. # convert to days since epoch
  172. t = np.array(
  173. (dates - pd.datetime(1970, 1, 1))
  174. .apply(lambda x: x.days)
  175. .astype(np.float)
  176. )
  177. return np.column_stack([
  178. fun((2.0 * (i + 1) * np.pi * t / period))
  179. for i in range(series_order)
  180. for fun in (np.sin, np.cos)
  181. ])
  182. @classmethod
  183. def make_seasonality_features(cls, dates, period, series_order, prefix):
  184. features = cls.fourier_series(dates, period, series_order)
  185. columns = [
  186. '{}_{}'.format(prefix, i + 1)
  187. for i in range(features.shape[1])
  188. ]
  189. return pd.DataFrame(features, columns=columns)
  190. def make_holiday_features(self, dates):
  191. """Generate a DataFrame with each column corresponding to a holiday.
  192. """
  193. # A smaller prior scale will shrink holiday estimates more
  194. scale_ratio = self.holidays_prior_scale / self.seasonality_prior_scale
  195. # Holds columns of our future matrix.
  196. expanded_holidays = defaultdict(lambda: np.zeros(dates.shape[0]))
  197. # Makes an index so we can perform `get_loc` below.
  198. row_index = pd.DatetimeIndex(dates)
  199. for ix, row in self.holidays.iterrows():
  200. dt = row.ds.date()
  201. try:
  202. lw = int(row.get('lower_window', 0))
  203. uw = int(row.get('upper_window', 0))
  204. except ValueError:
  205. lw = 0
  206. uw = 0
  207. for offset in range(lw, uw + 1):
  208. occurrence = dt + timedelta(days=offset)
  209. try:
  210. loc = row_index.get_loc(occurrence)
  211. except KeyError:
  212. loc = None
  213. key = '{}_{}{}'.format(
  214. row.holiday,
  215. '+' if offset >= 0 else '-',
  216. abs(offset)
  217. )
  218. if loc is not None:
  219. expanded_holidays[key][loc] = scale_ratio
  220. else:
  221. # Access key to generate value
  222. expanded_holidays[key]
  223. # This relies pretty importantly on pandas keeping the columns in order.
  224. return pd.DataFrame(expanded_holidays)
  225. def make_all_seasonality_features(self, df):
  226. seasonal_features = [
  227. # Add a column of zeros in case no seasonality is used.
  228. pd.DataFrame({'zeros': np.zeros(df.shape[0])})
  229. ]
  230. # Seasonality features
  231. if self.yearly_seasonality:
  232. seasonal_features.append(self.make_seasonality_features(
  233. df['ds'],
  234. 365.25,
  235. 10,
  236. 'yearly',
  237. ))
  238. if self.weekly_seasonality:
  239. seasonal_features.append(self.make_seasonality_features(
  240. df['ds'],
  241. 7,
  242. 3,
  243. 'weekly',
  244. ))
  245. if self.holidays is not None:
  246. seasonal_features.append(self.make_holiday_features(df['ds']))
  247. return pd.concat(seasonal_features, axis=1)
  248. @staticmethod
  249. def linear_growth_init(df):
  250. i0, i1 = df['ds'].idxmin(), df['ds'].idxmax()
  251. T = df['t'].ix[i1] - df['t'].ix[i0]
  252. k = (df['y_scaled'].ix[i1] - df['y_scaled'].ix[i0]) / T
  253. m = df['y_scaled'].ix[i0] - k * df['t'].ix[i0]
  254. return (k, m)
  255. @staticmethod
  256. def logistic_growth_init(df):
  257. i0, i1 = df['ds'].idxmin(), df['ds'].idxmax()
  258. T = df['t'].ix[i1] - df['t'].ix[i0]
  259. # Force valid values, in case y > cap.
  260. r0 = max(1.01, df['cap_scaled'].ix[i0] / df['y_scaled'].ix[i0])
  261. r1 = max(1.01, df['cap_scaled'].ix[i1] / df['y_scaled'].ix[i1])
  262. if abs(r0 - r1) <= 0.01:
  263. r0 = 1.05 * r0
  264. L0 = np.log(r0 - 1)
  265. L1 = np.log(r1 - 1)
  266. # Initialize the offset
  267. m = L0 * T / (L0 - L1)
  268. # And the rate
  269. k = L0 / m
  270. return (k, m)
  271. # fb-block 7
  272. def fit(self, df, **kwargs):
  273. """Fit the Prophet model to data.
  274. Parameters
  275. ----------
  276. df: pd.DataFrame containing history. Must have columns 'ds', 'y', and
  277. if logistic growth, 'cap'.
  278. kwargs: Additional arguments passed to Stan's sampling or optimizing
  279. function, as appropriate.
  280. Returns
  281. -------
  282. The fitted Prophet object.
  283. """
  284. history = df[df['y'].notnull()].copy()
  285. history = self.setup_dataframe(history, initialize_scales=True)
  286. self.history = history
  287. seasonal_features = self.make_all_seasonality_features(history)
  288. self.set_changepoints()
  289. A = self.get_changepoint_matrix()
  290. dat = {
  291. 'T': history.shape[0],
  292. 'K': seasonal_features.shape[1],
  293. 'S': len(self.changepoints_t),
  294. 'y': history['y_scaled'],
  295. 't': history['t'],
  296. 'A': A,
  297. 't_change': self.changepoints_t,
  298. 'X': seasonal_features,
  299. 'sigma': self.seasonality_prior_scale,
  300. 'tau': self.changepoint_prior_scale,
  301. }
  302. if self.growth == 'linear':
  303. kinit = self.linear_growth_init(history)
  304. model = self.get_linear_model()
  305. else:
  306. dat['cap'] = history['cap_scaled']
  307. kinit = self.logistic_growth_init(history)
  308. model = self.get_logistic_model()
  309. def stan_init():
  310. return {
  311. 'k': kinit[0],
  312. 'm': kinit[1],
  313. 'delta': np.zeros(len(self.changepoints_t)),
  314. 'beta': np.zeros(seasonal_features.shape[1]),
  315. 'sigma_obs': 1,
  316. }
  317. if self.mcmc_samples > 0:
  318. stan_fit = model.sampling(
  319. dat,
  320. init=stan_init,
  321. iter=self.mcmc_samples,
  322. **kwargs
  323. )
  324. for par in stan_fit.model_pars:
  325. self.params[par] = stan_fit[par]
  326. else:
  327. params = model.optimizing(dat, init=stan_init, iter=1e4, **kwargs)
  328. for par in params:
  329. self.params[par] = params[par].reshape((1, -1))
  330. # If no changepoints were requested, replace delta with 0s
  331. if len(self.changepoints) == 0:
  332. # Fold delta into the base rate k
  333. params['k'] = params['k'] + params['delta']
  334. params['delta'] = np.zeros(params['delta'].shape)
  335. return self
  336. # fb-block 8
  337. def predict(self, df=None):
  338. """Predict historical and future values for y.
  339. Note: you must only pass in future dates here.
  340. Historical dates are prepended before predictions are made.
  341. `df` can be None, in which case we predict only on history.
  342. """
  343. if df is None:
  344. df = self.history.copy()
  345. else:
  346. df = self.setup_dataframe(df)
  347. df['trend'] = self.predict_trend(df)
  348. seasonal_components = self.predict_seasonal_components(df)
  349. intervals = self.predict_uncertainty(df)
  350. df2 = pd.concat((df, intervals, seasonal_components), axis=1)
  351. df2['yhat'] = df2['trend'] + df2['seasonal']
  352. return df2
  353. @staticmethod
  354. def piecewise_linear(t, deltas, k, m, changepoint_ts):
  355. # Intercept changes
  356. gammas = -changepoint_ts * deltas
  357. # Get cumulative slope and intercept at each t
  358. k_t = k * np.ones_like(t)
  359. m_t = m * np.ones_like(t)
  360. for s, t_s in enumerate(changepoint_ts):
  361. indx = t >= t_s
  362. k_t[indx] += deltas[s]
  363. m_t[indx] += gammas[s]
  364. return k_t * t + m_t
  365. @staticmethod
  366. def piecewise_logistic(t, cap, deltas, k, m, changepoint_ts):
  367. # Compute offset changes
  368. k_cum = np.concatenate((np.atleast_1d(k), np.cumsum(deltas) + k))
  369. gammas = np.zeros(len(changepoint_ts))
  370. for i, t_s in enumerate(changepoint_ts):
  371. gammas[i] = (
  372. (t_s - m - np.sum(gammas))
  373. * (1 - k_cum[i] / k_cum[i + 1])
  374. )
  375. # Get cumulative rate and offset at each t
  376. k_t = k * np.ones_like(t)
  377. m_t = m * np.ones_like(t)
  378. for s, t_s in enumerate(changepoint_ts):
  379. indx = t >= t_s
  380. k_t[indx] += deltas[s]
  381. m_t[indx] += gammas[s]
  382. return cap / (1 + np.exp(-k_t * (t - m_t)))
  383. def predict_trend(self, df):
  384. k = np.nanmean(self.params['k'])
  385. m = np.nanmean(self.params['m'])
  386. deltas = np.nanmean(self.params['delta'], axis=0)
  387. t = np.array(df['t'])
  388. if self.growth == 'linear':
  389. trend = self.piecewise_linear(t, deltas, k, m, self.changepoints_t)
  390. else:
  391. cap = df['cap_scaled']
  392. trend = self.piecewise_logistic(
  393. t, cap, deltas, k, m, self.changepoints_t)
  394. return trend * self.y_scale
  395. def predict_seasonal_components(self, df):
  396. seasonal_features = self.make_all_seasonality_features(df)
  397. lower_p = 100 * (1.0 - self.interval_width) / 2
  398. upper_p = 100 * (1.0 + self.interval_width) / 2
  399. components = pd.DataFrame({
  400. 'col': np.arange(seasonal_features.shape[1]),
  401. 'component': [x.split('_')[0] for x in seasonal_features.columns],
  402. })
  403. # Remove the placeholder
  404. components = components[components['component'] != 'zeros']
  405. if components.shape[0] > 0:
  406. X = seasonal_features.as_matrix()
  407. data = {}
  408. for component, features in components.groupby('component'):
  409. cols = features.col.tolist()
  410. comp_beta = self.params['beta'][:, cols]
  411. comp_features = X[:, cols]
  412. comp = (
  413. np.matmul(comp_features, comp_beta.transpose())
  414. * self.y_scale
  415. )
  416. data[component] = np.nanmean(comp, axis=1)
  417. data[component + '_lower'] = np.nanpercentile(comp, lower_p,
  418. axis=1)
  419. data[component + '_upper'] = np.nanpercentile(comp, upper_p,
  420. axis=1)
  421. component_predictions = pd.DataFrame(data)
  422. component_predictions['seasonal'] = (
  423. component_predictions[components['component'].unique()].sum(1))
  424. else:
  425. component_predictions = pd.DataFrame(
  426. {'seasonal': np.zeros(df.shape[0])})
  427. return component_predictions
  428. def predict_uncertainty(self, df):
  429. n_iterations = self.params['k'].shape[0]
  430. samp_per_iter = max(1, int(np.ceil(
  431. self.uncertainty_samples / float(n_iterations)
  432. )))
  433. # Generate seasonality features once so we can re-use them.
  434. seasonal_features = self.make_all_seasonality_features(df)
  435. sim_values = {'yhat': [], 'trend': [], 'seasonal': []}
  436. for i in range(n_iterations):
  437. for j in range(samp_per_iter):
  438. sim = self.sample_model(df, seasonal_features, i)
  439. for key in sim_values:
  440. sim_values[key].append(sim[key])
  441. lower_p = 100 * (1.0 - self.interval_width) / 2
  442. upper_p = 100 * (1.0 + self.interval_width) / 2
  443. series = {}
  444. for key, value in sim_values.items():
  445. mat = np.column_stack(value)
  446. series['{}_lower'.format(key)] = np.nanpercentile(mat, lower_p,
  447. axis=1)
  448. series['{}_upper'.format(key)] = np.nanpercentile(mat, upper_p,
  449. axis=1)
  450. return pd.DataFrame(series)
  451. def sample_model(self, df, seasonal_features, iteration):
  452. trend = self.sample_predictive_trend(df, iteration)
  453. beta = self.params['beta'][iteration]
  454. seasonal = np.matmul(seasonal_features.as_matrix(), beta) * self.y_scale
  455. sigma = self.params['sigma_obs'][iteration]
  456. noise = np.random.normal(0, sigma, df.shape[0]) * self.y_scale
  457. return pd.DataFrame({
  458. 'yhat': trend + seasonal + noise,
  459. 'trend': trend,
  460. 'seasonal': seasonal,
  461. })
  462. def sample_predictive_trend(self, df, iteration):
  463. k = self.params['k'][iteration]
  464. m = self.params['m'][iteration]
  465. deltas = self.params['delta'][iteration]
  466. t = np.array(df['t'])
  467. T = t.max()
  468. if T > 1:
  469. # Get the time discretization of the history
  470. dt = np.diff(self.history['t'])
  471. dt = np.min(dt[dt > 0])
  472. # Number of time periods in the future
  473. N = np.ceil((T - 1) / float(dt))
  474. S = len(self.changepoints_t)
  475. prob_change = min(1, (S * (T - 1)) / N)
  476. n_changes = np.random.binomial(N, prob_change)
  477. # Sample ts
  478. changepoint_ts_new = sorted(np.random.uniform(1, T, n_changes))
  479. else:
  480. # Case where we're not extrapolating.
  481. changepoint_ts_new = []
  482. n_changes = 0
  483. # Get the empirical scale of the deltas, plus epsilon to avoid NaNs.
  484. lambda_ = np.mean(np.abs(deltas)) + 1e-8
  485. # Sample deltas
  486. deltas_new = np.random.laplace(0, lambda_, n_changes)
  487. # Prepend the times and deltas from the history
  488. changepoint_ts = np.concatenate((self.changepoints_t,
  489. changepoint_ts_new))
  490. deltas = np.concatenate((deltas, deltas_new))
  491. if self.growth == 'linear':
  492. trend = self.piecewise_linear(t, deltas, k, m, changepoint_ts)
  493. else:
  494. cap = df['cap_scaled']
  495. trend = self.piecewise_logistic(t, cap, deltas, k, m,
  496. changepoint_ts)
  497. return trend * self.y_scale
  498. def make_future_dataframe(self, periods, freq='D', include_history=True):
  499. last_date = self.history['ds'].max()
  500. dates = pd.date_range(
  501. start=last_date,
  502. periods=periods + 1, # closed='right' removes a period
  503. freq=freq,
  504. closed='right') # omits the start date
  505. if include_history:
  506. dates = np.concatenate((np.array(self.history['ds']), dates))
  507. return pd.DataFrame({'ds': dates})
  508. def plot(self, fcst, uncertainty=True, xlabel='ds', ylabel='y'):
  509. """Plot the Prophet forecast.
  510. Parameters
  511. ----------
  512. fcst: pd.DataFrame output of self.predict.
  513. uncertainty: Optional boolean to plot uncertainty intervals.
  514. xlabel: Optional label name on X-axis
  515. ylabel: Optional label name on Y-axis
  516. Returns
  517. -------
  518. a matplotlib figure.
  519. """
  520. forecast_color = '#0072B2'
  521. fig = plt.figure(facecolor='w', figsize=(10, 6))
  522. ax = fig.add_subplot(111)
  523. ax.plot(self.history['ds'].values, self.history['y'], 'k.')
  524. ax.plot(fcst['ds'].values, fcst['yhat'], ls='-', c=forecast_color)
  525. if 'cap' in fcst:
  526. ax.plot(fcst['ds'].values, fcst['cap'], ls='--', c='k')
  527. if uncertainty:
  528. ax.fill_between(fcst['ds'].values, fcst['yhat_lower'],
  529. fcst['yhat_upper'], color=forecast_color, alpha=0.2)
  530. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  531. ax.set_xlabel(xlabel)
  532. ax.set_ylabel(ylabel)
  533. fig.tight_layout()
  534. return fig
  535. def plot_components(self, fcst, uncertainty=True):
  536. """Plot the Prophet forecast components.
  537. Will plot whichever are available of: trend, holidays, weekly
  538. seasonality, and yearly seasonality.
  539. Parameters
  540. ----------
  541. fcst: pd.DataFrame output of self.predict.
  542. uncertainty: Optional boolean to plot uncertainty intervals.
  543. Returns
  544. -------
  545. a matplotlib figure.
  546. """
  547. # Identify components to be plotted
  548. plot_trend = True
  549. plot_holidays = self.holidays is not None
  550. plot_weekly = 'weekly' in fcst
  551. plot_yearly = 'yearly' in fcst
  552. npanel = plot_trend + plot_holidays + plot_weekly + plot_yearly
  553. forecast_color = '#0072B2'
  554. fig = plt.figure(facecolor='w', figsize=(9, 3 * npanel))
  555. panel_num = 1
  556. ax = fig.add_subplot(npanel, 1, panel_num)
  557. ax.plot(fcst['ds'].values, fcst['trend'], ls='-', c=forecast_color)
  558. if 'cap' in fcst:
  559. ax.plot(fcst['ds'].values, fcst['cap'], ls='--', c='k')
  560. if uncertainty:
  561. ax.fill_between(
  562. fcst['ds'].values, fcst['trend_lower'], fcst['trend_upper'],
  563. color=forecast_color, alpha=0.2)
  564. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  565. ax.xaxis.set_major_locator(MaxNLocator(nbins=7))
  566. ax.set_xlabel('ds')
  567. ax.set_ylabel('trend')
  568. if plot_holidays:
  569. panel_num += 1
  570. ax = fig.add_subplot(npanel, 1, panel_num)
  571. holiday_comps = self.holidays['holiday'].unique()
  572. y_holiday = fcst[holiday_comps].sum(1)
  573. y_holiday_l = fcst[[h + '_lower' for h in holiday_comps]].sum(1)
  574. y_holiday_u = fcst[[h + '_upper' for h in holiday_comps]].sum(1)
  575. # NOTE the above CI calculation is incorrect if holidays overlap
  576. # in time. Since it is just for the visualization we will not
  577. # worry about it now.
  578. ax.plot(fcst['ds'].values, y_holiday, ls='-', c=forecast_color)
  579. if uncertainty:
  580. ax.fill_between(fcst['ds'].values, y_holiday_l, y_holiday_u,
  581. color=forecast_color, alpha=0.2)
  582. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  583. ax.xaxis.set_major_locator(MaxNLocator(nbins=7))
  584. ax.set_xlabel('ds')
  585. ax.set_ylabel('holidays')
  586. if plot_weekly:
  587. panel_num += 1
  588. ax = fig.add_subplot(npanel, 1, panel_num)
  589. df_s = fcst.copy()
  590. df_s['dow'] = df_s['ds'].dt.weekday_name
  591. df_s = df_s.groupby('dow').first()
  592. days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
  593. 'Friday', 'Saturday']
  594. y_weekly = [df_s.loc[d]['weekly'] for d in days]
  595. y_weekly_l = [df_s.loc[d]['weekly_lower'] for d in days]
  596. y_weekly_u = [df_s.loc[d]['weekly_upper'] for d in days]
  597. ax.plot(range(len(days)), y_weekly, ls='-', c=forecast_color)
  598. if uncertainty:
  599. ax.fill_between(range(len(days)), y_weekly_l, y_weekly_u,
  600. color=forecast_color, alpha=0.2)
  601. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  602. ax.set_xticks(range(len(days)))
  603. ax.set_xticklabels(days)
  604. ax.set_xlabel('Day of week')
  605. ax.set_ylabel('weekly')
  606. if plot_yearly:
  607. panel_num += 1
  608. ax = fig.add_subplot(npanel, 1, panel_num)
  609. df_s = fcst.copy()
  610. df_s['doy'] = df_s['ds'].map(lambda x: x.strftime('2000-%m-%d'))
  611. df_s = df_s.groupby('doy').first().sort_index()
  612. ax.plot(pd.to_datetime(df_s.index), df_s['yearly'], ls='-',
  613. c=forecast_color)
  614. if uncertainty:
  615. ax.fill_between(
  616. pd.to_datetime(df_s.index), df_s['yearly_lower'],
  617. df_s['yearly_upper'], color=forecast_color, alpha=0.2)
  618. ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
  619. months = MonthLocator(range(1, 13), bymonthday=1, interval=2)
  620. ax.xaxis.set_major_formatter(DateFormatter('%B %-d'))
  621. ax.xaxis.set_major_locator(months)
  622. ax.set_xlabel('Day of year')
  623. ax.set_ylabel('yearly')
  624. fig.tight_layout()
  625. return fig
  626. # fb-block 9