Skip to content
TotalFinance

Backtesting · @insiderfinance/totalfinance

@insiderfinance/totalfinance/backtest

import { … } from '@insiderfinance/totalfinance/backtest'
stable-by-law (pre-1.0; not a 1.0 stability guarantee)iface 82const 6type 15class 1fn 28JSON ↗
class

SimulatedBroker

#

A deterministic simulated broker.

Signature
import { SimulatedBroker } from '@insiderfinance/totalfinance/backtest';

export declare class SimulatedBroker {
  constructor(config: BrokerConfig);
  cancel(id: string): void;
  cash: number;
  equity(marks: Map<SymbolId, number>): number;
  exerciseOption(input: ExerciseOptionInput): OptionSettlement;
  orders: readonly Order[];
  policies(): { cost: string; slippage: string; margin: string; assignment: string; oco: string; };
  position(symbol: SymbolId): Position;
  readonly positions: Map<string, Position>;
  processBar(bar: Bar, action?: CorporateAction): Trade[];
  registerOption(symbol: SymbolId, specification: OptionContractSpecification): void;
  settleExpiries(asOfTimestampMs: EpochMs, underlierMarks?: Map<SymbolId, number>): OptionSettlement[];
  settlements: readonly OptionSettlement[];
  submit(request: OrderRequest): string;
  trades: readonly Trade[];
  warnings: readonly QuantWarning[];
}
Fields, parameters and returned members (109)

Loading 109 members…

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

iface

SlippageModel

#

Public declaration. Read the signature and member contracts below; no additional behaviour is inferred.

Signature
import type { SlippageModel } from '@insiderfinance/totalfinance/backtest';

export interface SlippageModel {
    readonly label: string;
    fill(input: SlippageFillInput): number;
}
Fields, parameters and returned members (6)
Name · typeMeaning · unitRequired · default
fill(input: SlippageFillInput) => number—unitless by nameRequiredNo @default declared
fill(input)SlippageFillInput—unitless by nameRequiredNo @default declared
fill(input).quantitynumber—unitless by nameRequiredNo @default declared
fill(input).referencePricenumber—currency amount (the field or record currency)RequiredNo @default declared
fill(input).sideOrderSide—unitless by nameRequiredNo @default declared
labelstring—unitless by nameRequiredNo @default declared

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

iface

StrategyContext

#

The strategy's view of the world on the current bar.

Signature
import type { StrategyContext } from '@insiderfinance/totalfinance/backtest';

/** The strategy's view of the world on the current bar. */
export interface StrategyContext {
    /** The bar currently being handled. */
    readonly bar: Bar;
    /**
     * Register a handler that runs on every bar of `symbol`. Throws if `symbol` already has a handler —
     * one handler per symbol, so behaviour never silently depends on registration order (WS2.8).
     */
    onBar(symbol: SymbolId, handler: () => void): void;
    /**
     * Register a portfolio-level handler that fires ONCE per timestamp, after every symbol's bar handler
     * for that timestamp has run — the right hook for cross-sectional logic (ranking, rebalancing) that
     * must not depend on the input bar order (WS2.8).
     */
    onBars(handler: () => void): void;
    /** Bind a streaming indicator to a symbol; returns a handle refreshed before each handler call. */
    indicator<In, Out>(symbol: SymbolId, stream: Indicator<In, Out>, field: BarField | ((bar: Bar) => In)): IndicatorHandle<Out>;
    /** Buy (target long via `percent`, or add via `quantity`/`value`). Returns the order id. */
    buy(symbol: SymbolId, options?: TradeOptions): string;
    /** Sell / short. Returns the order id. */
    sell(symbol: SymbolId, options?: TradeOptions): string;
    /** Flatten the position in `symbol` with a market order. */
    close(symbol: SymbolId): void;
    /** Cancel a working order. */
    cancel(id: string): void;
    /** Current position in `symbol`. */
    position(symbol: SymbolId): Position;
    /** Register an option symbol (underlying/type/strike/expiry) so it's marked and settled at expiry. */
    registerOption(symbol: SymbolId, specification: OptionContractSpecification): void;
    /**
     * Manually exercise `quantity` contracts of a LONG American option early (WS7.4). Requires the
     * broker's `assignment: 'model'` policy; settles at the current underlier mark.
     */
    exercise(symbol: SymbolId, quantity: number): void;
    /** Current cash. */
    readonly cash: number;
    /** Current portfolio equity (cash + marked positions). */
    readonly equity: number;
}
Fields, parameters and returned members (70)

