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