or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-forecasting.mddiagnostics.mdholidays.mdindex.mdplotting.mdserialization.mdutilities.md

core-forecasting.mddocs/

0

# Core Forecasting

1

2

The Prophet class provides the main forecasting functionality with comprehensive time series modeling capabilities. It supports multiple growth patterns, automatic seasonality detection, custom seasonalities, external regressors, and holiday effects.

3

4

## Capabilities

5

6

### Prophet Class

7

8

The main forecasting class that implements Facebook's Prophet algorithm for time series forecasting.

9

10

```python { .api }

11

class Prophet:

12

def __init__(

13

self,

14

growth='linear',

15

changepoints=None,

16

n_changepoints=25,

17

changepoint_range=0.8,

18

yearly_seasonality='auto',

19

weekly_seasonality='auto',

20

daily_seasonality='auto',

21

holidays=None,

22

seasonality_mode='additive',

23

seasonality_prior_scale=10.0,

24

holidays_prior_scale=10.0,

25

changepoint_prior_scale=0.05,

26

mcmc_samples=0,

27

interval_width=0.8,

28

uncertainty_samples=1000,

29

stan_backend=None,

30

scaling='absmax',

31

holidays_mode=None

32

):

33

"""

34

Prophet forecaster.

35

36

Parameters:

37

- growth: str, growth trend type ('linear', 'logistic', 'flat')

38

- changepoints: list, dates for potential changepoints

39

- n_changepoints: int, number of potential changepoints (default: 25)

40

- changepoint_range: float, proportion of history for changepoints (default: 0.8)

41

- yearly_seasonality: bool/str/int, yearly seasonality setting ('auto', True, False, or Fourier terms)

42

- weekly_seasonality: bool/str/int, weekly seasonality setting

43

- daily_seasonality: bool/str/int, daily seasonality setting

44

- holidays: DataFrame, holiday dates and effects

45

- seasonality_mode: str, seasonality mode ('additive' or 'multiplicative')

46

- seasonality_prior_scale: float, prior scale for seasonality (default: 10.0)

47

- holidays_prior_scale: float, prior scale for holidays (default: 10.0)

48

- changepoint_prior_scale: float, prior scale for changepoints (default: 0.05)

49

- mcmc_samples: int, number of MCMC samples (default: 0 for MAP estimation)

50

- interval_width: float, width of uncertainty intervals (default: 0.8)

51

- uncertainty_samples: int, number of samples for uncertainty estimation (default: 1000)

52

- stan_backend: str, Stan backend to use

53

- scaling: str, scaling method ('absmax' or 'minmax')

54

- holidays_mode: str, holiday mode (defaults to seasonality_mode)

55

"""

56

```

57

58

### Model Fitting

59

60

Fit the Prophet model to historical time series data.

61

62

```python { .api }

63

def fit(self, df, **kwargs):

64

"""

65

Fit the Prophet model.

66

67

Parameters:

68

- df: DataFrame with columns 'ds' (date) and 'y' (values)

69

- **kwargs: additional arguments passed to Stan

70

71

Returns:

72

- self: fitted Prophet object

73

"""

74

```

75

76

### Prediction

77

78

Generate forecasts for future time periods.

79

80

```python { .api }

81

def predict(self, df=None, vectorized=True):

82

"""

83

Predict using the Prophet model.

84

85

Parameters:

86

- df: DataFrame with column 'ds' (dates), 'cap' for logistic growth,

87

and any additional regressors. If None, uses dates from training.

88

- vectorized: bool, whether to use vectorized prediction (default: True)

89

90

Returns:

91

- DataFrame with forecast components: yhat, yhat_lower, yhat_upper, trend, etc.

92

"""

93

```

94

95

### Future Dataframe Creation

96

97

Create a dataframe with future dates for forecasting.

98

99

```python { .api }

100

def make_future_dataframe(self, periods, freq='D', include_history=True):

101

"""

102

Create a dataframe with future dates for forecasting.

103

104

Parameters:

105

- periods: int, number of future periods to forecast

106

- freq: str, frequency of dates ('D' for daily, 'W' for weekly, etc.)

107

- include_history: bool, whether to include historical dates (default: True)

108

109

Returns:

110

- DataFrame with 'ds' column containing historical and future dates

111

"""

112

```

113

114

### Built-in Plotting Methods

115

116

Prophet instance methods for quick plotting and visualization.

117

118

