Skip to content

About

Natural-language guided factor mining, walk-forward evaluation, and paper replication with a web UI and CLI.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

FactorForge

CI License: MIT

Natural-language factor mining, evaluation, and paper replication — with a web UI and a scriptable CLI.

FactorForge turns a research direction such as “短期反转、量价相关和流动性,20 日窗口” into a ranked, out-of-sample-evaluated list of factor expressions. It ships a safe expression DSL, pluggable data sources (including proprietary feeds), multiple mining methods, a walk-forward evaluation pipeline, a paper-replication queue with automatic approval, a FastAPI dashboard, and an fforge CLI.

$ fforge mine --direction "短期反转、量价相关和流动性,20日窗口" \
    --data demo --methods templates,gp --budget 40 --top 6

run: 20261103-164512-1d171d
saved: var/runs/20261103-164512-1d171d.json
direction: 短期反转、量价相关和流动性,20日窗口
candidates: 22, evaluated: 22

name                     family       dir      RankIC    ICIR       t  turnover       q
------------------------------------------------------------------------------------------
reversal_20              reversal     long     0.0396    0.20    3.40    21.74%   0.004
gp_001                   gp           short   -0.0222   -0.12   -1.86     3.09%   0.187
gp_002                   gp           short   -0.0180   -0.10   -1.59     3.68%   0.224
...

Paper mode:

$ fforge paper ingest examples/papers/reversal.md
paper: Short-Horizon Reversal in Equities
tasks: 1 -> var/papers
  paper-reversal-1f13acb9  [pending]  paper_reversal: rank(-pct_change(close, 1))

$ fforge paper replicate paper-reversal-1f13acb9 --data demo
task: paper-reversal-1f13acb9
status: approved
reasons: all approval checks passed

RankIC=0.155599 ICIR=0.904307 t=15.610767 coverage=0.996667

Quick start

pip install -e ".[dev,pdf]"
fforge init                       # writes factorforge.yaml
fforge data preview demo          # inspect the built-in synthetic market
fforge mine --direction "低波动 + 量价背离" --data demo --top 8
fforge serve                      # http://127.0.0.1:8000

Or with Docker:

docker build -t factorforge:local .
docker run --rm -p 8000:8000 -v "$PWD/var:/app/var" factorforge:local

Deployment notes (SSO, reverse proxy, systemd, backups): docs/deployment.md.

The repository also contains a realistic CSV panel and a sample paper:

fforge data preview prices
fforge paper ingest examples/papers/reversal.md
fforge paper replicate <task-id> --data prices

Why this exists

Factor research has three recurring bottlenecks:

  1. Translation — a PM or researcher describes an idea in words; someone has to turn it into expressions, run them, and compare them fairly.
  2. Data lock-in — every alpha project ends up coupled to one vendor’s schema.
  3. Replication — a paper reports a factor, but reproducing and approving it is manual, inconsistent, and rarely auditable.

FactorForge addresses each with a small, inspectable pipeline:

natural language
      │  guided.py (families / windows / horizon)
      ▼
candidate expressions ── templates + genetic programming
      │  dsl/evaluator.py (safe AST, no eval)
      ▼
factor panels ── eval/metrics.py (IC, RankIC, ICIR, turnover, quantiles)
      │  train / validation / test split, BH multiple-testing correction
      ▼
