Skip to main content

In a Fable 5.2 backtest recipe, Python retuning raised the p-value from 0.152 to 0.874 on synthetic data

Updated 10 min readMarkdown
In a Fable 5.2 backtest recipe, Python retuning raised the p-value from 0.152 to 0.874 on synthetic data

Fable 5.2 can organize trading-strategy research in Claude Code while Python calculates the results. In a December 1, 2026 example with synthetic returns, scoring the originally selected parameters on 1,000 shuffled paths gave a p-value of 0.1518. Repeating the parameter search inside each shuffle gave 0.8741. Both tests used the same observed score.

This is a research workflow with a paper watchlist at the end. The model can propose hypotheses and write code. Decide what counts as evidence before you let it start another run. Start with the reproducible example below, then apply the same validation rules to the historical data you have permission to use.

1. Configure Claude Code and give Python the calculations

Anthropic introduced Fable 5.2 on November 9, 2026. Standard Claude API pricing is $8 per million input tokens and $40 per million output tokens. Claude Code v2.1.321 or later supports the model. Medium is the default in Claude Code. Run a single bounded trial and log time, tokens, and retries before comparing High and Xhigh. FrontierCode 2.0 tests software tasks. The evidence you need for a backtest comes from your validation run. Anthropic launch · Claude Code model configuration · API pricing

2. Set up a research directory you can rerun

Binance publishes daily and monthly spot candles and archive checksums. Spot timestamps switch to microseconds on January 1, 2025. Normalize the unit before you join older and newer files. Log the date range, checksum, missing bars and duplicate rows. Binance public data notes

Paste the setup prompt into a session scoped to the research directory. A next-open simulation should compute signals from completed bars and apply costs to position changes. The short side in this example is hypothetical. Spot candle files supply prices, and simulated shorting needs separate borrowing, financing, and fill assumptions. Backtesting.py · vectorbt

Set up a crypto backtest lab in the current directory:

1. Create a Python virtual environment and install pandas, numpy, backtesting, vectorbt, pyarrow, and requests.
2. Fetch BTCUSDT and ETHUSDT spot 1-hour candles from data.binance.vision,
   from the earliest available month through last month. Save data/{symbol}_1h.parquet.
   Report gaps, duplicate rows, and missing hours.
3. Write engine.py with one public function:
   run(signal_fn, params, df, fee, slippage) -> dict
   - signal_fn returns a position for each bar: 1 long, -1 hypothetical short, 0 flat.
   - Use only data available through the current completed bar. Simulate execution at the next bar open.
   - Return per-bar returns, total return, profit factor, Sharpe ratio, maximum drawdown, and trade count.
4. Write a repeatable test. Run the same inputs 3 times and require identical output in all three runs.
5. Leave fee and slippage unset for me to supply.

Use actual engine.py output for every reported number. Give me the command that reproduces it.

Run the engine once with a fixed configuration. Check the time alignment and fee assumptions before giving the agent a grid to search.

Use engine.py with the BTCUSDT 1-hour data. Simulate a long position on an EMA 20/50 cross up and a short on a cross down.
Set the fee to [your fee] and slippage to [your slippage].
Print the table and point to the line of code that produced each figure.

3. Use four checks for four failure modes

  1. In sample. Fit on the first four years in this setup. Freeze the score, parameter grid and cost model. Inspect exceptionally smooth results for look-ahead.
  2. In-sample permutation. Generate 1,000 paths under a stated null. Run the same parameter search and score against every path.
  3. Walk forward. Fit using the preceding four years. Freeze the fit for the next 30 days and repeat. Combine scores from the held-out windows.
  4. Walk-forward permutation. Keep the initial training prefix fixed. Resample the subsequent path under the chosen null. Redo every training and evaluation window on each simulated path.

Four checks in order from in-sample testing to forward permutation

Shuffling individual returns assumes exchangeability under the null. The shuffle can erase time dependence, including volatility clustering. With dependent data, justify a suitable null and run the same search under that design. Log each hypothesis you tried. A holdout becomes part of your selection process if you inspect it repeatedly and use it to decide what to try next. The Probability of Backtest Overfitting

The example below records cutoffs as workflow settings. A cluster of similar scores across neighboring parameters is worth investigating. A single sharp peak gives you a specific sensitivity check.

One year of walk-forward data: require p < 5%.
Two years or more of walk-forward data: require p < 1%.

4. Run the same parameter search on the shuffled paths

The permutation_demo.py example uses 300 synthetic returns and 16 candidate configurations. Each signal uses returns from before the bar it scores. The toy score subtracts a fixed turnover fee. It uses synthetic data throughout. Save the code under the same filename.

import numpy as np

WINDOWS = (2, 3, 5, 8, 13, 21, 34, 55)
FEE = 0.0005
DRAWS = 1000


def equity_scores(returns):
    cumulative = np.r_[0.0, np.cumsum(returns)]
    timeline = np.arange(55, len(returns))
    signals = np.array([
        np.sign(cumulative[timeline] - cumulative[timeline - window])
        for window in WINDOWS
    ])
    positions = np.concatenate((signals, -signals), axis=0)
    turnover = np.abs(np.diff(positions, axis=1, prepend=0))
    return (positions * returns[timeline] - FEE * turnover).sum(axis=1)


def p_value(null, observed):
    return (1 + np.count_nonzero(null >= observed)) / (len(null) + 1)