Loading 70 members…

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

iface

SymbolAttribution

#

Realized P&L (and costs) attributed to one symbol.

Signature
import type { SymbolAttribution } from '@insiderfinance/totalfinance/backtest';

/** Realized P&L (and costs) attributed to one symbol. */
export interface SymbolAttribution {
    symbol: SymbolId;
    /** Realized trading P&L (average-cost matched; excludes open positions, dividends, borrow). */
    realizedPnl: number;
    commission: number;
    slippage: number;
    tradedNotional: number;
}
Fields, parameters and returned members (5)
Name · typeMeaning · unitRequired · default
commissionnumber—unitless by nameRequiredNo @default declared
realizedPnlnumber

Realized trading P&L (average-cost matched; excludes open positions, dividends, borrow).

currency amount (the field or record currency)
RequiredNo @default declared
slippagenumber—unitless by nameRequiredNo @default declared
symbolstring—unitless by nameRequiredNo @default declared
tradedNotionalnumber—currency amount (the field or record currency)RequiredNo @default declared

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

iface

TearSheet

#

Public declaration. Read the signature and member contracts below; no additional behaviour is inferred.

Signature
import type { TearSheet } from '@insiderfinance/totalfinance/backtest';

export interface TearSheet {
    performance: PerformanceSummary;
    trades: TradeStatistics;
    returns: ReturnStatistics;
    attribution: SymbolAttribution[];
    monteCarlo?: MonteCarloResampleResult;
    /** The source backtest's echoed modelling assumptions — a tear sheet never drops them (WS2.8). */
    assumptions: BacktestAssumptions;
    /** The source backtest's implementation-risk diagnostics — a tear sheet never drops them (WS2.8). */
    diagnostics: ImplementationRisk;
}
Fields, parameters and returned members (80)

Loading 80 members…

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

iface

TearSheetOptions

#

Public declaration. Read the signature and member contracts below; no additional behaviour is inferred.

Signature
import type { TearSheetOptions } from '@insiderfinance/totalfinance/backtest';

export interface TearSheetOptions {
    /** Add a seeded Monte-Carlo bootstrap of the bar returns for total-return confidence bands. */
    monteCarlo?: {
        iterations?: number;
        seed?: number;
    };
}
Fields, parameters and returned members (3)
Name · typeMeaning · unitRequired · default
monteCarlo{ iterations?: number; seed?: number; }

Add a seeded Monte-Carlo bootstrap of the bar returns for total-return confidence bands.

unitless by name
OptionalNo @default declared
monteCarlo.iterationsnumber—unitless by nameOptionalNo @default declared
monteCarlo.seednumber—unitless by nameOptionalNo @default declared

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

type

TimeInForce

#

Public declaration. Read the signature and member contracts below; no additional behaviour is inferred.

Signature
import type { TimeInForce } from '@insiderfinance/totalfinance/backtest';

export type TimeInForce = 'day' | 'gtc';

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

iface

Trade

#

A filled trade. quantity is always positive; side carries the direction (core OrderSide, B6).

Signature
import type { Trade } from '@insiderfinance/totalfinance/backtest';

/** A filled trade. `quantity` is always positive; `side` carries the direction (core `OrderSide`, B6). */
export interface Trade {
    symbol: SymbolId;
    timestampMs: EpochMs;
    side: OrderSide;
    /** Filled quantity (> 0). */
    quantity: number;
    /** Fill price *after* slippage. */
    price: number;
    /** Commission charged on this fill. */
    commission: number;
    /** Slippage cost (signed against the trader) embedded in `price` vs the reference. */
    slippage: number;
    /**
     * Contract multiplier of the instrument traded — `1` for a share, the registered option's
     * multiplier (default 100) for an option symbol. Cash value of the fill is
     * `quantity · price · multiplier`; turnover and realized-P&L attribution apply it or a
     * 100×-multiplier option trade is reported at 1% of its true size. Every engine stamps it —
     * the share-only loops (vectorized, cross-sectional) stamp `1` by construction — so no reader
     * has to guess what an absent field meant.
     */
    multiplier: number;
}
Fields, parameters and returned members (8)
Name · typeMeaning · unitRequired · default
commissionnumber

