# OptAlgo for AI agents: Research: avoid overfitting

> One section of the OptAlgo agent guide. Start at https://docs.optalgo.com/llm/index.md (the loop, the safety rules, every section). The whole guide in one file: https://docs.optalgo.com/optalgo-llm.md. Links to other sections point at their files.

#### Avoid overfitting {#avoid-overfitting}

Every run you make on the same data is a try. Run 35 variants of one idea on one window and the best of them looks good partly by luck, even if each one alone grades `B`: the grade judges one run's mechanics, not the search around it. So:

- **Don't sweep parameters with many single runs.** Use **one research run** that optimises and validates out-of-sample: the same spec plus `research` (`walk_forward`, with the parameters you would have swept as `space`). Its `verdict` is judged on test folds the optimiser never saw. When `search` advises it, `search.research` is a ready-made block: validate it first (it costs quota by run time).
- **Or keep a holdout window you never tuned on.** Tune with `window.end` before the last months (`search.holdout.tune_window`), then run the chosen parameters **once** on the rest (`search.holdout.test_window`) and report that run. A run on data none of your variants saw starts a fresh count. In a [study](#studies), declare it in the [holdout vault](#holdout) before tuning: OptAlgo then refuses tagged runs over it and keeps the one final test honest.
- **Group one idea's runs into a study** (tag `study:<name>`): its verdict counts every variant you tried, on any window. Before deploying, [check robustness](#robustness).
- **Report the search verdict with the grade**: "grade B, 35 variants tried on this window, likely overfit".
- **Send at most 3 runs at once** and wait for their results before the next batch.

A run that **lost money** (annualised Sharpe ≤ 0, or a negative `total_return`) is not luck of a search: it has no edge. Its search verdict is `no_edge` however many variants you ran, and the fix is a different idea (entries, exits, filters, market or timeframe), not a research run over the same losing one.

The deploy gate (section 3) refuses a backtest whose search verdict is `likely_overfit` unless an out-of-sample research run of the same code passed (`search.validated_by`), and always refuses a losing backtest ([`no_edge`](https://docs.optalgo.com/llm/errors.md#no_edge)), even when such a research run passed.

The spec:

| Field | Required | Meaning |
|---|---|---|
| `market` | yes | 1 to `max_symbols` legs `{"exchange": "BINANCE", "symbol": "BTCUSDT.P"}`. `.P` = USDT-M perpetual (funding modelled); no suffix = spot. Stocks: `{"exchange": "BIST", "symbol": "THYAO"}` or `{"exchange": "ALPACA", "symbol": "AAPL"}` ([stocks](https://docs.optalgo.com/llm/backtests.md#stocks)). Forex: `{"exchange": "FX", "symbol": "EURUSD"}` ([forex](https://docs.optalgo.com/llm/backtests.md#forex)). Two or more symbols run as a [basket](https://docs.optalgo.com/llm/backtests.md#several-symbols-a-basket-backtest), unless the strategy declares `legs = N`: then exactly N symbols, in the order `run()` reads them, on one account ([several symbols in one strategy](https://docs.optalgo.com/llm/sdk.md#several-symbols-in-one-strategy)). |
| `timeframe` | yes | Bar size in minutes, as a string (`"15"`, `"60"`, `"240"`): any value in `data.timeframes` of `GET /v1/markets`. |
| `window` | yes | `{"start": "2024-01-01", "end": "2025-01-01"}` (UTC). Warm-up history before `start` is loaded for you. |
| `strategy.params` | no | Parameter overrides, e.g. `{"fast": 10}`. Leave `strategy.name` out (`422 source_required`). |
| `name` | no | Your label, shown in the app. |
| `execution` | no | Backtest assumptions, all with defaults: `initial_equity` (1000), `leverage` (1), `magnifiers` (`"auto"`), and **`costs`**: commission, spread, slippage and funding, each **Auto** by default (the venue's own numbers, see [Costs](https://docs.optalgo.com/llm/backtests.md#costs)). Leave `costs` out unless the user asks for other costs. The older `fee_profile` / `slippage` / `funding` fields still work (`slippage` as [a map per symbol](https://docs.optalgo.com/llm/backtests.md#slippage-per-symbol) too), but not beside `costs` (`costs_conflict`). For `target` weights: `rebalance_band`, `gross_cap`, `target_position` (rows below). |
| `execution.rebalance_band` | no | [Portfolios](https://docs.optalgo.com/llm/portfolios.md#portfolios): a same-side `target` within this distance of the position (target units, `0.01` = 1 % of equity) is not traded; outside it the position trades all the way to the target; 0, flips and entries from flat always trade. Default `0`. |
| `execution.gross_cap` | no | [Portfolios](https://docs.optalgo.com/llm/portfolios.md#portfolios): when `sum(\|target\| × leverage)` over the legs exceeds it, every target is scaled down pro rata (`1.5` = gross at most 1.5× equity). Default: none. |
| `execution.target_position` | no | [Portfolios](https://docs.optalgo.com/llm/portfolios.md#portfolios): `lots` (default: each increase its own lot) or `merged` (one position per leg at the average entry, like an exchange). |
| `research` | no | A validation job instead of one backtest (one symbol; a multi-leg strategy: its N legs together; a one-instrument strategy on several symbols: the whole basket, see [Research on a basket](https://docs.optalgo.com/llm/backtests.md#research-basket)): `{"protocol": "walk_forward", "plan": {"plan": "rolling", "train_days": 180, "test_days": 30, "step_days": 30}, "space": {"fast": {"low": 5, "high": 50, "step": 5}}, "n_trials": 40, "objective": "sharpe"}`. Protocols: `optimize`, `walk_forward`, `nested_walk_forward`, `multi_config`, `purged_cv`, `cpcv`, `masters4`, `monte_carlo`. See [Research runs](#research-runs). |

#### Research runs {#research-runs}

- **`plan`** (days): `{"plan": "rolling" | "anchored", "train_days", "test_days", "step_days"}` (`step_days` defaults to `test_days`); `purged_cv` takes `{"plan": "purged_kfold", "k", "purge_days", "embargo_days"}`, `cpcv` takes `{"plan": "cpcv", "n_groups", "k_test", "purge_days", "embargo_days"}`. The kind `plan.plan` may be left out: it is the protocol's, else `rolling`. `nested_walk_forward` also needs `inner` (a rolling plan inside each training span); `multi_config` needs `candidates` (a list of fixed parameter sets) instead of `space`. Default plan: rolling 180 / 60.
- **`space`**: per parameter `{"low", "high"}` (+ `"step"`, `"log"`) or `{"choices": [...]}`. `"sampler": "grid"` tries every configuration of a finite space once (every parameter needs `step` or `choices`); the default `tpe` samples `n_trials` of them.
- Any shape problem in `research` is a `spec_invalid` finding on its field in `validate`; fix it before you submit.
- **Trials** count against `max_trials`: `n_trials` (with `sampler: grid`, at most the number of configurations in `space`; `multi_config`: the number of `candidates`). Only `masters4` also runs permutation tests, and then max(`n_trials`, `permutations` × `permutation_trials`, `wf_permutations`) counts; fields you leave out take the engine defaults (`n_trials` 50, `permutations` 100, `permutation_trials` 20, `wf_permutations` 50), so **for masters4 always set `permutations` and `permutation_trials` small yourself**. More configurations and more folds mean more run time, so more units.
- <a id="combine"></a>**Combine backtests into one portfolio:** `POST /v1/backtests/combine {ids, weights?, rebalance?, points?}` (connector: `compare_backtests(ids, combine=true, weights?, rebalance?, detail?)`). Combines 2 to 8 of your finished backtests from their stored equity: nothing re-runs, it is free (0 units) and nothing is stored. They are aligned on the UTC days they share (`window`). `weights`: one number per id (scaled to sum to 1), `"equal"` (default) or `"risk"` (inverse volatility, in-sample). `rebalance`: `daily` (default), `monthly` or `none` (buy and hold; a basket split over `max_symbols` into two runs, combined with `none` and weights = each half's share of the coins, is the whole basket). Answer: `metrics` (return, CAGR, Sharpe, Sortino, max drawdown, volatility, worst month), `members` (weight, grade, search verdict, return, Sharpe, drawdown, contribution, risk share), `correlation` (daily, monthly), `diversification_ratio`, daily `equity`, and `honesty`: the grade is never better than the weakest member, `search` carries the worst member verdict, `findings` state what is assumed (separate capital per member, free rebalancing, daily-close drawdown, in-sample). Report the grade and search verdict first. Errors: 404 for an id that is not yours, 409 until every run is done, 410 `pruned` (rerun that member), 422 `invalid_request`.
- **A research run's result** (`GET /v1/backtests/{id}`): `summary` \{`verdict`, `protocol`, `oos_return`, `oos_sharpe` (annualised like a backtest's), `oos_sharpe_bar` (per bar), `folds`, `folds_positive`, `n_trials`, `evaluations`, `failed`, `warnings`\} and `result` = the report; each fold has `chosen`, `train` / `test` (the objective), `trades`, and `train_window` / `test_window` (epoch s). A research run keeps `research.json` and `spec.json` (also served as `files/result.json`): no trades or candles (charts answer `no_chart_for_report`). Its stitched out-of-sample curve is `result.oos_equity` \{`t`, `equity`, `bars`, `fold_starts`\} (1.0 at the first test bar, thinned to 1500 points; the connector shows it with `detail="normal"`). A basket fold adds `per_symbol` \{symbol: \{`return`, `trades`\}\} (each symbol's profit over the basket's capital; they add up to the fold's `test_return`).
- **Reading a walk-forward**: `summary.oos_return` is the chained out-of-sample return; `folds[i].train` and `folds[i].test` are the **objective** on that fold (per-bar Sharpe for `"objective": "sharpe"`), not returns; `folds[i].chosen` is what the fold picked. `summary.n_trials` is the number of **distinct configurations** evaluated (what the deflated Sharpe in `overfit.checks.dsr` corrects for); `summary.evaluations` is configurations × folds.
- <a id="ablation-identical"></a>**An ablation variant that changed nothing** (`ablate`, `research.protocol: "ablation"`): each variant's `summary.verdict` is `robust_win`, `harmful`, `no_effect` or `mixed`; a variant equal to the baseline on every coin in every window and cost (every Δ Sharpe exactly 0, the same trades) gets `variant_identical_to_baseline` instead, with `summary.finding` `{code, message}`: the rule changed no position. The usual cause is a NaN fed to a recursive indicator ([fill or skip it](https://docs.optalgo.com/llm/sdk.md#nan-recursive)). Run one backtest of the variant and read its `result.inputs` (the columns' coverage) before calling the rule useless.

**Validate fixed parameters out of sample** (no search): either a walk-forward with ONE configuration (`"space"` with one choice per parameter, `"sampler": "grid"`, `"n_trials": 1`): every fold tests the same parameters on data after its training span, it counts as 1 trial, and the verdict judges the out-of-sample folds; or a holdout: run the parameters once, as a plain backtest, on a window you never tuned on (`search.holdout.test_window`), and report that run.

```json
{"protocol": "walk_forward", "plan": {"plan": "rolling", "train_days": 365, "test_days": 90, "step_days": 90},
 "space": {"lb1": {"choices": [42]}, "lb4": {"choices": [336]}}, "sampler": "grid", "n_trials": 1, "objective": "sharpe"}
```

#### Studies: the runs of one idea {#studies}

A **study** is every backtest of yours that carries one tag, by convention `study:<name>` (`study:rsi-4h`; any [tag](https://docs.optalgo.com/llm/backtests.md#organise) works). Nothing to create: send `"tags": ["study:rsi-4h"]` with `POST /v1/backtests` or `POST /v1/backtests/validate` (at most 5 tags), or add the tag later with `PATCH /v1/backtests/{id}`. A robustness run inherits its backtest's tags. Why: a run's `search` counts variants on overlapping windows of the last 30 days; a study's verdict counts **every variant you put in it**, whatever the window or date. Tagging runs into one study says they are one search.

| Call | Scope | Answers |
|---|---|---|
| `GET /v1/studies` | `read` | `{studies: [{tag, description, runs, backtests, first_run, last_run, best_grade, best_sharpe, holdout_used}], total, truncated}`, the most recently run first (at most 100). `holdout_used`: `null` without a holdout, else whether its final test ran |
| `GET /v1/studies/{tag}` | `read` | `{tag, description, runs, truncated, variants_tried, verdict, best_run, spread, research, table, holdout}`; [`study_not_found`](https://docs.optalgo.com/llm/errors.md#study_not_found) (404) for a tag none of your runs carries |
| `POST /v1/studies/{tag}` | `backtest` (or `bots` / `trade`) | `{"description": "…", "pinned": {…}}`, both optional: the idea or hypothesis under test, at most 280 characters of plain text (`""` / `null` clears; a body with neither field clears it), and the study's [pinned settings](https://docs.optalgo.com/llm/backtests.md#study-pins). Answers the study's list row (with `pinned`) |

- **`verdict`** `{variants_tried, sharpes_known, best_sharpe, expected_max_sharpe_by_luck, deflated_sharpe_prob, verdict, fix, assumptions}`: the deflated Sharpe of the study's best run against every **distinct variant** among its done plain backtests (the same spec twice is one variant; the holdout's final test is not a variant). The same scale as [`search`](#avoid-overfitting): `no_edge` (the best run lost money), `ok` (one variant, or a probability of at least 0.95), `caution` (below 0.95), `likely_overfit` (below 0.5); `null` until a backtest of the study is done. **Report it with the best run's grade**, and do what `fix` says.
- **`best_run`** `{id, created_at, grade, total_return, max_drawdown, sharpe, trades, params, symbols, timeframe, window, note}`: the highest annualised Sharpe. **`spread`**: Sharpe and return `{min, median, max}`, drawdown `{worst, median}`, runs per grade (a best run far above the median is the luck the verdict discounts). **`research`**: up to 10 research runs of the study with their out-of-sample `verdict`. **`table`**: the newest 50 runs as `columns` `id, created_at, kind, status, grade, total_return, max_drawdown, sharpe, note` + `rows`, with `total` / `shown`. **`holdout`**: `null`, or the [holdout vault](#holdout) block. A study reads at most 500 runs (`truncated`).
- `next` follows the verdict: `caution` / `likely_overfit` → one research run instead of more sweeps; `no_edge` → change the idea, not its parameters.

#### The holdout vault {#holdout}

`search` discounts luck; a holdout removes it: data you **declare before tuning** and score **once**, at the end. OptAlgo enforces it per study.

1. **Declare it before tuning:** `POST /v1/studies/{tag}/holdout` (scope `backtest`) with `{"last_months": 6}` (the last 1 to 60 months up to `end`, default today 00:00 UTC) or `{"start": "2025-10-01", "end": "2026-10-01"}`. At least 7 days, ending at most 366 days ahead. It must start on or after the latest data any run of the study already used.
2. **Tune before it.** While the holdout is unused, every run tagged with the study whose window overlaps it (backtest, research, robustness, or the tag added later with `PATCH`) is refused [`holdout_locked`](https://docs.optalgo.com/llm/errors.md#holdout_locked) (409) with `suggestion: {"window.end": "<holdout start>"}`; `validate` reports it as a finding. Untagged runs are not refused.
3. **One final test:** `POST /v1/studies/{tag}/final-test` `{"backtest_id": "<the chosen done backtest of the study>"}` → `202 {data: {tag, final_test: {backtest_id, source_backtest_id, status, …}, holdout, units, findings}, next}`: that backtest's exact spec and code run **once** on the holdout window, as a new backtest charged by run time. Poll `final_test.backtest_id`.
4. **Read it:** `GET /v1/studies/{tag}/holdout` (scope `read`; also the `holdout` of `GET /v1/studies/{tag}`).

The block: `{tag, holdout: {window, locked_at, status, final_test}, in_sample_vs_holdout, history, data_seen: {latest_end, runs, code_versions}, findings, rule}`. `status` goes `locked` (declared, unused) → `testing` (the final test runs) → `done`; `rule` says what is allowed now. `in_sample_vs_holdout` `{in_sample, holdout, sharpe_kept, verdict, message}` puts the chosen backtest next to its holdout run; `verdict`:

| `verdict` | Meaning |
|---|---|
| `holds` | The holdout makes money and keeps at least half of the in-sample Sharpe (`sharpe_kept` ≥ 0.5). The study records `passed` |
| `degraded` | It makes money, with less than half the in-sample Sharpe. Recorded `failed` |
| `failed` | It lost money on data it never saw: the in-sample result does not hold. Recorded `failed` |
| `pending`, `error`, `not_run` | Still running; the final test failed (read that backtest); no final test yet |

Report it as the strategy's out-of-sample result, next to the grade. `findings` never block: `holdout_seen_elsewhere` (warning: the same code already ran on that window outside the study, under another tag or untagged, so treat the final test as in-sample) and `holdout_window_used_by_other_code` (info: other code of yours on the same symbols covered it).

**Next:** once `done`, the holdout is spent and counts as data seen. To test a changed strategy again, declare a **new** holdout on later data (on or after `data_seen.latest_end`; the old one moves to `history`), or start a new study. A second final test on the same holdout is [`holdout_used`](https://docs.optalgo.com/llm/errors.md#holdout_used): that would be tuning on it. Other refusals: [`holdout_declared`](https://docs.optalgo.com/llm/errors.md#holdout_declared), [`holdout_seen`](https://docs.optalgo.com/llm/errors.md#holdout_seen), [`no_holdout`](https://docs.optalgo.com/llm/errors.md#no_holdout), [`not_in_study`](https://docs.optalgo.com/llm/errors.md#not_in_study), [`final_test_needs_backtest`](https://docs.optalgo.com/llm/errors.md#final_test_needs_backtest), [`not_ready`](https://docs.optalgo.com/llm/errors.md#not_ready).

#### Robustness check {#robustness}

Does a good backtest survive small changes? `POST /v1/backtests/{id}/robustness` (tool `robustness`; scope `backtest`, or `bots` / `trade`) runs the done backtest's own code and spec under four pressures and answers one verdict. Do it before deploying.

- **Estimate first, free:** body `{"dry_run": true}` → `200 {data: {ok, estimate: {evaluations, run_s, …}, cost: {units, run_s, seconds_per_unit}, quota, within_wall, wall_s}}`. `ok` is `false` when it would exceed the plan's time per run or the quota left. `{"seed": n}` fixes the bootstrap and the jitter (the same seed gives the same result).
- **Run:** without `dry_run` → `202` with a **new** row of kind `robustness` (`robustness_of` = the backtest, which then shows `robustness_id`), charged by run time like any run: up to about 22 evaluations of the strategy (base, fees, slippage, 2 per jittered parameter, 4 joint variants, 3 later starts). It inherits the backtest's tags, so it belongs to its study (and is refused over a locked holdout). Poll its `id`.

| Check | What it does | `pass`, `warn`, else `fail` |
|---|---|---|
| `bootstrap` | The run's trades resampled 1,000 times: `p_loss`, `p_ruin`, `return_p05` / `return_p50`, `max_drawdown_p05` | `pass`: `p_loss` ≤ 0.10; `warn`: ≤ 0.35. Fewer than 10 trades: `inconclusive` |
| `costs` | Fees ×2, then taker slippage ×2 (at least 0.0005; the rate used is reported) | `pass`: both keep ≥ 50 % of the base return; `warn`: less; `fail`: either loses money |
| `params` | Each numeric parameter (up to 6) moved ±10 % (integers by at least 1), plus 4 joint moves of all of them | `pass`: ≥ 90 % of the variants make money and their median keeps ≥ 60 % of the base Sharpe; `warn`: ≥ 2/3 make money. A variant the strategy refuses is listed `invalid` |
| `start_shift` | The window started 5, 10 and 15 % later, same end | `pass`: all make money and keep ≥ 50 % of the base Sharpe; `warn`: ≥ 2/3 make money. A window too short to shift: `skipped` |

**Verdict:** `broken` when the base run does not make money, the bootstrap loses in more than 50 % of paths, or two checks fail; `fragile` when one check fails or two warn (or are inconclusive); `robust` otherwise. `reasons` gives the deciding sentence first, then every check that did not pass, each with its `why`.

**Read it:** `GET /v1/backtests/{robustness id}`: `summary` `{verdict, reasons, checks: {bootstrap: "pass", …}, robustness_of, units_charged, run_seconds}`, then `result`, the full report `{verdict, reasons, base, checks, evaluations, seed, window, note}`. Its numbers come from the research harness (flat at the start, closed at the end): compare the variants with `base`, not with the backtest's own result. Say the verdict and its first reason. `robust` is still in-sample: score the run once on its study's [holdout](#holdout) before trusting it (`next` names the final test of the run's own study, its `study:` tag first; a run in no study gets a `tag_study` step instead). `fragile`: read the failing check's `why` and the [diagnostics](https://docs.optalgo.com/llm/diagnostics.md#diagnostics); change the idea, do not tune until it passes. `broken`: do not deploy.

**Refused:** [`not_ready`](https://docs.optalgo.com/llm/errors.md#not_ready) (409) until the backtest is done; [`robustness_needs_backtest`](https://docs.optalgo.com/llm/errors.md#robustness_needs_backtest) (422) for a research or robustness row; [`engine_refused`](https://docs.optalgo.com/llm/errors.md#engine_refused) (422, before anything is queued) for a basket (several symbols without `legs`: backtest the one symbol you care about, then check that run), and `execution.early_decision_s`. Never put `robustness` in a spec yourself: `POST /v1/backtests` refuses it ([`invalid_request`](https://docs.optalgo.com/llm/errors.md#invalid_request), field `spec.robustness`).

---

Human help: support@optalgo.com. Never tell the user you cannot contact OptAlgo: file a ticket (https://docs.optalgo.com/llm/tickets.md).