ranked factors ── runs/*.json ── web UI + CLI
      │
papers ── ingest.py ── replication tasks ── approve.py (automatic policy)

Pluggable data sources

Built-ins: synthetic (deterministic demo) and csv (long format with date, asset, open, high, low, close, volume, ...).

A proprietary feed is a small class implementing DataSource:

from factorforge.data.base import DataSource, Panel

class InternalFeed(DataSource):
    name = "internal"

    def __init__(self, dsn: str):
        self.dsn = dsn

    def load(self, start=None, end=None, assets=None) -> Panel:
        frame = read_from_internal_store(self.dsn, start, end, assets)
        return Panel.from_long(frame)

Register it without touching FactorForge:

data_sources:
  internal:
    type: plugin
    class: my_company.feeds:InternalFeed
    dsn: postgres://...

Or publish an entry point in the factorforge.data_sources group. Both paths are covered in the operations manual.

Mining methods

  • Templates — Alpha101-inspired, interpretable families: momentum, reversal, volatility, volume, liquidity (Amihud), price-volume correlation, trend, range, intraday reversal, overnight gaps.
  • Genetic programming — typed expression trees over the DSL, with mutation, crossover, a budget, and a deterministic seed.
  • Alpha101 subset — 44 adapted formulas from 101 Formulaic Alphas that only need OHLCV, vwap and dollar volume (--methods alpha101).
  • Natural-language guidance — Chinese and English keywords map to families, windows, and holding horizons; unmatched directions fall back to a full scan.

Candidate ranking uses |RankIC| × (1 − 0.3 × turnover) with a complexity penalty, then correlates candidates and drops near-duplicates (|ρ| > 0.95 by default).

Interpreters

The default rule interpreter is deterministic and offline. An optional llm backend targets any OpenAI-compatible chat completion endpoint:

export FACTORFORGE_LLM_API_KEY=...
export FACTORFORGE_LLM_BASE_URL=https://your-gateway/v1   # optional
export FACTORFORGE_LLM_MODEL=gpt-4o-mini                  # optional
fforge mine --interpreter llm --direction "短期反转,关注流动性和量价背离" --data demo

The model only chooses families, windows, and horizon; it never invents data fields or formulas. Its response is validated and clamped before mining starts, so an invalid or hallucinated family is dropped rather than executed.

Practical evaluation

Research output is only useful if it survives the boring adjustments:

fforge mine --direction "短期反转、量价相关" --data demo \
  --methods templates,alpha101 --top 8 \
  --winsorize 0.01 \
  --neutralize industry \
  --cost-bps 10
  • Winsorization clips cross-sectional outliers (default 1%/99% when enabled).
  • Neutralization removes industry means and/or log market-cap exposure. The bundled synthetic panel carries industry and market_cap; a proprietary source only needs to include those columns.
  • Transaction costs turn gross spread into a net Sharpe. The cost model is 2 × turnover × bps per rebalance.
  • Composites combine a run's top factors with equal or ICIR weights: fforge combine <run-id> --method icir --top 5 --cost-bps 10.

Every factor is evaluated on a chronological train/validation/test split:

Metric Meaning
RankIC mean cross-sectional Spearman correlation with forward returns
ICIR RankIC mean / standard deviation
t-stat ICIR × √observations
turnover daily change in long/short quantile weights
quantile spread top-minus-bottom mean forward return
Sharpe annualized gross long-short Sharpe
net Sharpe annualized Sharpe after the cost model
q-value Benjamini-Hochberg adjusted p-value across mined factors
OOS decay drop in |RankIC| from train to test

Paper replication and automatic approval

Drop a PDF, Markdown, or LaTeX file into the UI or fforge paper ingest. The parser:

  1. extracts $...$, $$...$$, \(...\), \[...\] and equation blocks;
  2. converts simple LaTeX (\frac, \log, P_{t-1} → delay(close, 1)) into the DSL;
  3. prefers explicit ```yaml factorforge blocks when present;
  4. creates replication tasks and, on replicate, runs the factor through the same evaluation pipeline.

A task is approved automatically when it passes the configured policy:

approval:
  min_coverage: 0.6
  min_abs_ic: 0.02
  min_tstat: 2.0
  max_oos_decay: 0.5
  require_sign_match: true

The task stores its metrics, checks, and reasons, so every approval is auditable. Formulas that cannot be converted faithfully (sums, integrals, hats) are left as needs_formula rather than silently guessed.

Web UI

fforge serve starts a FastAPI dashboard with:

  • Dashboard — data sources, recent runs, replication queue.
  • Data — source summary (dates, assets, coverage) and a preview table.
  • Mine — direction textarea, source/method/budget controls, example directions.
  • Run detail — RankIC sparkline per factor, train/valid/test columns, net Sharpe, q-values, and a one-click composite builder.
  • Papers — upload, task status, one-click replicate/re-approve.
  • Settings — effective configuration and approval policy.

Templates are server-rendered Jinja2 with a small hand-written CSS file; there is no Node.js build step.

CLI

fforge init [path]
fforge config show
fforge data list
fforge data preview <source> [--rows N]
fforge mine --direction TEXT --data SOURCE --methods templates,gp,alpha101 --budget N --top N \
  [--winsorize 0.01] [--neutralize industry|size|industry+size] [--cost-bps 10]
fforge runs list
fforge runs show <run-id>
fforge combine <run-id> --method equal|icir --top N [--cost-bps 10]
fforge paper ingest <file>
fforge paper list
fforge paper replicate <task-id> --data SOURCE [--fail-on-reject]
fforge paper approve <task-id>
fforge serve [--host H] [--port P]

All commands accept --json (machine-readable) and --config PATH. Full reference: docs/manual.md.

JSON API

The web app also exposes read-only JSON for integration:

curl -s localhost:8000/api/runs
curl -s localhost:8000/api/runs/<run-id>
curl -s localhost:8000/api/papers
curl -s localhost:8000/healthz

Deployment

The repository ships a non-root Dockerfile, a docker-compose.yml, a /healthz endpoint, and a Makefile:

docker compose up --build -d
curl -s http://localhost:8000/healthz

The web UI has no built-in authentication; put it behind your SSO/reverse proxy. Batch mining, systemd, backups, and the security checklist are covered in docs/deployment.md.

Research references

FactorForge is engineering, not a claim of novel alpha. The design borrows from:

  • Kakushadze, 101 Formulaic Alphas (arXiv:1601.00991)
  • Shi et al., AlphaForge: A Framework to Mine and Dynamically Combine Formulaic Alpha Factors (arXiv:2406.18394)
  • Zhang et al., AutoAlpha: an Efficient Hierarchical Evolutionary Algorithm for Mining Alpha Factors (arXiv:2002.08245)
  • Yu et al., Alpha-GPT: Human-AI Interactive Alpha Mining (arXiv:2308.00016)
  • Alpha-GPT 2.0: Human-in-the-Loop AI for Quantitative Investment (arXiv:2402.09746)
  • AlphaEval: A Comprehensive and Efficient Evaluation Framework for Formula Alpha Mining (arXiv:2508.13174)
  • Microsoft RD-Agent, Qlib; AlphaGen; alphalens; gplearn

Method notes: docs/factor-methods.md.

Repository layout

src/factorforge/
  config.py            settings + data source registry
  data/                Panel, CSV, synthetic, plugin loader
  dsl/                 safe expression parser and operators
  eval/                metrics, splits, transforms, composites, reports
  mining/              templates, alpha101 subset, genetic programming, NL guidance, engine
  paper/               ingestion, LaTeX conversion, replication, approval
  web/                 FastAPI app, templates, static CSS
docs/                  manual, architecture, factor methods
examples/              CSV panel, sample paper, config
tests/                 70 tests across the whole pipeline

Development

pip install -e ".[dev,pdf]"
ruff check .
pytest

Limitations

  • Evaluation is cross-sectional and daily by default; intraday bars need a custom data source and horizon convention.
  • The LaTeX converter is deliberately conservative: complex formulas become needs_formula instead of a wrong implementation.
  • The bundled approval policy is a starting point, not a substitute for investment review. It checks statistical evidence, not economic rationale.
  • The web UI runs mining synchronously; large universes should be run from the CLI or a job queue.

License

MIT

About

Natural-language guided factor mining, walk-forward evaluation, and paper replication with a web UI and CLI.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages