Last updated: 2025-10-19

KA Evaluation View — Explorer Documentation

This guide explains how the KA Candidate Detail page is assembled, what each metric represents, and how to trace entries/exits back to the stored evaluation payload.

← Back to KA index · Open example view

1. Page Purpose

The view is a diagnostic tool for pattern evaluations produced by ka_evaluation.py. Every card summarises a slice of the simulation_json payload stored in ka_pattern_candidates. Use it to:

2. Data Flow Overview

  1. Evaluation loop (ka_evaluation.py::runner) picks a trading pair, pulls candles, and generates synthetic pattern candidates.
  2. Simulation payload (_simulate_four_candle_strategy) scans the dataset for qualifying windows, builds trade history, and assembles entry_context/exit_context summaries.
  3. Storage (KaEvaluationStorage.persist_results) serialises the dataclasses via dataclasses.asdict into the simulation_json column.
  4. View (ka_view.php) retrieves the row by id or candidate_id, decodes JSON fields, and renders the cards and charts.

Prototype pattern logic

  • Window size: four consecutive candles (pattern_window_size).
  • Long trigger: each close is lower than the previous one, the total drop exceeds drop_threshold_pct, and the last candle closes green. Opens a long trade at the close of the fourth candle.
  • Short trigger: mirrored rules — four higher closes, total rise above rise_threshold_pct, last candle closes red.
  • Exit rule: wait for the opposite signal or, if configured, cap exposure at max_hold_bars candles. Any open position is force-closed at dataset end.
  • Returns: each trade subtracts two commissions (entry + exit). Aggregate performance is short_term_return.
  • Persistence filter: simulations with no trades or non-positive total return are discarded and never stored, so every candidate in the UI represents at least one profitable pattern sequence.
  • Context candles: the detail view shows both context_candles_before and context_candles_after so you can inspect price action leading into the pattern and the immediate aftermath after the last trade closes.
Tip: Because all rationale lives inside simulation_json, historical rows generated before April 2025 will show “—” for the entry/exit explanation cards. Re-run the evaluator if you want the richer context for older candidates.

3. Key Payload Fields

The table below maps the main JSON keys to the UI components:

JSON path Type Description & UI usage
simulation_json.short_term_return float Displayed as “Pattern return” in the Overview stat cards and multiplied by trade_size for P&L.
simulation_json.long_return, short_return float Baseline comparisons, shown both in the Overview cards and in the Scenario table.
simulation_json.window_candles array High/low/open/close data for the highlighted window; drawn as the candlestick chart with context bars.
simulation_json.entry_context object New in this revision. Carries entry summary, notes, orientation bias, and baseline edges. Rendered as “Entry rationale”.
simulation_json.exit_context object Lists why the synthetic trade closed (currently always “window_end”) and how future windows behaved. Rendered as “Exit rationale”.
simulation_json.comparison array One element per forward projection window, each containing long_return, short_return, price_return, and timestamps. Drives the Forward Projections table and chart series.
metadata_json.window_size int Window length in candles, surfaced in the Overview → “Window length” fact.
reasoning_json.short_term_return float Legacy reasoning bundle kept for compatibility. Not required for the new rationale blocks.

4. Entry & Exit Contexts

Entry context (entry_context)

  • trigger: currently window_start because the stub enters at the first candle. Reserve for future triggers.
  • orientation: long, short, or flat based on the sign of pattern_return.
  • summary: Sentence combining entry rule, pattern vs baseline returns.
  • notes: Bullet list including edges vs long/short baselines and synthetic trade count.
  • baselines: Raw numeric snapshot (pattern/long/short) kept for downstream use.

Exit context (exit_context)

  • trigger: window_end — evaluation always closes at last candle.
  • summary: Explains close timing, projection positivity counts, and the window outcome.
  • notes: Underlying price move and averaged projection returns when available.
  • projections: Aggregated counts and averages used to populate the Forward Projections fact cards.
Roadmap: When the discovery engine evolves beyond the stub, replace the hardcoded entry/exit triggers and enrich notes with the actual rules that caused trades to fire.

5. Manual Trade Replay Guide

You do not need local Python access to repeat a candidate’s trade. Everything required is on the KA view. Follow this checklist with the trading/charting software you prefer:

  1. Capture the inputs. Note the Trading pair, Interval, Entry/Exit time, Entry/Exit price, and trade size shown under “Window & Trade”. Download the raw payload if you want exact candles.
  2. Set the timeframe. In your platform pick the same interval (e.g., 1m, 5m). Convert the timestamps from the view (UTC) into your platform’s timezone before marking the candles.
  3. Mark the window. Highlight the candle range using window_size and the recorded start time. This ensures indicators or overlays use the same slice as the evaluator.
  4. Recreate the trade. Use the orientation from the Entry rationale: open a synthetic position at Entry price on the first candle of the window, and exit at Exit price when the final candle closes. The baseline returns/cards let you compare to buy-and-hold benchmarks.
  5. Match overlays. On the chart, the shaded green/red bands highlight each executed trade while the circles with callout bubbles explain the entry/exit rationale—mirror these candles in your platform to verify the sequence.
  6. Apply position sizing. Multiply the percentage return by the documented trade_size (or your own notional) to compute cash P&L. The Scenario table shows the calculations the UI performs.
  7. Review projections. Use the Forward Projections table to see how price behaved after the exit. You can optionally run paper trades on those future windows using the same methodology.
  8. Document findings. Record whether the recreated trade matches the evaluator’s percentages. If you adjusted rules, jot them down for repeatability.
Reminder: Entry/exit times are UNIX seconds. Most charting packages accept UTC timestamps directly; otherwise convert with your platform’s time-zone tools before plotting.

6. Chart & Returns Panel

Performance chart

Returns projection (dotted chart)

7. Interpreting the Fact Grids

Overview

Shows headline returns and metadata. Values are formatted with helper functions format_percent, format_money, and trend_class.

Window & Trade

Aggregates entry/exit timestamps, prices, duration, trade size, and triggers. Rationale blocks render only when summaries are present.

Forward Projections

Fact grid uses projectionFacts derived from exit_context.projections plus raw counts for long/short/price windows.

Metadata Highlights

Displays score and timestamps directly from the table row. If metadata_json contains extra keys, they are listed in a table beneath.

8. Adding Your Own Signals

  1. Extend PatternSimulation with new fields (e.g., indicator_snapshots).
  2. Populate them in _simulate_pattern and ensure they serialise cleanly.
  3. Expose the data in ka_view.php by updating the decoded arrays/fact grids.
  4. Document the meaning in this file so analysts can interpret the new metrics quickly.

Because storage uses JSON longtext, you can evolve the schema without database migrations, but keep an eye on payload size (MySQL limit ≈ 4 GB — practically, keep below a few megabytes per row).

9. FAQ

Why is the candidate ID a four-digit number?

The stub generator uses PATTERN-{random.randint(1000, 9999)} purely as a label. It does not encode significance or rank.

Where do the entry/exit notes come from?

They are currently derived from baseline returns inside _build_entry_context / _build_exit_context. Replace those helpers when real pattern logic is available.

Do I need to migrate the database?

No. Additional context lives inside the JSON payload, so existing schema is fine.

How can I export the raw JSON?

Use the “Raw Payloads” accordions at the bottom of the detail page or query the MySQL table directly.

10. Troubleshooting Checklist