Commission charged on this fill.

unitless by name
RequiredNo @default declared
multipliernumber

Contract multiplier of the instrument traded — 1 for a share, the registered option's multiplier (default 100) for an option symbol. Cash value of the fill is quantity · price · multiplier; turnover and realized-P&L attribution apply it or a 100×-multiplier option trade is reported at 1% of its true size. Every engine stamps it — the share-only loops (vectorized, cross-sectional) stamp 1 by construction — so no reader has to guess what an absent field meant.

unitless by name
RequiredNo @default declared
pricenumber

Fill price *after* slippage.

unitless by name
RequiredNo @default declared
quantitynumber

Filled quantity (> 0).

unitless by name
RequiredNo @default declared
sideOrderSide—unitless by nameRequiredNo @default declared
slippagenumber

Slippage cost (signed against the trader) embedded in price vs the reference.

unitless by name
RequiredNo @default declared
symbolstring—unitless by nameRequiredNo @default declared
timestampMsnumber—millisecondsRequiredNo @default declared

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

iface

TradeOptions

#

Sizing + order parameters for context.buy / context.sell.

Signature
import type { TradeOptions } from '@insiderfinance/totalfinance/backtest';

/** Sizing + order parameters for `context.buy` / `context.sell`. */
export interface TradeOptions {
    /** Incremental share quantity. */
    quantity?: number;
    /** Target allocation as a fraction of equity (a *target*, e.g. `1` = 100% long for `buy`). */
    percent?: number;
    /** Incremental notional value (shares = value / price). */
    value?: number;
    type?: OrderType;
    limitPrice?: number;
    stopPrice?: number;
    timeInForce?: TimeInForce;
    takeProfit?: number;
    stopLoss?: number;
}
Fields, parameters and returned members (9)
Name · typeMeaning · unitRequired · default
limitPricenumber—currency amount (the field or record currency)OptionalNo @default declared
percentnumber

Target allocation as a fraction of equity (a *target*, e.g. 1 = 100% long for buy).

unitless by name
OptionalNo @default declared
quantitynumber

Incremental share quantity.

unitless by name
OptionalNo @default declared
stopLossnumber—unitless by nameOptionalNo @default declared
stopPricenumber—currency amount (the field or record currency)OptionalNo @default declared
takeProfitnumber—unitless by nameOptionalNo @default declared
timeInForceTimeInForce—unitless by nameOptionalNo @default declared
typeOrderType—unitless by nameOptionalNo @default declared
valuenumber

Incremental notional value (shares = value / price).

unitless by name
OptionalNo @default declared

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

iface

TradeStatistics

#

Public declaration. Read the signature and member contracts below; no additional behaviour is inferred.

Signature
import type { TradeStatistics } from '@insiderfinance/totalfinance/backtest';

export interface TradeStatistics {
    count: number;
    totalCommission: number;
    totalSlippage: number;
    turnover: number;
}
Fields, parameters and returned members (4)
Name · typeMeaning · unitRequired · default
countnumber—unitless by nameRequiredNo @default declared
totalCommissionnumber—unitless by nameRequiredNo @default declared
totalSlippagenumber—unitless by nameRequiredNo @default declared
turnovernumber—unitless by nameRequiredNo @default declared

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

iface

TradingEnvironment

#

The familiar reset / step contract over the frozen simulator.

Signature
import type { TradingEnvironment } from '@insiderfinance/totalfinance/backtest';

/** The familiar `reset` / `step` contract over the frozen simulator. */
export interface TradingEnvironment {
    /** The definition's identity, seed excluded. */
    readonly definitionHash: string;
    /** The decision instants an episode steps through. */
    readonly instantCount: number;
    reset(options?: EnvironmentResetOptions): EnvironmentResetResult;
    step(action: EnvironmentAction): EnvironmentStepResult;
    /** The engine's own result over the episode so far — the same shape `portfolioBacktest` returns; ends the episode. */
    finish(): PortfolioBacktestResult;
}
Fields, parameters and returned members (103)