rng = np.random.default_rng(20261201)
returns = rng.normal(0, 0.008, 300)
real_scores = equity_scores(returns)
selected = int(np.argmax(real_scores))
observed = real_scores[selected]
null_scores = np.array([
    equity_scores(rng.permutation(returns)) for _ in range(DRAWS)
])
frozen = p_value(null_scores[:, selected], observed)
refitted = p_value(null_scores.max(axis=1), observed)
assert refitted >= frozen
print(f"candidates={len(real_scores)} draws={DRAWS}")
print(f"frozen p={frozen:.4f} refitted p={refitted:.4f}")
uv run --no-project --with numpy==2.2.6 python permutation_demo.py

Shuffled returns are scored with the same parameter search

The output is frozen p=0.1518 refitted p=0.8741. The frozen score is a diagnostic for one already-selected winner. It leaves out selection. The refitted test gives each shuffled path the same opportunity to select. Each path's maximum includes the frozen candidate, so the paired p-value can only stay the same or rise. The one-sided calculation uses (r + 1) / (B + 1), where r counts simulated scores at least as high as the observed one. SciPy permutation test

5. Put the rules, experiments and report in separate files

Save the research protocol as FACTORY_RULES.md and have Claude Code read it before each run. Give each run a candidate budget, a time limit and a place to log incomplete work. The rule file keeps the source setup's thresholds and records both the raw exceedance count and the plus-one p-value.

# Research rules to read at the start of every run

## Role
You conduct research and paper simulations. Do not connect to exchange order interfaces or read API keys.

## Division of work
- Propose hypotheses, write signal functions, plan the search, and classify the results.
- Use engine.py for every number. Cite the script and command that produced it.

## Data
- Use only the public Binance candles under data/.
- Use the first 4 years in sample. Reserve later data for gates 3 and 4. Evaluate each idea out of sample at most once and record that run.

## Four gates, in order. Stop on the first failure.
1. In sample: reject mediocre results. Investigate implausibly smooth curves for look-ahead and reject unexplained results.
2. Permutation: generate 1000 paths from shuffled relative bar returns. Refit each path with the same search.
   Record the at-least-as-extreme count, raw fraction and plus-one p-value. Reject p >= 1%.
3. Walk forward: fit on 4 years, simulate the next 30 days, and roll forward. Reject results that miss the preregistered minimum after fee and slippage.
4. Forward permutation: shuffle data only after the first training window, then rerun all walk-forward windows.
   Require p < 5% for 1 year of forward data and p < 1% for 2 years or more.

## Sensitivity
Export a parameter heatmap for each tuning run. Reject a single winning point if its neighbors deteriorate sharply.

## Log
- Write one row per hypothesis in research_log.csv: date, idea, rationale, grid, gate results, p-values, status, and reason.
- Keep rejected ideas in the log and flag uncertainty. Do not rename rejected ideas to retest them.

## Progression
A pass at every gate earns a place on the paper watchlist. Leave the decision about live execution to a human.
Read FACTORY_RULES.md and research_log.csv.
Propose 10 new BTC/ETH research hypotheses. For each, give:
1. The market behavior and possible counterparty behind it, such as a reversal after high funding, thinner weekend liquidity, or breakout follow-through.
2. The conditions where the hypothesis should fail.
3. The basic signal function, number of parameters, and search range for each.
Exclude ideas without a rationale and ideas already rejected in the log.
Rank the hypotheses by the quality of the rationale. Send the top 3 to gate 1.
Run the gate 2 permutation test for [hypothesis name]:
- Use the in-sample BTCUSDT 1-hour data.
- Preserve the initial and terminal price. Shuffle relative bar returns and carry each bar's open-high-low-close relationship with it.
- Generate 1000 paths and repeat the same parameter search on each path.
- Parallelize with vectorbt. Fix the random seed and record it.
Report the observed score, null distribution, p-value, and result.
Write results to research_log.csv and figures to reports/.
Every day at 8 a.m. Beijing time (UTC+8), write a research report to reports/YYYY-MM-DD.md:
1. How many ideas ran overnight, which gate rejected each one, and why.
2. Survivors: scores at each gate, p-values, and paths to parameter heatmaps.
3. Whether paper watchlist results remain within the earlier expected range.
4. Which ideas to test next and why.
Leave buy or sell advice out. Identify the source script for every number.

6. Keep the paper watchlist under review

A paper run can reveal missing data, signal delays and unrealistic fill assumptions. Save the current specification and observation window before rerunning tests on newer data each Sunday. Log new observations as monitoring evidence. Earlier windows remain part of the existing research record. Give the researcher a clear way to send a result back for review.

Read the paper watchlist entries in research_log.csv.
Rerun the walk-forward permutation test for each idea using data through yesterday.
Flag any idea with a rising p-value or a clear gap between paper behavior and the backtest expectation. Record the reason.
Keep the registered strategy definition and parameter grid unchanged. Refit inside each training window and each shuffled path as specified. Do not change the rules to make a result pass.

FAQ

Does a p-value of 20% mean a strategy has a 20% chance of being luck?

A p-value estimates the frequency of scores at least as extreme as the observed one under a specified null. The probability that a strategy is due to luck is a different quantity.

Can I tune again on the same out-of-sample windows?

An out-of-sample window becomes part of selection if its results influence the next revision. Reserve fresh data or choose a nested evaluation design before iterating.

Sources

About the author

  • Crafting seamless user experiences with a passion for headless CMS, Vercel deployments, and Cloudflare optimization. I'm a Full Stack Developer with expertise in building modern web applications that are blazing fast, secure, and scalable. Let's connect and discuss how I can help you elevate your next project!

No comments yet. Be the first to comment.

More from this blog