```python { .api }

119

def plot(self, fcst, ax=None, uncertainty=True, plot_cap=True,

120

xlabel='ds', ylabel='y', figsize=(10, 6), include_legend=False):

121

"""

122

Plot the Prophet forecast (instance method).

123

124

Parameters:

125

- fcst: DataFrame, forecast output from self.predict()

126

- ax: matplotlib axes, axes to plot on (optional)

127

- uncertainty: bool, whether to plot uncertainty intervals (default: True)

128

- plot_cap: bool, whether to plot carrying capacity (default: True)

129

- xlabel: str, label for X-axis (default: 'ds')

130

- ylabel: str, label for Y-axis (default: 'y')

131

- figsize: tuple, figure size in inches (default: (10, 6))

132

- include_legend: bool, whether to add legend (default: False)

133

134

Returns:

135

- matplotlib Figure object

136

"""

137

138

def plot_components(self, fcst, uncertainty=True, plot_cap=True,

139

weekly_start=0, yearly_start=0, figsize=None):

140

"""

141

Plot the Prophet forecast components (instance method).

142

143

Parameters:

144

- fcst: DataFrame, forecast output from self.predict()

145

- uncertainty: bool, whether to plot uncertainty intervals (default: True)

146

- plot_cap: bool, whether to plot carrying capacity (default: True)

147

- weekly_start: int, start day of weekly plot (0=Sunday, default: 0)

148

- yearly_start: int, start day of yearly plot (0=Jan 1, default: 0)

149

- figsize: tuple, figure size in inches (optional)

150

151

Returns:

152

- matplotlib Figure object with component subplots

153

"""

154

```

155

156

### Seasonality Management

157

158

Add custom seasonality patterns to the model.

159

160

```python { .api }

161

def add_seasonality(

162

self,

163

name,

164

period,

165

fourier_order,

166

prior_scale=None,

167

mode=None,

168

condition_name=None

169

):

170

"""

171

Add a custom seasonality component.

172

173

Parameters:

174

- name: str, name of the seasonality component

175

- period: float, period of the seasonality in the same units as the data

176

- fourier_order: int, number of Fourier terms to generate

177

- prior_scale: float, prior scale for this seasonality (default: uses global seasonality_prior_scale)

178

- mode: str, seasonality mode ('additive' or 'multiplicative', default: uses global seasonality_mode)

179

- condition_name: str, column name for conditional seasonality

180

181

Returns:

182

- self: Prophet object with added seasonality

183

"""

184

```

185

186

### Regressor Management

187

188

Add external regressor variables to the model.

189

190

```python { .api }

191

def add_regressor(

192

self,

193

name,

194

prior_scale=None,

195

standardize='auto',

196

mode=None

197

):

198

"""

199

Add an external regressor variable.

200

201

Parameters:

202

- name: str, name of the regressor column

203

- prior_scale: float, prior scale for the regressor coefficient

204

- standardize: str/bool, whether to standardize the regressor ('auto', True, False)

205

- mode: str, regressor mode ('additive' or 'multiplicative')

206

207

Returns:

208

- self: Prophet object with added regressor

209

"""

210

```

211

212

### Holiday Integration

213

214

Add built-in country holidays to the model.

215

216

```python { .api }

217

def add_country_holidays(self, country_name):

218

"""

219

Add built-in holidays for a specific country.

220

221

Parameters:

222

- country_name: str, country name (e.g., 'US', 'UK', 'Germany')

223

224

Returns:

225

- self: Prophet object with added country holidays

226

"""

227

```

228

229

### Prediction Sampling

230

231

Generate samples from the posterior predictive distribution.

232

233

```python { .api }

234

def predictive_samples(self, df, vectorized=True):

235

"""

236

Generate samples from the posterior predictive distribution.

237

238

Parameters:

239

- df: DataFrame with column 'ds' and any regressors

240

- vectorized: bool, whether to use vectorized sampling (default: True)

241

242

Returns:

243

- DataFrame with samples from posterior predictive distribution

244

"""

245

```

246

247

## Static Methods

248

249

### Seasonality Features

250

251

Generate Fourier series components for seasonality modeling.

252

253

```python { .api }

254

@staticmethod

255

def fourier_series(dates, period, series_order):

256

"""

257

Generate Fourier series components.

258

259

Parameters:

260

- dates: Series of dates

261

- period: float, period of the seasonality

262

- series_order: int, number of Fourier terms

263

264

Returns:

265

- DataFrame with Fourier series components

266

"""

267

268

@staticmethod

269

def make_seasonality_features(dates, period, series_order, prefix):

270

"""

271

Create seasonality features DataFrame.

272

273

Parameters:

274

- dates: Series of dates

275

- period: float, period of the seasonality

276

- series_order: int, number of Fourier terms

277

- prefix: str, prefix for column names

278

279

Returns:

280

- DataFrame with seasonality features

281

"""

282

```

