📚 Table of Contents
Model Initialization
Farseer()
Initialize a new Farseer forecasting model.
Farseer(
growth='linear',
changepoints=None,
n_changepoints=25,
changepoint_range=0.8,
yearly_seasonality='auto',
weekly_seasonality='auto',
daily_seasonality='auto',
holidays=None,
seasonality_mode='additive',
seasonality_prior_scale=10.0,
holidays_prior_scale=10.0,
changepoint_prior_scale=0.05,
interval_width=0.80
)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
growth |
str | 'linear' | Type of trend. Options: 'linear', 'logistic', 'flat' |
changepoints |
list or None | None | List of dates at which to include potential changepoints. If None, automatically select. |
n_changepoints |
int | 25 | Number of potential changepoints to include. Not used if changepoints is specified. |
changepoint_range |
float | 0.8 | Proportion of history in which trend changepoints will be estimated. Range: [0, 1] |
yearly_seasonality |
bool or 'auto' | 'auto' | Fit yearly seasonality. If 'auto', enabled for ≥ 2 cycles of data. |
weekly_seasonality |
bool or 'auto' | 'auto' | Fit weekly seasonality. If 'auto', enabled for ≥ 2 cycles of data. |
daily_seasonality |
bool or 'auto' | 'auto' | Fit daily seasonality. If 'auto', enabled for ≥ 2 cycles of data. |
holidays |
DataFrame or None | None | DataFrame with 'ds' (dates) and 'holiday' (names) columns. |
seasonality_mode |
str | 'additive' | Mode for seasonality. Options: 'additive', 'multiplicative' |
seasonality_prior_scale |
float | 10.0 | Prior scale for seasonality. Larger values allow more flexible seasonality. |
holidays_prior_scale |
float | 10.0 | Default prior scale for holidays. Can be overridden per holiday. |
changepoint_prior_scale |
float | 0.05 | Prior scale for changepoint flexibility. Larger values = more flexible trend. |
interval_width |
float | 0.80 | Width of uncertainty intervals. Range: (0, 1] |
Example
from farseer import Farseer
# Basic initialization
m = Farseer()
# Custom initialization
m = Farseer(
growth='logistic',
yearly_seasonality=True,
weekly_seasonality=False,
changepoint_prior_scale=0.1,
seasonality_mode='multiplicative',
interval_width=0.95
)
Fitting Methods
fit(df)
Fit the Farseer model to historical data.
fit(df)
Parameters
| Parameter | Type | Description |
|---|---|---|
df |
DataFrame | Historical data. Must have 'ds' (datetime) and 'y' (numeric) columns. Optional columns: 'cap', 'floor', 'weight', and any regressors. |
Returns: self (Farseer object) - Fitted model
Example
import polars as pl
from datetime import datetime, timedelta
from farseer import Farseer
# Create data
dates = [datetime(2020, 1, 1) + timedelta(days=i) for i in range(100)]
df = pl.DataFrame({
'ds': dates,
'y': list(range(100))
})
# Fit model
m = Farseer()
m.fit(df)
# With optional columns
df_with_extras = pl.DataFrame({
'ds': dates,
'y': values,
'cap': 200.0, # For logistic growth
'floor': 10.0, # Minimum value
'weight': weights, # Observation weights
'temperature': temps # Regressor
})
m = Farseer(growth='logistic')
m.add_regressor('temperature')
m.fit(df_with_extras)
Prediction Methods
predict(df=None)
Generate forecasts for future dates.
predict(df=None)
Parameters
| Parameter | Type | Description |
|---|---|---|
df |
DataFrame or None | DataFrame with 'ds' column containing dates to predict. If None, uses historical dates. |
Returns: DataFrame - Forecast with columns: ds, yhat, yhat_lower, yhat_upper, trend, and any seasonality/regressor components
Example
from farseer import Farseer
m = Farseer()
m.fit(train_df)
# Predict on future dates
future = m.make_future_dataframe(periods=30)
forecast = m.predict(future)
# View results
print(forecast.select(['ds', 'yhat', 'yhat_lower', 'yhat_upper']).tail())
make_future_dataframe(periods, freq='D', include_history=True)
Create a dataframe with future dates for prediction.
make_future_dataframe(periods, freq='D', include_history=True)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
periods |
int | - | Number of periods to forecast forward |
freq |
str | 'D' | Frequency: 'H' (hourly), 'D' (daily), 'W' (weekly), 'M' (monthly), 'Y' (yearly) |
include_history |
bool | True | Whether to include historical dates in the output |
Returns: DataFrame - DataFrame with 'ds' column containing dates
Example
from farseer import Farseer
m = Farseer()
m.fit(df)
# 30 days ahead (daily frequency)
future_daily = m.make_future_dataframe(periods=30, freq='D')
# 12 weeks ahead (weekly frequency)
future_weekly = m.make_future_dataframe(periods=12, freq='W')
# 6 months ahead (monthly frequency, ~30 days)
future_monthly = m.make_future_dataframe(periods=6, freq='M')
# Future only (no history)
future_only = m.make_future_dataframe(periods=30, include_history=False)
Seasonality Methods
add_seasonality(name, period, fourier_order, prior_scale=None, mode=None, condition_name=None)
Add a custom seasonality component to the model.
add_seasonality(
name,
period,
fourier_order,
prior_scale=None,
mode=None,
condition_name=None
)
Parameters
| Parameter | Type | Description |
|---|---|---|
name |
str | Name of the seasonality component |
period |
float | Period of the seasonality in days (e.g., 7 for weekly, 30.5 for monthly) |
fourier_order |
int | Number of Fourier components. Higher values = more flexible seasonality |
prior_scale |
float or None | Prior scale for this seasonality. If None, uses model's seasonality_prior_scale |
mode |
str or None | 'additive' or 'multiplicative'. If None, uses model's seasonality_mode |
condition_name |
str or None | Column name for conditional seasonality. Seasonality only applies when this column is True |
Returns: self (Farseer object)
Example
from farseer import Farseer
m = Farseer()
# Add monthly seasonality
m.add_seasonality(name='monthly', period=30.5, fourier_order=5)
# Add quarterly seasonality with custom prior
m.add_seasonality(
name='quarterly',
period=91.25,
fourier_order=8,
prior_scale=15.0,
mode='multiplicative'
)
# Add conditional seasonality (weekday pattern)
m.add_seasonality(
name='weekly_on_weekday',
period=7,
fourier_order=3,
condition_name='is_weekday'
)
# Add condition column to data
df = df.with_columns((pl.col('ds').dt.weekday() < 5).alias('is_weekday'))
m.fit(df)
Regressor Methods
add_regressor(name, prior_scale=None, standardize='auto', mode=None)
Add an additional regressor to be used for fitting and predicting.
add_regressor(
name,
prior_scale=None,
standardize='auto',
mode=None
)
Parameters
| Parameter | Type | Description |
|---|---|---|
name |
str | Name of the regressor (must match column in dataframe) |
prior_scale |
float or None | Prior scale for the regressor. Larger values = more flexible. If None, uses 10.0 |
standardize |
str | 'auto', 'true', or 'false'. Auto mode detects binary (0/1) vs continuous and standardizes accordingly |
mode |
str or None | 'additive' or 'multiplicative'. If None, uses model's seasonality_mode |
Returns: self (Farseer object)
Example
from farseer import Farseer
m = Farseer()
# Binary regressor (auto mode won't standardize)
m.add_regressor('is_weekend', standardize='auto')
# Continuous regressor (auto mode will standardize)
m.add_regressor('temperature', standardize='auto', prior_scale=10.0)
# Force standardization
m.add_regressor('sales', standardize='true', prior_scale=5.0)
# No standardization
m.add_regressor('pre_scaled_feature', standardize='false')
# Must have regressor columns in dataframe
df = pl.DataFrame({
'ds': dates,
'y': values,
'is_weekend': [0, 1, 0, ...],
'temperature': [15.2, 18.4, ...],
'sales': [100, 150, ...],
'pre_scaled_feature': [0.5, 0.7, ...]
})
m.fit(df)
Holiday Methods
add_holidays(name, dates, lower_window=0, upper_window=0, prior_scale=None)
Add holiday effects to the model with custom prior scales.
add_holidays(
name,
dates,
lower_window=0,
upper_window=0,
prior_scale=None
)
Parameters
| Parameter | Type | Description |
|---|---|---|
name |
str | Name of the holiday |
dates |
list | List of datetime objects or date strings for the holiday |
lower_window |
int | Number of days before the holiday to include in the window |
upper_window |
int | Number of days after the holiday to include in the window |
prior_scale |
float or None | Prior scale for this holiday. If None, uses model's holidays_prior_scale. Larger values allow stronger effects |
Returns: self (Farseer object)
Example
from farseer import Farseer
from datetime import datetime
m = Farseer()
# Major holiday with strong effect
m.add_holidays(
'christmas',
dates=[
datetime(2020, 12, 25),
datetime(2021, 12, 25),
datetime(2022, 12, 25)
],
prior_scale=20.0,
lower_window=-1, # Day before
upper_window=1 # Day after
)
# Minor holiday with weak effect
m.add_holidays(
'minor_event',
dates=['2020-03-17', '2021-03-17'],
prior_scale=5.0
)
# Using date strings
m.add_holidays(
'new_year',
dates=['2021-01-01', '2022-01-01', '2023-01-01'],
prior_scale=10.0
)
m.fit(df)
Serialization Methods
save(filepath)
Save the trained model to a JSON file.
save(filepath)
Parameters
| Parameter | Type | Description |
|---|---|---|
filepath |
str | Path where the model will be saved |
Example
from farseer import Farseer
m = Farseer()
m.fit(df)
# Save model
m.save('my_model.json')
Farseer.load(filepath)
Load a trained model from a JSON file.
Farseer.load(filepath)
Parameters
| Parameter | Type | Description |
|---|---|---|
filepath |
str | Path to the saved model file |
Returns: Farseer object - Loaded model
Example
from farseer import Farseer
# Load saved model
m = Farseer.load('my_model.json')
# Make predictions with loaded model
future = m.make_future_dataframe(periods=30)
forecast = m.predict(future)
# Note: Loaded models may require pandas DataFrames
# due to PyO3 serialization limitations
import pandas as pd
future_pd = future.to_pandas()
forecast = m.predict(future_pd)
to_json()
Serialize the model to a JSON string.
to_json()
Returns: str - JSON representation of the model
Example
from farseer import Farseer
m = Farseer()
m.fit(df)
# Get JSON string
json_str = m.to_json()
print(json_str[:100]) # First 100 characters
Farseer.from_json(json_str)
Deserialize a model from a JSON string.
Farseer.from_json(json_str)
Parameters
| Parameter | Type | Description |
|---|---|---|
json_str |
str | JSON string representation of the model |
Returns: Farseer object - Deserialized model
Example
from farseer import Farseer
# Serialize
m = Farseer()
m.fit(df)
json_str = m.to_json()
# Deserialize
m_loaded = Farseer.from_json(json_str)
forecast = m_loaded.predict(future)
Utility Functions
regressor_coefficients(model)
Extract regressor coefficients from a fitted model.
from farseer import regressor_coefficients regressor_coefficients(model)
Parameters
| Parameter | Type | Description |
|---|---|---|
model |
Farseer | Fitted Farseer model |
Returns: DataFrame - Regressor names, coefficients, and standardization info
Example
from farseer import Farseer, regressor_coefficients
m = Farseer()
m.add_regressor('temperature')
m.add_regressor('is_weekend')
m.fit(df)
# Get coefficients
coeffs = regressor_coefficients(m)
print(coeffs)
# Output:
# shape: (2, 4)
# ┌─────────────┬─────────────┬──────┬──────┐
# │ regressor ┆ coefficient ┆ mu ┆ std │
# ├─────────────┼─────────────┼──────┼──────┤
# │ temperature ┆ 0.523 ┆ 15.2 ┆ 5.3 │
# │ is_weekend ┆ -10.234 ┆ 0.0 ┆ 1.0 │
# └─────────────┴─────────────┴──────┴──────┘
params()
Get model parameters as a dictionary.
params()
Returns: dict - Model parameters including k, m, delta, beta, sigma_obs, etc.
Example
from farseer import Farseer
m = Farseer()
m.fit(df)
# Get parameters
params = m.params()
print(f"Trend slope (k): {params['k']}")
print(f"Trend offset (m): {params['m']}")
print(f"Observation noise (sigma_obs): {params['sigma_obs']}")
print(f"Fitted: {params['fitted']}")
print(f"Logistic floor used: {params.get('logistic_floor', False)}")