Fynance logo Fynance logo fynance
User Guide DCCD PyPI GitHub
Contents Menu Expand Light mode Dark mode Auto light/dark, in light mode Auto light/dark, in dark mode Skip to content
Fynance v2.13.0 Reference Guide

Getting Started

  • Installation
  • Quickstart
  • Research workflow
  • Changelog

Reference

  • Core (fynance.core)
    • PriceSeries
    • OHLCV
    • DataSource
    • FeatureTransform
    • SignalModel
    • Allocator
    • CostModel
    • Metric
    • check_conforms
    • assert_causal
  • Data (fynance.data)
    • load
    • CSVSource
    • ParquetSource
    • align
    • resample
    • session_mask
    • session_id
    • session_bounds
    • split_sessions
    • train_test_split
    • walk_forward
    • combinatorial_purged_cv
    • BaseDataSource
    • register
    • get_source
  • Signal (fynance.signal)
    • sign
    • threshold
    • rank
    • vol_target_position
    • ema_smooth
    • deadband
    • min_hold
    • SignalPipeline
  • Portfolio (fynance.portfolio)
    • Portfolio allocation
      • ERC
      • RBP
      • HRP
      • IVP
      • MDP
      • MVP
      • MVP_uc
      • rolling_allocation
    • Risk decomposition
      • marginal_risk
      • risk_contribution
      • roll_risk_contribution
    • Constraint projection
      • project_weights
    • Conditioned covariance
      • sample_cov
      • ledoit_wolf
      • ewma_cov
      • factor_cov
      • denoise_cov
    • Rebalancing & delay
      • rebalance_calendar
      • rebalance_band
      • rebalance_turnover_cap
      • discretize
      • delay
    • Position sizing
      • kelly_fraction
      • vol_target
      • transaction_cost
  • BackTest (fynance.backtest)
    • backtest
    • BacktestResult
    • ProportionalCost
    • MarketImpactCost
    • HoldingCost
    • CompositeCost
    • capacity_curve
    • breakeven_fee
    • set_text_stats
    • BacktestNeuralNet
  • Estimator (fynance.estimator)
    • fit_volatility
    • VolatilityResult
  • Features (fynance.features)
    • Cross-section
      • cs_rank
      • cs_zscore
      • cs_demean
      • cs_winsorize
      • cs_neutralize
    • Feature engineering
      • multi_resolution
      • adaptive_roll
      • adaptive_volatility
      • granger_causality
      • IncrementalMoments
    • Filters
      • kalman_filter
      • rts_smoother
      • kalman_loglikelihood
      • fit_kalman
    • Indicators
      • bollinger_band
      • cci
      • hma
      • macd_hist
      • macd_line
      • realized_volatility
      • roc
      • rolling_autocorr
      • rolling_kurtosis
      • rolling_skewness
      • rsi
      • signal_line
    • Labels
      • triple_barrier
      • meta_labels
      • label_concurrency
      • uniqueness_weights
    • OHLCV indicators
      • atr
      • adx
      • williams_r
      • obv
      • vwap
    • Statistics
      • accuracy
      • directional_accuracy
      • percent_positive
      • tail_ratio
      • z_score
      • roll_z_score
      • mad
      • roll_mad
      • iso_vol
    • Momentums
      • ema
      • sma
      • wma
      • emstd
      • smstd
      • wmstd
    • Market regime
      • detect_regimes
      • regime_features
      • RegimeDetector
    • GARCH volatility
      • garch_volatility
    • Rolling Functions
      • roll_min
      • roll_max
      • roll_cov
      • roll_corr
      • roll_beta
      • cross_corr
    • Scale
      • normalize
      • standardize
      • roll_normalize
      • roll_rank
      • roll_standardize
      • Scale
  • Performance metrics (fynance.metrics)
    • sharpe
    • sortino
    • calmar
    • annual_return
    • annual_volatility
    • diversified_ratio
    • perf_index
    • perf_returns
    • perf_strat
    • returns_strat
    • drawdown
    • mdd
    • var
    • cvar
    • cdar
    • tail_dependence
    • roll_sharpe
    • roll_calmar
    • roll_annual_return
    • roll_annual_volatility
    • roll_drawdown
    • roll_mdd
    • roll_var
    • roll_cvar
    • beta
    • alpha
    • tracking_error
    • information_ratio
    • capture_ratio
    • benchmark_summary
    • roll_beta_benchmark
    • information_coefficient
    • quantile_returns
    • roll_information_coefficient
    • ic_decay
    • ic_summary
    • factor_rank_autocorr
    • QuantileResult
    • turnover_series
    • annual_turnover
    • gross_exposure
    • net_exposure
    • exposure_summary
    • extract_trades
    • trade_summary
    • summary
  • Financial models (fynance.models)
    • Attention
      • ScaledDotProductAttention
      • MultiHeadAttention
    • Conformal prediction intervals
      • ConformalWrapper
      • rolling_conformal
    • Econometric models
      • MA
      • ARMA
      • ARMA_GARCH
      • ARMAX_GARCH
      • get_parameters
    • Ensemble
      • StackingEnsemble
    • Loss functions
      • BaseLoss
      • SharpeLoss
      • SortinoLoss
      • DirectionalAccuracyLoss
      • CalmarLoss
      • OmegaLoss
      • HybridLoss
      • PinballLoss
    • Neural network models
      • BaseNeuralNet
      • MultiLayerPerceptron
      • ObjectiveModel
      • pretrain_pooled
      • QuantileModel
      • RegimeMoE
    • Recurrent neural networks
      • GRUCell
      • LSTMCell
      • RecurrentNeuralNetwork
      • GatedRecurrentUnit
      • LongShortTermMemory
    • Rolling models
      • CVResult
      • _RollingBasis
      • RollMultiLayerPerceptron
    • Temporal Convolutional Network
      • TemporalConvNet
    • Training utilities
      • EarlyStopping
      • exp_sample_weights
    • Transformer
      • Transformer
      • PositionalEncoding
    • Purged walk-forward tuning
      • SearchResult
      • walk_forward_search
    • Uncertainty
      • DeepEnsemble
      • MCDropout
  • Reporting (fynance.plot)
    • tearsheet
    • tearsheet_text
    • plot_equity
    • plot_drawdown
    • plot_returns_hist
    • plot_rolling_sharpe
    • plot_exposure
    • plot_quantile_returns
    • plot_ic_series
    • plot_ic_decay
    • factor_tearsheet
  • Strategy (fynance.strategy)
    • Strategy
  • Research (fynance.research)
    • Experiment
    • Ledger
    • run_experiment
    • write_report
    • compare_report
    • leaderboard
    • permutation_test
    • probabilistic_sharpe_ratio
    • deflated_sharpe_ratio
    • resample_paths
    • bootstrap_metric
    • block_permutation_test
    • ImportanceResult
    • walk_forward_mda
    • PBOResult
    • pbo
    • returns_panel
    • gbm
    • regime_switching