Loading 103 members…

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

iface

TradingEnvironmentDefinition

#

What an environment simulates: the stepper's request plus the episode bound, the limits, the reward, the features.

Signature
import type { TradingEnvironmentDefinition } from '@insiderfinance/totalfinance/backtest';

/** What an environment simulates: the stepper's request plus the episode bound, the limits, the reward, the features. */
export interface TradingEnvironmentDefinition extends PortfolioStepperRequest {
    /** The most steps an episode takes before `truncated` (default: the instant count; ceiling 100,000). */
    maximumSteps?: number;
    limits?: EnvironmentLimits;
    reward?: RewardComposition;
    features?: FeatureRecipes;
}
Fields, parameters and returned members (147)

Loading 147 members…

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

iface

VectorizedOptions

#

Public declaration. Read the signature and member contracts below; no additional behaviour is inferred.

Signature
import type { VectorizedOptions } from '@insiderfinance/totalfinance/backtest';

export interface VectorizedOptions {
    /** Price bars in ascending time order. */
    data: Bar[];
    /**
     * Target exposure per bar, aligned to `data`. A boolean is long (`1`) / flat (`0`); a number is a
     * target weight (fraction of equity; negative = short), clamped to `maxLeverage`.
     *
     * Accepts a warmup-aware {@link SeriesSignal} (`{ value, warmup }`, e.g. a `technicalAnalysis.*.explain(...)`
     * result) so an indicator's leading warmup NaNs are treated as flat (position 0) instead of
     * throwing. A bare `number[]`/`Float64Array` has an implicit `warmup` of 0, so any NaN in it still
     * throws (a genuine mid-series NaN is a real error, not warmup).
     */
    signal: ArrayLike<number | boolean> | SeriesSignal | EnvelopeSignal;
    /** Rebalance calendar (default `everyBar`). */
    rebalance?: RebalanceRule;
    /** Commission model (default `fees.none()`). */
    fees?: CostModel;
    /** Slippage model (default `slippage.none()`). */
    slippage?: SlippageModel;
    /** Short borrow-fee model (default `borrow.none()`). */
    borrow?: BorrowModel;
    /** Opening capital (default 1). */
    initialCapital?: number;
    /** Bars per year, for annualized metrics (default 252). */
    periodsPerYear?: number;
    /** Per-asset gross weight cap applied to the signal (default 1). */
    maxLeverage?: number;
    /** Bars between observing the signal and trading on it; ≥ 1 avoids look-ahead (default 1). */
    executionLag?: number;
    /** Annualized risk-free rate for Sharpe/Sortino (default 0). */
    riskFreeRate?: number;
}
Fields, parameters and returned members (28)

Loading 28 members…

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

iface

WalkForwardOptions

#

Public declaration. Read the signature and member contracts below; no additional behaviour is inferred.

Signature
import type { WalkForwardOptions } from '@insiderfinance/totalfinance/backtest';

export interface WalkForwardOptions {
    /** Bars in ascending time order (one symbol, or a pre-sorted multi-symbol stream). */
    data: Bar[];
    /** Training window length in bars. */
    trainSize: number;
    /** Test (out-of-sample) window length in bars. */
    testSize: number;
    /** Step between successive windows (default `testSize`, i.e. non-overlapping test windows). */
    step?: number;
    /** `rolling` (sliding train window) or `anchored` (train grows from the start). Default `rolling`. */
    mode?: 'rolling' | 'anchored';
    /** Run a backtest over a window; return its out-of-sample result. */
    run: (window: WalkForwardWindow) => BacktestResult;
    /** Bars per year for the stitched performance (default 252). */
    periodsPerYear?: number;
}
Fields, parameters and returned members (19)

Loading 19 members…

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

iface

WalkForwardResult

#

Public declaration. Read the signature and member contracts below; no additional behaviour is inferred.

Signature
import type { WalkForwardResult } from '@insiderfinance/totalfinance/backtest';