283

284

### Trend Functions

285

286

Evaluate trend functions for different growth patterns.

287

288

```python { .api }

289

@staticmethod

290

def piecewise_linear(t, deltas, k, m, changepoint_ts):

291

"""

292

Evaluate piecewise linear trend function.

293

294

Parameters:

295

- t: array, time values

296

- deltas: array, rate changes at changepoints

297

- k: float, base growth rate

298

- m: float, offset

299

- changepoint_ts: array, changepoint times

300

301

Returns:

302

- array, trend values

303

"""

304

305

@staticmethod

306

def piecewise_logistic(t, cap, deltas, k, m, changepoint_ts):

307

"""

308

Evaluate piecewise logistic trend function.

309

310

Parameters:

311

- t: array, time values

312

- cap: array, carrying capacity values

313

- deltas: array, rate changes at changepoints

314

- k: float, base growth rate

315

- m: float, offset

316

- changepoint_ts: array, changepoint times

317

318

Returns:

319

- array, trend values

320

"""

321

322

@staticmethod

323

def flat_trend(t, m):

324

"""

325

Evaluate flat trend function.

326

327

Parameters:

328

- t: array, time values

329

- m: float, offset value

330

331

Returns:

332

- array, constant trend values

333

"""

334

```

335

336

### Growth Initialization

337

338

Initialize parameters for different growth patterns.

339

340

```python { .api }

341

@staticmethod

342

def linear_growth_init(df):

343

"""

344

Initialize linear growth parameters.

345

346

Parameters:

347

- df: DataFrame with 'ds' and 'y' columns

348

349

Returns:

350

- tuple, (growth rate, offset)

351

"""

352

353

@staticmethod

354

def logistic_growth_init(df):

355

"""

356

Initialize logistic growth parameters.

357

358

Parameters:

359

- df: DataFrame with 'ds', 'y', and 'cap' columns

360

361

Returns:

362

- tuple, (growth rate, offset)

363

"""

364

365

@staticmethod

366

def flat_growth_init(df):

367

"""

368

Initialize flat growth parameters.

369

370

Parameters:

371

- df: DataFrame with 'ds' and 'y' columns

372

373

Returns:

374

- tuple, (growth rate, offset)

375

"""

376

```

377

378

## Usage Examples

379

380

### Basic Time Series Forecasting

381

382

```python

383

import pandas as pd

384

import numpy as np

385

from prophet import Prophet

386

387

# Create sample data

388

df = pd.DataFrame({

389

'ds': pd.date_range('2020-01-01', periods=365, freq='D'),

390

'y': np.random.randn(365).cumsum() + 100

391

})

392

393

# Initialize and fit model

394

model = Prophet()

395

model.fit(df)

396

397

# Create future dates and predict

398

future = model.make_future_dataframe(periods=30)

399

forecast = model.predict(future)

400

401

print(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail())

402

```

403

404

### Logistic Growth with Capacity

405

406

```python

407

import numpy as np

408

409

# Data with capacity constraint

410

df = pd.DataFrame({

411

'ds': pd.date_range('2020-01-01', periods=365, freq='D'),

412

'y': np.random.randn(365).cumsum() + 100,

413

'cap': [200] * 365 # Carrying capacity

414

})

415

416

# Model with logistic growth

417

model = Prophet(growth='logistic')

418

model.fit(df)

419

420

# Future dataframe must include capacity

421

future = model.make_future_dataframe(periods=30)

422

future['cap'] = 200

423

424

forecast = model.predict(future)

425

```

426

427

### Custom Seasonality and Regressors

428

429

```python

430

import numpy as np

431

432

# Add custom seasonality and external regressor

433

model = Prophet()

434

model.add_seasonality(name='monthly', period=30.5, fourier_order=5)

435

model.add_regressor('temperature')

436

437

# Training data with regressor

438

df = pd.DataFrame({

439

'ds': pd.date_range('2020-01-01', periods=365, freq='D'),

440

'y': np.random.randn(365).cumsum() + 100,

441

'temperature': np.random.normal(20, 5, 365)

442

})

443

444

model.fit(df)

445

446

# Future data must include regressor

447

future = model.make_future_dataframe(periods=30)

448

future['temperature'] = np.random.normal(20, 5, len(future))

449

450

forecast = model.predict(future)

451

```