Also by the author

  • DCCD
  • Trading Bot
Back to top
View this page
Edit this page

walk_forward_search¶

Defined in fynance.models.tuning

walk_forward_search(factory, param_grid, X, y, *, train=252, test=63, step=None, purge=0, metric=None, n_iter=None, seed=0)[source]

Purged walk-forward hyperparameter search.

Every configuration in param_grid is scored on the same purged walk-forward folds (fynance.data.split.walk_forward), so configurations are compared honestly on out-of-sample data only – no configuration ever sees a fold’s test window during its own fit.

Parameters:
factorycallable

factory(**params) must return a fresh model exposing fit(X, y) (returns the model, or ignored) and predict(X).

param_griddict of list

Maps parameter name to the list of candidate values. With n_iter None (default) the full grid is tried, in the deterministic order of itertools.product over param_grid.values() (insertion order of param_grid’s keys). With n_iter set, a size-n_iter subsample of that same full grid is drawn without replacement, seeded by seed.

X, yarray_like

Full, time-ordered feature matrix and target, both of length n (the number of observations along axis 0).

train, testint

Train and test window lengths forwarded to walk_forward. Default 252/63 (roughly one trading year / one quarter of daily bars).

stepint, optional

Roll step forwarded to walk_forward (defaults to test, i.e. non-overlapping test windows).

purgeint

Embargo forwarded to walk_forward (observations dropped at the train/test boundary of every fold).

metriccallable, optional

metric(y_true, y_pred) -> float, higher is better. Defaults to negative mean squared error (-mean((y_true - y_pred) ** 2)), so the default search maximizes prediction accuracy; pass a Sharpe-like metric to search directly for OOS risk-adjusted return.

n_iterint, optional

If given, draw this many configurations at random (without replacement) from the full grid instead of trying every configuration; capped at the full grid size. None (default) tries the full grid.

seedint

Seed for the n_iter random subsample. Ignored when n_iter is None. The same seed always draws the same subsample.

Returns:
SearchResult

See SearchResult.

Raises:
ValueError

If param_grid is empty or any of its value lists is empty (there would be nothing to search over), or if train + test exceeds the number of observations in X (no walk-forward fold would ever be produced, which would otherwise fail silently downstream with an empty table).

Examples

A tiny closed-form ridge regression, searched over its regularization strength; the data is (near) noiseless and linear, so the unregularized fit (alpha=0.0) wins:

>>> import numpy as np
>>> from fynance.models.tuning import walk_forward_search
>>> class RidgeModel:
...     ''' Closed-form ridge regression. '''
...     def __init__(self, alpha=0.0):
...         self.alpha = alpha
...     def fit(self, X, y):
...         n_features = X.shape[1]
...         gram = X.T @ X + self.alpha * np.eye(n_features)
...         self.coef_ = np.linalg.solve(gram, X.T @ y)
...         return self
...     def predict(self, X):
...         return X @ self.coef_
>>> rng = np.random.default_rng(0)
>>> T, F = 400, 2
>>> X = rng.standard_normal((T, F))
>>> w_true = np.array([1.5, -0.5])
>>> y = X @ w_true + 0.01 * rng.standard_normal(T)
>>> result = walk_forward_search(
...     RidgeModel, {"alpha": [0.0, 1.0, 10.0]}, X, y,
...     train=200, test=50, step=50,
... )
>>> result.table.shape
(3, 4)
>>> result.n_trials
3
>>> result.best_params
{'alpha': 0.0}
>>> pred = result.best_model.predict(X[:3])
>>> pred.shape
(3,)

The trial count plugs directly into the deflated Sharpe ratio, so the winning configuration’s Sharpe can be reported honestly rather than at face value:

from fynance.research.guards import deflated_sharpe_ratio
dsr = deflated_sharpe_ratio(sr, n_obs, result.n_trials)
Next
Uncertainty
Previous
SearchResult
Copyright © 2018-2026, Arthur Bernard
Made with Sphinx and @pradyunsg's Furo