export interface WalkForwardResult {
    /** The per-window out-of-sample results, in order, each tagged with its train/test ranges. */
    windows: WalkForwardWindowResult[];
    /** Out-of-sample equity stitched across all test windows (starts at 1). */
    equityCurve: number[];
    /** Performance of the stitched out-of-sample curve. */
    performance: PerformanceSummary;
    /**
     * The echoed modelling assumptions, identical across windows (same engine/config) — taken from the
     * first window, so the walk-forward artifact carries the same honesty story as a single backtest
     * (WS2.8 / dx §2.5).
     */
    assumptions: BacktestAssumptions;
    /** Core diagnostics: the union of every window's warnings, deduped by code + message (WS2.8). */
    diagnostics: Diagnostics;
}
Fields, parameters and returned members (61)

Loading 61 members…

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

iface

WalkForwardWindow

#

Public declaration. Read the signature and member contracts below; no additional behaviour is inferred.

Signature
import type { WalkForwardWindow } from '@insiderfinance/totalfinance/backtest';

export interface WalkForwardWindow {
    train: Bar[];
    test: Bar[];
}
Fields, parameters and returned members (2)
Name · typeMeaning · unitRequired · default
testBar[]—unitless by nameRequiredNo @default declared
trainBar[]—unitless by nameRequiredNo @default declared

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

iface

WalkForwardWindowResult

#

A per-window out-of-sample result, tagged with the train/test time ranges it covered (WS2.8).

Signature
import type { WalkForwardWindowResult } from '@insiderfinance/totalfinance/backtest';

/** A per-window out-of-sample result, tagged with the train/test time ranges it covered (WS2.8). */
export interface WalkForwardWindowResult extends BacktestResult {
    /** `[firstTrainBarTs, lastTrainBarTs]`. */
    trainRange: [
        EpochMs,
        EpochMs
    ];
    /** `[firstTestBarTs, lastTestBarTs]`. */
    testRange: [
        EpochMs,
        EpochMs
    ];
}
Fields, parameters and returned members (68)

Loading 68 members…

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

iface

WeightContext

#

What a supplied-weights callback sees.

Signature
import type { WeightContext } from '@insiderfinance/totalfinance/backtest';

/** What a supplied-weights callback sees. */
export interface WeightContext {
    asOf: EpochMs;
    sessionDate: string;
    long: readonly SignalRow[];
    short: readonly SignalRow[];
    /** Trailing per-session returns per selected name, oldest first (as many as available). */
    trailingReturns: Readonly<Record<string, readonly number[]>>;
}
Fields, parameters and returned members (5)
Name · typeMeaning · unitRequired · default
asOfnumber—an instant: epoch milliseconds or a YYYY-MM-DD / zoned ISO string (the resolveAsOf convention)RequiredNo @default declared
longreadonly SignalRow[]—unitless by nameRequiredNo @default declared
sessionDatestring—calendar date (YYYY-MM-DD)RequiredNo @default declared
shortreadonly SignalRow[]—unitless by nameRequiredNo @default declared
trailingReturnsReadonly<Record<string, readonly number[]>>

Trailing per-session returns per selected name, oldest first (as many as available).

unitless by name
RequiredNo @default declared

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

type

WeightingMethod

#

Public declaration. Read the signature and member contracts below; no additional behaviour is inferred.

Signature
import type { WeightingMethod } from '@insiderfinance/totalfinance/backtest';

export type WeightingMethod = 'equal-weight' | 'score-weight' | 'inverse-volatility' | 'risk-budget' | 'supplied-weights';

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

const

agentBaselines

#

Public declaration. Read the signature and member contracts below; no additional behaviour is inferred.

Signature
import { agentBaselines } from '@insiderfinance/totalfinance/backtest';

export declare const agentBaselines: Readonly<{ holdCash: () => BaselinePolicy; buyAndHold: (input?: { weights?: Readonly<Record<string, number>>; }) => BaselinePolicy; periodicRebalance: (input: { everySessions: number; weights?: Readonly<Record<string, number>>; }) => BaselinePolicy; randomValidAction: (seed: number) => BaselinePolicy; riskParity: (input: { lookback: number; everySessions?: number; }) => BaselinePolicy; momentumCrossover: (input: { fast: number; slow: number; }) => BaselinePolicy; }>;
Fields, parameters and returned members (66)

Loading 66 members…

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.