API Reference
This page summarises the primary extension points for building strategies and tooling on top of Microalpha.
Runner (microalpha.runner)
run_from_config(path: str, override_artifacts_dir: str | None = None) -> dict- Loads a YAML config, resolves paths, executes the backtest, and returns a manifest-style dictionary containing artifact paths.
override_artifacts_diroverrides the root output directory without modifying the on-disk YAML.prepare_artifacts_dir(cfg_path: Path, config: dict) -> tuple[str, Path]- Allocates an isolated
artifacts/<run_id>directory for each run.
Engine (microalpha.engine.Engine)
Engine(data, strategy, portfolio, broker, rng: numpy.random.Generator | None = None)
- Streams
MarketEvents from the data handler, enforces monotonic timestamps, and routes signals/orders/fills between components. - Accepts a
numpy.random.Generatorfor reproducibility; randomness is typically consumed by downstream components (e.g., latency models) rather than the engine itself.
Profiling:
- Set MICROALPHA_PROFILE=1 or pass --profile via the CLI to record a profile.pstats under the active run’s artifact directory.
Data (microalpha.data.CsvDataHandler)
CsvDataHandler(csv_dir: Path, symbol: str, mode: str = "exact")
- Loads OHLCV CSV data and produces chronological
MarketEvents viastream(). get_latest_price(ts)supports"exact"and"ffill"modes for timestamp alignment.get_future_timestamps(start_ts, n)schedules TWAP child orders without lookahead.get_recent_prices(symbol, end_ts, lookback)for sizing;get_volume_at(symbol, ts)for VWAP.
Portfolio (microalpha.portfolio.Portfolio)
Portfolio(data_handler, initial_cash, *, max_exposure=None, max_drawdown_stop=None,
turnover_cap=None, kelly_fraction=None, trade_logger=None,
capital_policy=None)
- Tracks cash, inventory, and equity while enforcing exposure/drawdown/turnover limits.
- Emits fills to the
JsonlWriter(trade_logger) so executions are captured intrades.jsonl. - Provides
on_market,on_signal, andon_fillhooks consumed by the engine. - Adds realized PnL attribution per fill (average-cost) under
realized_pnland cumulativecum_realized_pnlin trades. - Resolve config-driven capital policies via
capital_policyin YAML; the runner instantiates them automatically.
Broker & Execution (microalpha.broker, microalpha.execution)
SimulatedBroker(executor)– wraps anExecutorand enforces t+1 semantics before returning fills.Executor– base class implementing simple price-impact + commission fills against theDataHandler.TWAP– splits orders evenly across future timestamps supplied by the data handler.VWAP– splits by future-tick volumes; usesDataHandler.get_volume_atif available (requiresvolumecolumn).ImplementationShortfall– front-loaded geometric schedule controlled byurgency.SquareRootImpact/KyleLambda– stylised impact models for execution cost studies.LOBExecution– routes orders to the in-memory level-2 book (microalpha.lob.LimitOrderBook) with latency simulation.- Supply
slippagein YAML to enableVolumeSlippageModelwithout hand-wiring objects.
Logging (microalpha.logging.JsonlWriter)
JsonlWriter(path: str)
- Creates parent directories, writes JSON-serialised objects per line, and flushes eagerly so artifacts remain tail-able.
Refer to the module docstrings and tests for deeper examples of composing these components.
Capital Allocation (microalpha.capital)
VolatilityScaledPolicy(lookback=20, target_dollar_vol=10000)scales base order qty inversely to recent per-symbol volatility.- Pass into
Portfolio(..., capital_policy=VolatilityScaledPolicy(...))or declare undercapital_policyin YAML to enable per-name risk targeting.
CLI (microalpha.cli)
microalpha run -c <cfg> [--out DIR] [--profile]microalpha wfv -c <cfg> [--out DIR] [--profile]
--out overrides the artifacts root directory; --profile enables cProfile.