API Reference
Core Modules
Core base classes, tags, and validation for time series estimators.
- class timesmith.core.BaseDetector[source]
Bases:
BaseEstimatorBase class for anomaly detectors.
Detectors identify anomalies in time series.
- class timesmith.core.BaseEstimator[source]
Bases:
BaseObjectBase class for all estimators with fit capability.
Adds fitted state management to BaseObject.
- class timesmith.core.BaseFeaturizer[source]
Bases:
BaseTransformerBase class for featurizers.
Featurizers are transformers that output TableLike data.
- class timesmith.core.BaseForecaster[source]
Bases:
BaseEstimatorBase class for forecasters.
Forecasters predict future values of time series.
- class timesmith.core.BaseObject[source]
Bases:
objectBase class for all time series objects with parameter management.
Provides get_params, set_params, clone, and __repr__ methods.
- clone()[source]
Create a deep copy of this object.
- Return type:
- Returns:
A new instance with the same parameters.
- class timesmith.core.BaseTransformer[source]
Bases:
BaseEstimatorBase class for transformers.
Transformers modify data but don’t predict future values.
- class timesmith.core.BayesianChangePointDetector(expected_segment_length=100.0, threshold=0.5, preprocess=True)[source]
Bases:
BaseDetectorChange point detector using Bayesian online change-point detection.
- __init__(expected_segment_length=100.0, threshold=0.5, preprocess=True)[source]
Initialize Bayesian change point detector.
- fit(y, X=None, **fit_params)[source]
Fit the change point detector.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.core.ButterworthFilter(cutoff_freq=0.1, filter_order=4, btype='low')[source]
Bases:
BaseTransformerButterworth low-pass filter transformer.
- class timesmith.core.CUSUMDetector(baseline_window=10, threshold=3.0)[source]
Bases:
BaseDetectorChange point detector using CUSUM (Cumulative Sum) method.
CUSUM detects changes by tracking cumulative deviations from a baseline. Detects change points by looking for significant shifts in the rate values.
- fit(y, X=None, **fit_params)[source]
Fit the change point detector.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.core.DecomposeTransformer(method='moving_average', seasonal_period=None, trend_window=None)[source]
Bases:
BaseTransformerDecompose time series into trend, seasonal, and residual components.
- __init__(method='moving_average', seasonal_period=None, trend_window=None)[source]
Initialize decomposition transformer.
- fit(y, X=None, **fit_params)[source]
Fit the decomposition transformer.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.core.DegradationRateFeaturizer(periods=[1, 3, 5])[source]
Bases:
BaseFeaturizerCreate degradation rate features (rate of change) from time series.
Transforms SeriesLike to TableLike by creating percentage change features.
- class timesmith.core.DeseasonalizeTransformer(seasonal_period=None, max_period=50)[source]
Bases:
BaseTransformerRemove seasonality from time series.
- fit(y, X=None, **fit_params)[source]
Fit the deseasonalize transformer.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.core.DetrendTransformer(method='linear')[source]
Bases:
BaseTransformerRemove trend from time series.
- __init__(method='linear')[source]
Initialize detrend transformer.
- Parameters:
method (
str) – Trend removal method: ‘linear’, ‘polynomial’, or ‘moving_average’.
- fit(y, X=None, **fit_params)[source]
Fit the detrend transformer.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.core.DifferencingFeaturizer(orders=[1])[source]
Bases:
BaseFeaturizerCreate differenced features from time series.
Transforms SeriesLike to TableLike by creating differenced features.
- class timesmith.core.HampelOutlierRemover(window=10, n_sigma=3.0)[source]
Bases:
BaseTransformerRemove outliers using Hampel filter (MAD-based).
Hampel filter uses median absolute deviation (MAD) to detect outliers relative to a rolling median baseline. More robust than Z-score methods.
- class timesmith.core.IsolationForestOutlierRemover(contamination=0.1, random_state=None, window=10)[source]
Bases:
BaseTransformerRemove outliers using IsolationForest.
Uses feature set: rate, delta rate, rolling median residual.
- __init__(contamination=0.1, random_state=None, window=10)[source]
Initialize IsolationForest outlier remover.
- class timesmith.core.LagFeaturizer(lags=[1, 2, 3, 7, 14], include_diff=False, include_pct_change=False, seasonal_lags=None, prevent_leads=True)[source]
Bases:
BaseFeaturizerCreate lagged features from time series.
Transforms SeriesLike to TableLike by creating lag features. Supports automatic lead prevention, differences, percentage changes, and seasonal lags.
- __init__(lags=[1, 2, 3, 7, 14], include_diff=False, include_pct_change=False, seasonal_lags=None, prevent_leads=True)[source]
Initialize lag featurizer.
- Parameters:
include_diff (
bool) – If True, include differenced features (lag differences).include_pct_change (
bool) – If True, include percentage change features.seasonal_lags (
Optional[List[int]]) – Optional list of seasonal lag periods (e.g., [12, 24] for monthly).prevent_leads (
bool) – If True, ensures no future data leakage (only positive lags).
- class timesmith.core.MissingDateFiller(method='forward')[source]
Bases:
BaseTransformerFill missing dates in time series.
Transforms SeriesLike by adding missing dates and filling values.
- __init__(method='forward')[source]
Initialize missing date filler.
- Parameters:
method (
str) – Fill method (‘forward’, ‘backward’, ‘interpolate’).
- class timesmith.core.MissingValueFiller(method='forward')[source]
Bases:
BaseTransformerFill missing values in time series.
Transforms SeriesLike by filling missing values.
- __init__(method='forward')[source]
Initialize missing value filler.
- Parameters:
method (
str) – Fill method (‘forward’, ‘backward’, ‘interpolate’).
- class timesmith.core.OutlierRemover(factor=1.5)[source]
Bases:
BaseTransformerRemove outliers using IQR method.
Transforms SeriesLike by removing outliers.
- __init__(factor=1.5)[source]
Initialize outlier remover.
- Parameters:
factor (
float) – IQR factor for outlier detection (default: 1.5).
- class timesmith.core.PELTDetector(penalty=None, model='l2', min_size=3, jump=1, preprocess=True)[source]
Bases:
BaseDetectorChange point detector using PELT (Pruned Exact Linear Time) algorithm.
- __init__(penalty=None, model='l2', min_size=3, jump=1, preprocess=True)[source]
Initialize PELT detector.
- Parameters:
penalty (
Optional[float]) – Penalty value (higher = fewer change points). Auto-tuned if None.model (
str) – Cost function model (‘l2’ for mean shift, ‘rbf’ for distributional change).min_size (
int) – Minimum segment length.jump (
int) – Subsample (1 = no subsampling).preprocess (
bool) – Whether to preprocess data before detection.
- fit(y, X=None, **fit_params)[source]
Fit the change point detector.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.core.Resampler(freq='D', method='mean')[source]
Bases:
BaseTransformerResample time series to different frequency.
Transforms SeriesLike by resampling to target frequency.
- class timesmith.core.RollingFeaturizer(windows=[7, 14, 30], functions=['mean', 'std'], n_jobs=None)[source]
Bases:
BaseFeaturizerCreate rolling window features from time series.
Transforms SeriesLike to TableLike by creating rolling statistics.
- __init__(windows=[7, 14, 30], functions=['mean', 'std'], n_jobs=None)[source]
Initialize rolling featurizer.
- class timesmith.core.SavitzkyGolayFilter(window_length=5, polyorder=2)[source]
Bases:
BaseTransformerSavitzky-Golay filter transformer for smoothing.
- class timesmith.core.SeasonalBaselineDetector(seasonality='week', threshold_sigma=2.5)[source]
Bases:
BaseDetectorSeasonal baseline anomaly detector for time series.
Calculates seasonal baselines (e.g., weekly, monthly) and flags points that deviate significantly from expected seasonal patterns.
- fit(y, X=None, **fit_params)[source]
Fit the detector by computing seasonal baselines.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.core.SeasonalFeaturizer(seasonal_periods)[source]
Bases:
BaseFeaturizerCreate seasonal features using sine/cosine transformations.
Transforms SeriesLike to TableLike by creating seasonal sine/cosine features.
- class timesmith.core.TimeFeaturizer[source]
Bases:
BaseFeaturizerCreate time-based features from datetime index.
Transforms SeriesLike to TableLike by extracting time features.
- class timesmith.core.VotingEnsembleDetector(detectors, threshold=2)[source]
Bases:
BaseDetectorVoting ensemble for anomaly detection.
Combines multiple anomaly detectors using majority voting. Flags a point as anomalous if at least threshold detectors agree.
- __init__(detectors, threshold=2)[source]
Initialize voting ensemble detector.
- Parameters:
detectors (
List[BaseDetector]) – List of BaseDetector instances to ensemble.threshold (
int) – Minimum number of detectors that must flag an anomaly.
- fit(y, X=None, **fit_params)[source]
Fit all detectors in the ensemble.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.core.WaveletDenoiser(wavelet='db4', threshold_mode='soft', level=5)[source]
Bases:
BaseTransformerWavelet-based signal denoising transformer.
Uses wavelet thresholding to remove noise from time series signals.
- class timesmith.core.WaveletDetector(wavelet='db4', threshold_factor=3.0, level=5)[source]
Bases:
BaseDetectorWavelet-based anomaly detector for time series.
Detects anomalies by identifying large coefficients in wavelet detail levels, which indicate sudden changes or anomalies.
- fit(y, X=None, **fit_params)[source]
Fit the detector.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.core.ZScoreOutlierRemover(window=10, z_threshold=3.0, use_log=True)[source]
Bases:
BaseTransformerRemove outliers using Z-score on log residual.
Better for multiplicative errors than linear Z-score.
- timesmith.core.detect_seasonality(y, max_period=50)[source]
Detect seasonality in time series data.
- timesmith.core.preprocess_for_changepoint(y, median_window=5, detrend_window=100)[source]
Preprocess time series for change point detection.
Applies median filtering to remove spikes and baseline removal to eliminate drift.
- timesmith.core.validate_input(data, scitype, name='data', allow_none=False)[source]
Validate input data matches expected scitype.
- Parameters:
- Raises:
TypeError – If data doesn’t match expected scitype.
ValueError – If data is None and allow_none is False.
- Return type:
Forecasters
Forecaster implementations for time series forecasting.
- class timesmith.forecasters.ARIMAForecaster(start_p=0, start_q=0, max_p=5, max_q=5, seasonal=False, stepwise=True, suppress_warnings=True, error_action='ignore', **kwargs)[source]
Bases:
BaseForecasterARIMA forecaster using auto_arima for automatic order selection.
Wraps pmdarima.auto_arima to provide a BaseForecaster interface.
- __init__(start_p=0, start_q=0, max_p=5, max_q=5, seasonal=False, stepwise=True, suppress_warnings=True, error_action='ignore', **kwargs)[source]
Initialize ARIMA forecaster.
- Parameters:
start_p (
int) – Starting value for p parameter.start_q (
int) – Starting value for q parameter.max_p (
int) – Maximum value for p parameter.max_q (
int) – Maximum value for q parameter.seasonal (
bool) – Whether to include seasonal component.stepwise (
bool) – Whether to use stepwise selection.suppress_warnings (
bool) – Whether to suppress warnings.error_action (
str) – Action on error (‘ignore’, ‘warn’, ‘raise’).**kwargs – Additional arguments passed to auto_arima.
- fit(y, X=None, **fit_params)[source]
Fit ARIMA model to time series.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.forecasters.BayesianForecaster(model_type='linear_trend', n_samples=2000, n_tune=1000, random_state=None, prior_params=None)[source]
Bases:
BaseForecasterBayesian forecaster with uncertainty quantification using MCMC.
Uses Bayesian inference to estimate forecaster parameters and provides uncertainty quantification through posterior sampling. Works by fitting a probabilistic model to the time series and sampling from the posterior.
This is a general-purpose Bayesian forecaster that can be used with any time series model. For specific models (like ARIMA), consider using model-specific Bayesian implementations.
- __init__(model_type='linear_trend', n_samples=2000, n_tune=1000, random_state=None, prior_params=None)[source]
Initialize Bayesian forecaster.
- Parameters:
model_type (
str) – Type of probabilistic model: - ‘linear_trend’: Linear trend with noise - ‘exponential_trend’: Exponential trend - ‘ar1’: AR(1) modeln_samples (
int) – Number of MCMC samples.n_tune (
int) – Number of tuning samples.random_state (
Optional[int]) – Random state for reproducibility.prior_params (
Optional[Dict[str,Any]]) – Optional prior parameter distributions.
- fit(y, X=None, **fit_params)[source]
Fit Bayesian model using MCMC.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- get_posterior_summary()[source]
Get summary statistics of posterior distributions.
- Return type:
- Returns:
DataFrame with posterior summary (mean, std, credible intervals).
- class timesmith.forecasters.BlackScholesMonteCarloForecaster(n_simulations=1000, random_state=None, use_log_returns=True)[source]
Bases:
BaseForecasterBlack-Scholes Monte Carlo forecaster for asset prices.
Uses geometric Brownian motion to simulate future price paths based on historical log returns. Estimates drift and volatility from historical data and generates ensemble forecasts with uncertainty quantification.
This is specifically designed for financial time series (stock prices, commodity prices, etc.) and follows the Black-Scholes model assumptions: - Log returns are normally distributed - Market is efficient (random walk) - Geometric Brownian motion process
- Parameters:
Example
>>> import pandas as pd >>> import numpy as np >>> dates = pd.date_range('2020-01-01', periods=100, freq='D') >>> prices = pd.Series(100 + np.random.randn(100).cumsum(), index=dates) >>> forecaster = BlackScholesMonteCarloForecaster(n_simulations=1000) >>> forecaster.fit(prices) >>> forecast = forecaster.predict(fh=30) >>> print(forecast.predicted.mean()) # Mean forecast
- __init__(n_simulations=1000, random_state=None, use_log_returns=True)[source]
Initialize Black-Scholes Monte Carlo forecaster.
- fit(y, X=None, **fit_params)[source]
Fit the forecaster to historical data.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- predict(fh, X=None, **predict_params)[source]
Generate forecast using Black-Scholes Monte Carlo simulation.
- Parameters:
- Returns:
predicted: Mean forecast (pandas Series)
intervals: Prediction intervals (DataFrame with ‘lower’ and ‘upper’)
metadata: Additional information including all simulation paths
- Return type:
Forecast object with
- class timesmith.forecasters.EnsembleForecaster(n_lags=2, random_state=None, n_estimators_classifier=100, n_estimators_regressor=100, max_depth=None)[source]
Bases:
BaseForecasterEnsemble forecaster combining classification and regression models.
Uses Random Forest classifier to predict direction (up/down) and Random Forest regressor to predict magnitude, with classification predictions as features.
- __init__(n_lags=2, random_state=None, n_estimators_classifier=100, n_estimators_regressor=100, max_depth=None)[source]
Initialize ensemble forecaster.
- Parameters:
n_lags (
int) – Number of lagged features to use.random_state (
Optional[int]) – Random seed for reproducibility.n_estimators_classifier (
int) – Number of trees for classifier.n_estimators_regressor (
int) – Number of trees for regressor.max_depth (
Optional[int]) – Maximum depth of trees (None = unlimited).
- fit(y, X=None, **fit_params)[source]
Fit ensemble models on training data.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.forecasters.ExponentialMovingAverageForecaster(alpha=0.3)[source]
Bases:
BaseForecasterExponential moving average forecaster.
Uses exponential smoothing with alpha parameter.
- __init__(alpha=0.3)[source]
Initialize exponential moving average forecaster.
- Parameters:
alpha (
float) – Smoothing factor (0 < alpha <= 1).
- fit(y, X=None, **fit_params)[source]
Fit the forecaster (computes EMA).
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.forecasters.ExponentialSmoothingForecaster(trend='add', seasonal='add', seasonal_periods=None, optimized=True)[source]
Bases:
BaseForecasterExponential smoothing forecaster using Holt-Winters method.
Wraps statsmodels.tsa.holtwinters.ExponentialSmoothing.
- __init__(trend='add', seasonal='add', seasonal_periods=None, optimized=True)[source]
Initialize exponential smoothing forecaster.
- fit(y, X=None, **fit_params)[source]
Fit exponential smoothing model.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.forecasters.KalmanFilterForecaster(state_dimension=2, measurement_dimension=1, initial_state=None, state_transition=None, measurement_matrix=None, initial_covariance=1000.0, measurement_noise=5.0, process_noise=0.1, dt=1.0)[source]
Bases:
BaseForecasterKalman filter forecaster for state space models.
Uses Kalman filtering for time series forecasting with state space models.
- __init__(state_dimension=2, measurement_dimension=1, initial_state=None, state_transition=None, measurement_matrix=None, initial_covariance=1000.0, measurement_noise=5.0, process_noise=0.1, dt=1.0)[source]
Initialize Kalman filter forecaster.
- Parameters:
state_dimension (
int) – Dimension of state vector (default: 2).measurement_dimension (
int) – Dimension of measurement vector (default: 1).initial_state (
Optional[ndarray]) – Initial state vector (default: zeros).state_transition (
Optional[ndarray]) – State transition matrix F (default: constant velocity model).measurement_matrix (
Optional[ndarray]) – Measurement matrix H (default: [1, 0]).initial_covariance (
float) – Initial covariance P (default: 1000.0).measurement_noise (
float) – Measurement noise R (default: 5.0).process_noise (
float) – Process noise variance (default: 0.1).dt (
float) – Time step (default: 1.0).
- fit(y, X=None, **fit_params)[source]
Fit Kalman filter to data.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.forecasters.LSTMForecaster(input_chunk_length=12, output_chunk_length=1, n_rnn_layers=2, hidden_dim=64, n_epochs=100, random_state=None, scale=True, **darts_params)[source]
Bases:
BaseForecasterLSTM forecaster using Darts RNNModel.
Uses Long Short-Term Memory networks for time series forecasting.
- __init__(input_chunk_length=12, output_chunk_length=1, n_rnn_layers=2, hidden_dim=64, n_epochs=100, random_state=None, scale=True, **darts_params)[source]
Initialize LSTM forecaster.
- Parameters:
input_chunk_length (
int) – Number of time steps to use as input.output_chunk_length (
int) – Number of time steps to predict at once.n_rnn_layers (
int) – Number of RNN layers (default: 2).hidden_dim (
int) – Hidden dimension size (default: 64).n_epochs (
int) – Number of training epochs (default: 100).random_state (
Optional[int]) – Random seed for reproducibility.scale (
bool) – Whether to scale the data (default: True).**darts_params (
Any) – Additional Darts RNNModel parameters.
- fit(y, X=None, **fit_params)[source]
Fit LSTM model.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.forecasters.LinearTrendForecaster[source]
Bases:
BaseForecasterForecaster using linear trend extrapolation.
Fits a linear trend to historical data and extrapolates forward.
- fit(y, X=None, **fit_params)[source]
Fit linear trend to training data.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.forecasters.MonteCarloForecaster(base_forecaster, n_samples=1000, random_state=None, parameter_uncertainty=None, noise_level=None)[source]
Bases:
BaseForecasterMonte Carlo ensemble forecaster with uncertainty quantification.
Wraps a base forecaster and generates ensemble forecasts by sampling from parameter distributions or adding noise to predictions.
- __init__(base_forecaster, n_samples=1000, random_state=None, parameter_uncertainty=None, noise_level=None)[source]
Initialize Monte Carlo forecaster.
- Parameters:
base_forecaster (
BaseForecaster) – Base forecaster to use for predictions.n_samples (
int) – Number of Monte Carlo samples.random_state (
Optional[int]) – Random state for reproducibility.parameter_uncertainty (
Optional[Dict[str,tuple]]) – Optional dict mapping parameter names to (mean, std) tuples.noise_level (
Optional[float]) – Optional noise level to add to predictions (as fraction of std).
- fit(y, X=None, **fit_params)[source]
Fit the base forecaster.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.forecasters.ProphetForecaster(yearly_seasonality='auto', weekly_seasonality='auto', daily_seasonality=False, seasonality_mode='additive', growth='linear', **prophet_params)[source]
Bases:
BaseForecasterProphet forecaster using Facebook’s Prophet.
Wraps prophet.Prophet for automatic forecasting of business time series.
- __init__(yearly_seasonality='auto', weekly_seasonality='auto', daily_seasonality=False, seasonality_mode='additive', growth='linear', **prophet_params)[source]
Initialize Prophet forecaster.
- Parameters:
yearly_seasonality (
Any) – Fit yearly seasonality (‘auto’, True, False, or int).weekly_seasonality (
Any) – Fit weekly seasonality (‘auto’, True, False, or int).daily_seasonality (
bool) – Fit daily seasonality (default: False).seasonality_mode (
str) – ‘additive’ or ‘multiplicative’ (default: ‘additive’).growth (
str) – ‘linear’ or ‘logistic’ (default: ‘linear’).**prophet_params (
Any) – Additional Prophet parameters.
- fit(y, X=None, **fit_params)[source]
Fit Prophet model.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.forecasters.SimpleMovingAverageForecaster(window=7)[source]
Bases:
BaseForecasterSimple moving average forecaster.
Uses the average of the last N values as the forecast.
- __init__(window=7)[source]
Initialize simple moving average forecaster.
- Parameters:
window (
int) – Window size for moving average.
- fit(y, X=None, **fit_params)[source]
Fit the forecaster (computes moving average).
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.forecasters.SyntheticControlForecaster(treatment_start=None, pre_period_min=5)[source]
Bases:
BaseForecasterSynthetic control forecaster for counterfactual analysis.
Creates a synthetic control unit as a weighted combination of control units to estimate what would have happened in the absence of treatment.
- fit(y, X=None, **fit_params)[source]
Fit synthetic control model.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.forecasters.VARForecaster(maxlags=10, ic='aic', force_differencing=False, verbose=False)[source]
Bases:
BaseForecasterVector Autoregression (VAR) forecaster for multivariate time series.
Fits a VAR model to multiple interdependent time series and generates forecasts for all series simultaneously.
- __init__(maxlags=10, ic='aic', force_differencing=False, verbose=False)[source]
Initialize VAR forecaster.
- Parameters:
- fit(y, X=None, **fit_params)[source]
Fit VAR model.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.forecasters.WeightedMovingAverageForecaster(window=7, weights=None)[source]
Bases:
BaseForecasterWeighted moving average forecaster.
Uses weighted average of the last N values.
- fit(y, X=None, **fit_params)[source]
Fit the forecaster (computes weighted MA).
- Parameters:
- Return type:
- Returns:
Self for method chaining.
Network Analysis
Network analysis for time series.
This module provides tools for converting time series to networks and analyzing network properties.
- class timesmith.network.Graph(edges, n_nodes, directed=False, weighted=False)[source]
Bases:
objectLightweight graph representation.
Primary storage is edges + optional adjacency matrix. NetworkX conversion is lazy and optional.
- edges
List of (int, int) or (int, int, float) tuples (edge list).
- n_nodes
Number of nodes.
- directed
Whether graph is directed.
- weighted
Whether edges have weights.
- adjacency_matrix(format='sparse')[source]
Adjacency matrix (lazy, sparse by default).
- Parameters:
format (
str) – Output format: “sparse” (CSR), “dense”, or “coo”.- Returns:
Adjacency matrix. Sparse by default to avoid memory blowup.
- Raises:
ValueError – If format=”dense” and n_nodes > 50_000.
- as_networkx(force=False)[source]
Convert to NetworkX graph (optional dependency).
- Parameters:
force (
bool) – If False, refuse conversion for n > 200_000 nodes.- Returns:
NetworkX graph object.
- Raises:
ImportError – If NetworkX is not installed.
ValueError – If n_nodes > 200_000 and force=False.
- degree_sequence()[source]
Degree sequence (cached).
For undirected graphs, returns total degree. For directed graphs, returns out-degree.
- class timesmith.network.HVGFeaturizer(weighted=False, limit=None, directed=False, include_degrees=True)[source]
Bases:
BaseFeaturizerHorizontal Visibility Graph featurizer.
Converts SeriesLike to TableLike by building HVG and extracting features.
- __init__(weighted=False, limit=None, directed=False, include_degrees=True)[source]
Initialize HVG featurizer.
- class timesmith.network.MultiscaleGraphs(method='hvg', scales=None, coarse_method='mean', **method_kwargs)[source]
Bases:
objectMultiscale graph analysis for time series.
Analyzes time series at multiple temporal scales by coarse-graining and computing graph features at each scale. Creates a scale signature (feature vector across scales) useful for detection stability.
- __init__(method='hvg', scales=None, coarse_method='mean', **method_kwargs)[source]
Initialize multiscale graph analyzer.
- Parameters:
method (
str) – Network method: ‘hvg’, ‘nvg’, ‘recurrence’, ‘transition’.scales (
Optional[List[int]]) – List of coarse-graining scales. If None, uses [1, 2, 4, 8, 16].coarse_method (
str) – Coarse-graining aggregation: “mean”, “median”, “max”, “min”, “std”.**method_kwargs – Additional parameters for the network builder.
- fit(x)[source]
Fit the multiscale analyzer to a time series.
- Parameters:
x (
ndarray) – Input time series (1D array).- Return type:
- Returns:
Self for method chaining.
- class timesmith.network.NVGFeaturizer(weighted=False, limit=None, directed=False, include_degrees=True)[source]
Bases:
BaseFeaturizerNatural Visibility Graph featurizer.
Converts SeriesLike to TableLike by building NVG and extracting features.
- __init__(weighted=False, limit=None, directed=False, include_degrees=True)[source]
Initialize NVG featurizer.
- class timesmith.network.NetworkSignificanceResult(metric_name, observed_value, null_mean, null_std, z_score, p_value, n_surrogates, surrogate_method, significant, confidence_interval, alpha=0.05)[source]
Bases:
objectResults from network significance testing.
- metric_name
Name of the metric being tested.
- observed_value
Observed value of the metric.
- null_mean
Mean of the null distribution.
- null_std
Standard deviation of the null distribution.
- z_score
Z-score: (observed - mean) / std.
- p_value
Two-tailed p-value (approximate, based on normal distribution).
- n_surrogates
Number of surrogates used.
- surrogate_method
Method used to generate surrogates.
- significant
Whether the result is significant at alpha=0.05 (two-tailed).
- confidence_interval
95% confidence interval for the metric under the null.
- __init__(metric_name, observed_value, null_mean, null_std, z_score, p_value, n_surrogates, surrogate_method, significant, confidence_interval, alpha=0.05)
- class timesmith.network.RecurrenceNetworkFeaturizer(threshold=None, embedding_dimension=None, time_delay=1, metric='euclidean', rule=None, k=None, include_degrees=True)[source]
Bases:
BaseFeaturizerRecurrence Network featurizer.
Converts SeriesLike to TableLike by building recurrence network and extracting features.
- __init__(threshold=None, embedding_dimension=None, time_delay=1, metric='euclidean', rule=None, k=None, include_degrees=True)[source]
Initialize recurrence network featurizer.
- class timesmith.network.TransferEntropyDetector(lag=1, bins=10, threshold=None)[source]
Bases:
BaseDetectorDetector using transfer entropy for causal inference.
Uses transfer entropy to detect causal relationships and anomalies.
- fit(y, X=None, **fit_params)[source]
Fit the detector (computes transfer entropy if X provided).
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.network.TransitionNetworkFeaturizer(n_bins=10, order=1, symbolizer=None, include_degrees=True)[source]
Bases:
BaseFeaturizerTransition Network featurizer.
Converts SeriesLike to TableLike by building transition network and extracting features.
- __init__(n_bins=10, order=1, symbolizer=None, include_degrees=True)[source]
Initialize transition network featurizer.
- timesmith.network.build_windows(x, window, step=1, method='hvg', output='stats', **method_kwargs)[source]
Build graph statistics per window (memory efficient for large series).
For meter data with millions of points, this computes graph stats per window and returns only the time series of stats, not full graphs.
- Parameters:
x (
ndarray) – Input time series (1D array).window (
int) – Window width (number of time points per window).step (
int) – Step size between consecutive windows.method (
str) – Network method: ‘hvg’, ‘nvg’, ‘recurrence’, ‘transition’.output (
str) – Output mode: ‘stats’ (recommended), ‘degrees’, or ‘edges’.**method_kwargs – Additional parameters for the network builder.
- Return type:
- Returns:
Dictionary mapping stat names to arrays of length n_windows.
- timesmith.network.coarse_grain(x, scale, method='mean')[source]
Coarse-grain a time series by aggregating points at a given scale.
- timesmith.network.compute_clustering(G, method='average', sample_size=None)[source]
Compute clustering coefficient metrics.
- Parameters:
- Return type:
- Returns:
Dictionary with clustering metrics.
- timesmith.network.compute_modularity(G, method='louvain', weight=None, resolution=1.0, seed=None)[source]
Compute modularity and community structure.
- Parameters:
G (
Any) – NetworkX graph or timesmith.network.Graph object.method (
str) – Community detection method: “louvain”, “leiden”, “greedy”, or “label_propagation”.weight (
Optional[str]) – Edge attribute to use as weight (default: unweighted).resolution (
float) – Resolution parameter for modularity (higher = more communities).
- Return type:
- Returns:
Dictionary with modularity metrics.
- timesmith.network.compute_network_metric_significance(x, metric_fn, method='shuffle', n_surrogates=200, alpha=0.05, metric_name='metric', rng=None, **kwargs)[source]
Test significance of a network metric against null distribution.
- Parameters:
x (
ndarray) – Original time series.metric_fn (
Callable[[ndarray],float]) – Function that takes a time series and returns a metric value.method (
Literal['shuffle','phase','circular','iaaft','block_bootstrap']) – Surrogate generation method.n_surrogates (
int) – Number of surrogate series to generate.alpha (
float) – Significance level (two-tailed).metric_name (
str) – Name of the metric for reporting.**kwargs – Additional arguments for surrogate generation.
- Return type:
- Returns:
NetworkSignificanceResult with test results.
- timesmith.network.compute_path_lengths(G, method='average', sample_size=None, weight=None)[source]
Compute shortest path length metrics.
- Parameters:
G (
Any) – NetworkX graph or timesmith.network.Graph object.method (
str) – Method: “average” (average path length), “diameter” (longest shortest path), or “eccentricity” (returns per-node eccentricity).sample_size (
Optional[int]) – For large graphs, sample node pairs for path computation.weight (
Optional[str]) – Edge attribute to use as weight (default: unweighted).
- Return type:
- Returns:
Dictionary with path length metrics.
- timesmith.network.conditional_transfer_entropy(x, y, z, lag=1, bins=10)[source]
Compute conditional transfer entropy from X to Y given Z.
Conditional transfer entropy accounts for confounding variables Z, measuring the direct causal influence from X to Y.
- Parameters:
- Return type:
- Returns:
Conditional transfer entropy from X to Y given Z (non-negative, bits).
- timesmith.network.directed_3node_motifs(G)[source]
Count connected directed 3-node motifs using adjacency pattern codes.
- Parameters:
G – Directed NetworkX graph.
- Return type:
- Returns:
Dictionary mapping motif codes to counts and frequencies.
- timesmith.network.generate_surrogate(x, method='shuffle', rng=None, **kwargs)[source]
Generate a surrogate time series using the specified method.
- Parameters:
- Return type:
- Returns:
Surrogate time series.
- timesmith.network.graph_summary(G, motifs=None, motif_samples=None, seed=3363)[source]
Compute a comprehensive summary of graph properties.
- Parameters:
- Return type:
- Returns:
Dictionary of graph properties.
- timesmith.network.net_enn(D, epsilon=None, percentile=None, weighted=False, directed=False)[source]
ε-Nearest Neighbors network from distance matrix.
Each node is connected to all nodes within distance epsilon.
- Parameters:
D (
ndarray) – Distance matrix (n, n) - smaller = more similar.epsilon (
Optional[float]) – Distance threshold. If None, use percentile.percentile (
Optional[float]) – Percentile of distances to use as threshold (0-100).weighted (
bool) – If True, edge weights = distances.directed (
bool) – If True, create directed graph.
- Returns:
Tuple of (NetworkX graph, adjacency matrix).
- timesmith.network.network_metrics(G, include=None, sample_size=None, **kwargs)[source]
Compute comprehensive network metrics.
- Parameters:
G (
Any) – NetworkX graph or timesmith.network.Graph object.include (
Optional[list]) – Metrics to include: [“clustering”, “path_lengths”, “modularity”]. If None, includes all metrics.sample_size (
Optional[int]) – For large graphs, sample nodes/pairs for expensive computations.**kwargs – Additional arguments passed to metric functions.
- Return type:
- Returns:
Dictionary with all requested network metrics.
- timesmith.network.node_roles(G, n_roles=4, features='basic', n_init=10, seed=3363)[source]
Compute node roles using clustering of network features.
- Parameters:
- Return type:
- Returns:
Tuple of (node_to_role dictionary, cluster centers array).
- timesmith.network.transfer_entropy(x, y, lag=1, bins=10)[source]
Compute transfer entropy from X to Y.
Transfer entropy measures the amount of information transferred from X to Y, quantifying causal influence.
- timesmith.network.transfer_entropy_network(X, lag=1, bins=10, threshold=None, series_names=None)[source]
Construct a directed network based on transfer entropy between time series.
Each edge (i, j) represents causal influence from series i to series j, weighted by the transfer entropy value.
- Parameters:
X (
list) – List of time series arrays to analyze.lag (
int) – Time lag for transfer entropy computation.bins (
int) – Number of bins for discretization.threshold (
Optional[float]) – Minimum transfer entropy threshold for edges (if None, include all edges).series_names (
Optional[list]) – Names for each series (default: “Series_0”, “Series_1”, …).
- Returns:
Tuple of (NetworkX DiGraph, transfer entropy matrix, statistics dictionary).
Utilities
Utility functions for time series operations.
- timesmith.utils.autocorrelation(data, max_lag=None)[source]
Calculate autocorrelation function (ACF).
Computes the autocorrelation coefficients for different lags, measuring the correlation between a time series and a lagged version of itself.
- Parameters:
- Return type:
- Returns:
List of autocorrelation coefficients for each lag (lag 0 to max_lag).
- Raises:
ValueError – If data is too short or max_lag is invalid.
Example
>>> data = [1, 2, 3, 4, 5, 4, 3, 2, 1] >>> acf = autocorrelation(data, max_lag=3) >>> len(acf) 4 >>> acf[0] # Lag 0 is always 1.0 1.0
- timesmith.utils.autocorrelation_plot_data(data, max_lag=None)[source]
Calculate ACF and PACF for plotting.
Convenience function that returns both ACF and PACF along with lag indices for easy plotting.
- timesmith.utils.black_scholes_monte_carlo(historical_data, forecast_days, n_simulations=1000, random_state=None)[source]
Black-Scholes Monte Carlo simulation for asset price forecasting.
Estimates drift and volatility from historical log returns and simulates future price paths using geometric Brownian motion. This is the standard approach used in option pricing and financial forecasting.
The model assumes: - Log returns are normally distributed - Market is efficient (random walk) - Geometric Brownian motion: ΔS = S * (μΔt + σε√Δt)
- Parameters:
- Return type:
- Returns:
Array of shape (forecast_days, n_simulations) with simulated price paths. Each column represents one simulation path.
Example
>>> import pandas as pd >>> import numpy as np >>> dates = pd.date_range('2020-01-01', periods=100, freq='D') >>> prices = pd.Series(100 + np.random.randn(100).cumsum(), index=dates) >>> paths = black_scholes_monte_carlo(prices, forecast_days=30, n_simulations=1000) >>> print(paths.shape) # (30, 1000)
- timesmith.utils.bootstrap_confidence_intervals(model_fit_func, data, forecast_steps, n_bootstraps=100, confidence=0.95, random_seed=None)[source]
Generate bootstrap confidence intervals for forecasts.
- Parameters:
model_fit_func (
Callable) – Function that takes data and returns a fitted model with a forecast(steps) or predict() method.data (
SeriesLike) – Time series data.forecast_steps (
int) – Number of steps to forecast.n_bootstraps (
int) – Number of bootstrap iterations (default: 100).confidence (
float) – Confidence level (default: 0.95).random_seed (
Optional[int]) – Random seed for reproducibility.
- Return type:
- Returns:
Tuple of (mean_forecast, lower_bound, upper_bound) as numpy arrays.
- timesmith.utils.compute_anomalies(y, climatology=None, anomaly_type='absolute')[source]
Compute climatological anomalies.
- timesmith.utils.compute_climatology(y, reference_period=None)[source]
Compute climatological statistics for time series.
- timesmith.utils.correlation_distance(x, y, method='pearson', absolute=False)[source]
Compute correlation-based distance between two time series.
- Parameters:
- Return type:
- Returns:
Distance value (0-2 range, where 0 = perfect correlation).
- timesmith.utils.create_sequences(data, lookback=5, forecast_horizon=1)[source]
Create sequences for LSTM/RNN models using sliding window.
Creates input sequences (X) and target sequences (y) from time series data using a sliding window approach.
- Parameters:
- Returns:
X: Array of shape (n_samples, lookback, n_features)
y: Array of shape (n_samples, forecast_horizon)
- Return type:
Tuple of (X, y) where
Example
>>> data = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) >>> X, y = create_sequences(data, lookback=3, forecast_horizon=1) >>> # X[0] = [1, 2, 3], y[0] = [4] >>> # X[1] = [2, 3, 4], y[1] = [5]
- timesmith.utils.create_sequences_with_exog(y, X, lookback=5, forecast_horizon=1)[source]
Create sequences with exogenous variables.
Creates input sequences for both target (y) and exogenous (X) variables.
- Parameters:
- Returns:
X_seq: Exogenous sequences (n_samples, lookback, n_exog_features)
y_seq: Target sequences (n_samples, lookback, 1)
y_target: Target values (n_samples, forecast_horizon)
- Return type:
Tuple of (X_seq, y_seq, y_target) where
- timesmith.utils.cross_correlation_distance(x, y, max_lag=10)[source]
Compute distance using maximum cross-correlation.
- timesmith.utils.detect_anomalies_mad(series, threshold_std=3.0, window=3)[source]
Detect anomalous values using median absolute deviation (MAD).
Flags values that are more than threshold_std MAD from the rolling median. Uses MAD instead of std for robustness to outliers.
- Parameters:
- Return type:
- Returns:
Boolean series indicating anomalies.
Example
>>> anomalies = detect_anomalies_mad(oil_series, threshold_std=3.0) >>> print(f"Found {anomalies.sum()} anomalies")
- timesmith.utils.detect_extreme_events(y, threshold_type='percentile', threshold_value=5.0)[source]
Detect extreme events in time series.
- timesmith.utils.euclidean_distance(x, y)[source]
Compute Euclidean distance between two time series.
- timesmith.utils.fill_missing_dates(data, method='forward')[source]
Fill missing dates in time series.
- timesmith.utils.is_stationary(y, test='adf', significance_level=0.05)[source]
Simple stationarity test that returns boolean and p-value.
- Parameters:
- Return type:
- Returns:
Tuple of (is_stationary, p_value).
Example
>>> is_stationary, p_value = ts.is_stationary(series, test='adf')
- timesmith.utils.load_ts_data(file_path, date_col='date', value_col='value', index_col=None)[source]
Load time series data from CSV file.
- timesmith.utils.manhattan_distance(x, y)[source]
Compute Manhattan (L1) distance between two time series.
- timesmith.utils.monte_carlo_simulation(initial_value, mu, sigma, days, simulations=1000)[source]
Perform a Monte Carlo simulation for time series forecasting.
Uses geometric Brownian motion model.
- Parameters:
- Return type:
- Returns:
Array of shape (days, simulations) with simulated paths.
- timesmith.utils.parametric_confidence_intervals(model, forecast_steps, confidence=0.95)[source]
Generate parametric confidence intervals from model.
- Parameters:
- Return type:
- Returns:
Tuple of (mean_forecast, lower_bound, upper_bound) as numpy arrays.
- timesmith.utils.partial_autocorrelation(data, max_lag=None)[source]
Calculate partial autocorrelation function (PACF).
Computes the partial autocorrelation coefficients, which measure the correlation between observations at different lags while controlling for intermediate lags.
Uses the Durbin-Levinson algorithm for computation.
- Parameters:
- Return type:
- Returns:
List of partial autocorrelation coefficients (lag 0 to max_lag).
- Raises:
ValueError – If data is too short.
Example
>>> data = [1, 2, 3, 4, 5, 4, 3, 2, 1] >>> pacf = partial_autocorrelation(data, max_lag=3) >>> len(pacf) 4 >>> pacf[0] # Lag 0 is always 1.0 1.0
- timesmith.utils.plot_autocorrelation(acf_values, pacf_values=None, max_lag=None, title='Autocorrelation', **kwargs)[source]
Plot autocorrelation and partial autocorrelation functions.
- timesmith.utils.plot_forecast(historical, forecast, intervals=None, title='Forecast', **kwargs)[source]
Plot forecast with historical data and optional confidence intervals.
- Parameters:
- Returns:
Figure and axes objects.
- timesmith.utils.plot_monte_carlo(prices, title='Monte Carlo Simulation', save_path=None)[source]
Plot the Monte Carlo simulation results using plotsmith.
- timesmith.utils.plot_monte_carlo_paths(paths, title='Monte Carlo Simulation', show_mean=True, show_percentiles=True, **kwargs)[source]
Plot Monte Carlo simulation paths using plotsmith.
- Parameters:
- Returns:
Figure and axes objects.
- timesmith.utils.plot_multiple_series(series_dict, title=None, figsize=None, **kwargs)[source]
Plot multiple time series on the same plot.
- timesmith.utils.plot_residuals(actual, predicted, plot_type='scatter', title='Residuals', **kwargs)[source]
Plot residuals using plotsmith.
- timesmith.utils.plot_timeseries(data, title=None, xlabel=None, ylabel=None, figsize=None, **kwargs)[source]
Plot time series data using plotsmith.
- timesmith.utils.resample_ts(data, freq='D', method='mean')[source]
Resample time series to different frequency.
- timesmith.utils.split_ts(data, train_size=None, test_size=None, date_split=None)[source]
Split time series into train and test sets.
- Parameters:
train_size (
Union[float,int,None]) – If float: proportion of data for training. If int: number of observations for training. Default: 0.8 (if test_size not provided).test_size (
Union[float,int,None]) – If float: proportion of data for testing. If int: number of observations for testing. If provided, takes precedence over train_size.date_split (
Optional[str]) – Date string to split on (e.g., ‘2023-01-01’).
- Return type:
- Returns:
Tuple of (train_data, test_data).
- timesmith.utils.test_stationarity(y, significance_level=0.05)[source]
Test time series for stationarity using ADF and KPSS tests.
- timesmith.utils.train_test_split(data, test_size=0.2, train_size=None, method='time')[source]
Split time series into train and test sets (time-aware split).
This is a convenience function for time series cross-validation that ensures temporal ordering is preserved (no shuffling).
- Parameters:
data (
Union[Series,DataFrame]) – Time series data (Series or DataFrame).test_size (
Union[float,int]) – If float: proportion of data for testing (0.0 to 1.0). If int: number of observations for testing.train_size (
Union[float,int,None]) – If float: proportion of data for training. If int: number of observations for training. If provided, test_size is ignored.method (
str) – Split method. Currently only ‘time’ is supported (temporal split).
- Return type:
- Returns:
Tuple of (train_data, test_data).
Example
>>> train, test = ts.train_test_split(data, test_size=0.2, method='time')
Composition
Composition objects for chaining estimators.
- class timesmith.compose.Adapter[source]
Bases:
BaseTransformerBase class for adapters that convert between scitypes.
Examples
Series to Table via window features
Table to Series via aligned join
- class timesmith.compose.FeatureUnion(featurizers)[source]
Bases:
BaseFeaturizerRuns multiple featurizers then concatenates their table outputs.
- featurizers
List of (name, featurizer) tuples.
- fit(y, X=None, **fit_params)[source]
Fit all featurizers.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- class timesmith.compose.ForecasterPipeline(steps, forecaster)[source]
Bases:
BaseForecasterPipeline that chains transformer(s) then a forecaster.
- steps
List of (name, transformer) tuples for preprocessing.
- forecaster
Final forecaster step.
- __init__(steps, forecaster)[source]
Initialize forecaster pipeline.
- Parameters:
forecaster (
BaseForecaster) – Final forecaster step.
- fit(y, X=None, **fit_params)[source]
Fit all transformers then the forecaster.
- Parameters:
- Return type:
- Returns:
Self for method chaining.
- predict_interval(fh, X=None, coverage=0.9, **predict_params)[source]
Make forecasts with intervals through the pipeline.
- class timesmith.compose.Pipeline(steps)[source]
Bases:
BaseEstimatorPipeline that chains transformer steps.
Supports scitype change across steps via adapters.
- steps
List of (name, transformer) tuples.
- timesmith.compose.make_forecaster_pipeline(*transformers, forecaster)[source]
Create a forecaster pipeline from transformers and a forecaster.
- Parameters:
*transformers (
BaseTransformer) – Transformer objects. Names will be auto-generated.forecaster (
BaseForecaster) – Final forecaster step.
- Return type:
- Returns:
ForecasterPipeline object.
- timesmith.compose.make_pipeline(*steps)[source]
Create a pipeline from transformers.
- Parameters:
*steps (
BaseTransformer) – Transformer objects. Names will be auto-generated.- Return type:
- Returns:
Pipeline object.
Evaluation
Evaluation tools: splitters, metrics, backtests, and summaries.
- class timesmith.eval.ExpandingWindowSplit(initial_window, step_size=1, fh=1)[source]
Bases:
objectExpanding window cross-validation splitter.
Each fold uses all data up to the cutoff point for training, and tests on the next window.
- initial_window
Initial training window size.
- step_size
Step size between folds.
- fh
Forecast horizon for each fold.
- class timesmith.eval.ModelComparison[source]
Bases:
objectCompare multiple forecasting models.
Stores results from multiple models and provides comparison utilities.
- add_result(result)[source]
Add a model result to comparison.
- Parameters:
result (
ModelResult) – ModelResult to add.- Return type:
- compare_metrics(actual)[source]
Compare all models’ metrics.
- Parameters:
actual (
SeriesLike) – Actual values to compare against.- Return type:
- Returns:
DataFrame with metrics for each model, sorted by RMSE.
- class timesmith.eval.ModelResult(name, forecast, metrics=None, confidence_intervals=None, model_params=None)[source]
Bases:
objectContainer for a single model’s forecast and metrics.
- __init__(name, forecast, metrics=None, confidence_intervals=None, model_params=None)
- forecast: SeriesLike
- class timesmith.eval.SlidingWindowSplit(window_size, step_size=1, fh=1)[source]
Bases:
objectSliding window cross-validation splitter.
Each fold uses a fixed-size window for training, and tests on the next window.
- window_size
Training window size.
- step_size
Step size between folds.
- fh
Forecast horizon for each fold.
- timesmith.eval.backtest_forecaster(forecaster, task, splitter=None, metrics=None)[source]
Run backtest on a forecaster with a task.
- Parameters:
forecaster (
BaseForecaster) – Forecaster or forecaster pipeline to test.task (
ForecastTask) – ForecastTask with y, fh, and optional X.splitter (
Optional[Any]) – Optional splitter (defaults to ExpandingWindowSplit).metrics (
Optional[list]) – Optional list of metric functions (defaults to [mae, rmse, mape]).
- Return type:
BacktestResult- Returns:
BacktestResult with results table and summary.
- timesmith.eval.bias(y_true, y_pred)[source]
Calculate bias (mean error).
Bias measures the average difference between predicted and actual values. Positive bias indicates over-estimation, negative indicates under-estimation.
- timesmith.eval.compare_models(actual, forecasts)[source]
Quick comparison function for multiple forecasts.
- timesmith.eval.mape(y_true, y_pred)[source]
Mean Absolute Percentage Error with safe zero handling.
- timesmith.eval.smape(y_true, y_pred)[source]
Symmetric Mean Absolute Percentage Error.
SMAPE is symmetric and handles zero values better than MAPE.
- timesmith.eval.summarize_backtest(result)[source]
Summarize backtest results with aggregate and per-fold metrics.
- Parameters:
result (
BacktestResult) – BacktestResult from backtest_forecaster.- Return type:
- Returns:
Dictionary with aggregate metrics and per-fold metrics DataFrame.