Strategy

Defined in fynance.strategy

class Strategy(model=None, signal=sign, features=None, cost=None, period=252)[source]

Bases: object

Compose features, a model, a signal mapper and costs into a backtest.

Parameters:
modelSignalModel, optional

Object with fit(X, y) / predict(X). If omitted, the (featured) input is fed straight to the signal mapper (rule-based strategy).

signalcallable, optional

Maps predictions/features to positions. Defaults to fynance.signal.sign.

featurescallable, optional

Maps the price series to a feature array used as model/​signal input. Defaults to the identity (the price series itself).

costCostModel, optional

Per-step transaction cost model.

periodint

Annualization factor passed to the summary.

run(data, y=None, X=None)[source]

Run the strategy on a price series, returning a backtest result.

Parameters:
dataPriceSeries or array-like

Price series (used for the P&L).

yarray-like, optional

Supervised target for the model (fit on the whole series; for leak-free training use run_walk_forward).

Xarray-like, optional

Precomputed feature matrix aligned with data (rows = time). When given it replaces features(prices) — use it to feed exogenous / regime / multi-venue inputs the price-only featurizer cannot build.

Returns:
BacktestResult
run_walk_forward(data, y, train, test, step=None, purge=0, X=None)[source]

Walk-forward run: refit per window on train only, predict on test.

The model and features are fit on each train slice only; out-of-sample positions are stitched together and backtested. Strictly no-lookahead. This per-window refit is the rolling-NN pattern when model is a net.

Note

The first realized return of every test block is discarded (set to 0): within a block the return at bar k is computed from prices k-1 and k, so the opening bar has no in-block prior and earns nothing. With the default step == test this drops one bar per block (roughly 1 / test of the out-of-sample sample); the dropped return is the gap return across the block join, which would require carrying the previous block’s closing position to realize causally. This conservative choice avoids any cross-block lookahead at the cost of a slightly truncated OOS sample.

Parameters:
dataPriceSeries or array-like

Price series (used for the P&L).

yarray-like

Supervised target aligned with data.

train, testint

Train and test window lengths.

stepint, optional

Roll step (defaults to test).

purgeint

Embargo removed at the train/test boundary.

Xarray-like, optional

Precomputed feature matrix aligned with data (rows = time). When given, each window slices X[train] / X[test] instead of featurizing the price slices — the way to feed exogenous / regime / multi-venue features. X must be causal and index-aligned.

Returns:
BacktestResult

Backtest of the concatenated out-of-sample positions.