Compare commits
39
Commits
5667e96c40
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
54776d5647 | ||
|
|
5b8a10c730 | ||
|
|
2b7a065ae5 | ||
|
|
4c32e2b737 | ||
|
|
576d9e31ec | ||
|
|
be6a92540c | ||
|
|
053b94b45f | ||
|
|
de5dd29217 | ||
|
|
3010ab287f | ||
|
|
7f175e5a05 | ||
|
|
51400f20c7 | ||
|
|
12b34929d7 | ||
|
|
da671a9ba2 | ||
|
|
ead9aeb25c | ||
|
|
dbb787c50a | ||
|
|
9516a7a8e8 | ||
|
|
fcc0da9c8d | ||
|
|
7a3cfac19a | ||
|
|
b1c8a91ed6 | ||
|
|
ffad4dfd8d | ||
|
|
a17a8f3cc4 | ||
|
|
14b2aeff7c | ||
|
|
105ab86bf6 | ||
|
|
1fb1e1a027 | ||
|
|
17158742b7 | ||
|
|
a69fd884e7 | ||
|
|
91c63ae673 | ||
|
|
d73a58b3d1 | ||
|
|
c87767cfe5 | ||
|
|
64590156f1 | ||
|
|
71b893ee73 | ||
|
|
dc057e9aeb | ||
|
|
6439e9ce73 | ||
|
|
68f2cc1477 | ||
|
|
a7daf333b2 | ||
|
|
f9b8cd10b2 | ||
|
|
f3fad16183 | ||
|
|
28c111234e | ||
|
|
03195dc55d |
No files matched your search
@@ -0,0 +1,14 @@
|
||||
.git
|
||||
.venv
|
||||
.hermes
|
||||
__pycache__
|
||||
*.pyc
|
||||
.pytest_cache
|
||||
backend/.pytest_cache
|
||||
backend/data
|
||||
backend/.venv
|
||||
frontend/node_modules
|
||||
reports
|
||||
.DS_Store
|
||||
.env
|
||||
docs
|
||||
+2
-1
@@ -6,5 +6,6 @@ __pycache__/
|
||||
backend/.pytest_cache/
|
||||
backend/data/
|
||||
frontend/node_modules/
|
||||
frontend/dist/
|
||||
# note: frontend/dist/ is intentionally TRACKED (prebuilt static bundle used by
|
||||
# the Docker image — see Dockerfile). Rebuild with `cd frontend && npm run build`.
|
||||
reports/
|
||||
@@ -0,0 +1,150 @@
|
||||
# Multi-Theme + Simulation Implementation Plan — REVISION 2
|
||||
|
||||
> **For Hermes:** Execute task-by-task with `todo` tracking and per-task commits. TDD for all logic; visual verification for UI/CSS.
|
||||
|
||||
**Goal:** Rebuild the single-theme tourism demo into a **multi-theme research platform** with (a) a combined dashboard (all themes + stock recommendation table), (b) per-theme detail pages, (c) a **capital allocation simulation** (same engine used for both backtest and forward test), and (d) an MT5 order interface (forward test sends dry-run orders; live gate kept off in this round). UI in **Thai** (technical terms stay English). Uses **real data + daily cache**, not mocks.
|
||||
|
||||
**Themes (3 alternative factors):**
|
||||
1. `tourism` — Tourism Pulse (signal exists, real BOT data path)
|
||||
2. `auto_credit` — Auto Credit Cycle (registry slot; data pipeline needs a real source before it can score)
|
||||
3. `refining_energy` — Refining / Energy Spread (registry slot; data pipeline TBD)
|
||||
|
||||
**Siamchart** is treated as a **fundamental data provider**, not a theme. It supplies PE/EPS/Yield/P/BV/ROE per symbol and contributes to the combined score with a **lower weight**.
|
||||
|
||||
---
|
||||
|
||||
## Confirmed requirements (from user, 2026-08-25)
|
||||
|
||||
1. **3 themes = 3 alternative factors** (tourism, auto_credit, refining_energy). A symbol can appear in multiple themes.
|
||||
2. **Score combining:** each symbol has a *theme score* (average across all themes that score it) and a *siamchart score*. Combined = **theme_score × 60% + siamchart_score × 40%**.
|
||||
3. **8-symbol live data** is OK for testing logic; production must cover the full universe (collectors must be scalable, not hard-coded to 8).
|
||||
4. **"ไม่จ่ายปันผล" (bucket 2)** = a high-score stock that does **not** pay a dividend (is_dividend = False / yield ≤ 0).
|
||||
5. **Paper ledger is replaced** by a forward test that reuses the **same simulation engine as backtest** — the only difference is real MT5 order dispatch. We build the MT5 order interface; live dispatch remains gated off (forward/dry-run in this round).
|
||||
6. **Data quality / provenance = real sources, cached daily** — not fixture mocks. Provenance shows where each alternative factor comes from.
|
||||
7. **Signal board + Stock board = ONE table**, signal-focused.
|
||||
8. **UI language = Thai** (technical terms English).
|
||||
9. **Remove unused/unnecessary dashboard sections.**
|
||||
|
||||
---
|
||||
|
||||
# PART A — Multi-Theme Backend
|
||||
|
||||
## Task A1: Theme registry
|
||||
**Files:** create `backend/app/themes.py`; create `backend/tests/test_themes.py`
|
||||
|
||||
Registry with 3 theme slots + their factor provider. `list_themes()` returns them. Registry is pluggable so a theme can be `enabled=False` while its data pipeline is absent.
|
||||
|
||||
## Task A2: Combined signal aggregation
|
||||
**Files:** modify `backend/app/themes.py`, `backend/app/__init__.py`; tests
|
||||
|
||||
`/api/v1/dashboard` returns:
|
||||
- Per-symbol `theme_score` = mean of enabled themes that score it
|
||||
- `siamchart_score` (normalized)
|
||||
- `combined_score = 0.6 * theme_score + 0.4 * siamchart_score`
|
||||
- `side` (LONG/SHORT/NEUTRAL) from combined
|
||||
- per-theme contributions
|
||||
|
||||
Normalization: each provider's raw score is z-scored (or min-max over the live universe) before combining, so weights are meaningful across heterogeneous scales.
|
||||
|
||||
## Task A3: Per-theme detail endpoint
|
||||
`/api/v1/themes/<id>` — 404 unknown; returns that theme's observations/surprise/signals/lineage. Also exposes `/api/v1/themes` (registry incl. enabled status + data source).
|
||||
|
||||
## Task A4: Daily cache layer (real data, no mocks)
|
||||
**Files:** create `backend/app/daily_cache.py`; tests
|
||||
|
||||
Fetch-once-then-cache daily:
|
||||
- Keyed by `(source, as_of)`.
|
||||
- TTL ~24h; stale-if-error fallback to last good cache.
|
||||
- Ensures tourism + siamchart reads hit cache instead of re-fetching every dashboard load, and sets up the "update daily" cadence the user wants.
|
||||
|
||||
---
|
||||
|
||||
# PART B — Simulation / Backtest / Forward-Test Engine
|
||||
|
||||
## Task B1: Price-series loader
|
||||
**Files:** create `backend/app/simulation.py`; tests
|
||||
|
||||
Load Yahoo price snapshot `series[SYM].bars` → `{date: adjusted_close}` for all symbols. Covers 2024-01-03 → 2026-08-24.
|
||||
|
||||
## Task B2: Capital allocation core (`allocate_capital`)
|
||||
**Files:** `backend/app/simulation.py` + tests
|
||||
|
||||
Given `capital`, per-symbol `combined_score`, `is_dividend`, `dividend_yield`, latest `price`:
|
||||
- **Bucket 1 (50%)** — highest combined_score among **dividend-paying** names.
|
||||
- **Bucket 2 (20%)** — highest combined_score among **non-dividend** names.
|
||||
- **Bucket 3 (30%)** — highest **dividend yield** among names **not already bought in bucket 1** (ignores score).
|
||||
|
||||
Per symbol: **minimum 100 shares**. Rank by combined_score desc. If a bucket's first pick can't afford 100 shares, try progressively cheaper eligible names (that still pass the bucket's criteria). If no eligible name fits, leave remainder as cash.
|
||||
- Allocation math: `qty = max(100, floor(available_cash / price / 100) * 100)` within bucket cash.
|
||||
- Overflow flows bucket → bucket → cash.
|
||||
|
||||
## Task B3: Simulation endpoint + forward-test mode
|
||||
**Files:** `backend/app/__init__.py`; tests
|
||||
|
||||
- `POST /api/v1/simulation` `{capital}` → allocation plan (per-bucket orders, qty, notional, total, unallocated cash, data caveat: revised history not PIT).
|
||||
- `POST /api/v1/simulation/forward` — same engine, but marks orders `execution=paper` and, if an MT5 bridge is configured, would dispatch. **Live dispatch gated off** (env `MT5_ENABLE_ORDER` must be set AND explicit approval).
|
||||
|
||||
## Task B4: MT5 order interface (interface only, live gated)
|
||||
**Files:** create `backend/app/mt5_bridge.py`; tests (mock `MetaTrader5` per `mt5-data-service` skill gotcha)
|
||||
|
||||
Abstract `MT5Bridge` with: `connect`, `symbol_resolve`, `order_new` (dry-run default), and a structural kill switch — no real dispatch path in code unless `MT5_ENABLE_ORDER=1` AND explicit user approval. Follows the `mt5-data-service` / `mql5-ea-development` skill patterns (Windows-only `MetaTrader5` stub for tests).
|
||||
|
||||
---
|
||||
|
||||
# PART C — Frontend Multi-Theme UI (Thai, signal-first)
|
||||
|
||||
## Task C1: Route shell
|
||||
**Files:** `frontend/src/App.vue`, `style.css`
|
||||
|
||||
Hash-routing: `#/` (dashboard), `#/theme/:id`, `#/simulation`. Sidebar nav in Thai: แดชบอร์ด, ธีม, การจำลอง (Simulation).
|
||||
|
||||
## Task C2: Combined Dashboard (Thai)
|
||||
- Theme strip: each active theme's surprise/label.
|
||||
- **ONE stock table** (signal-first: combined score, side, theme contributions, then fundamentals PE/EPS/Yield/P/BV/ROE). Dividend filter + sortable columns kept. This **replaces** the separate Signal board + Stock board.
|
||||
- Remove unused sections (Paper Ledger card, live receiver text, etc.).
|
||||
|
||||
## Task C3: Theme detail page
|
||||
`#/theme/:id` — that theme's observations (surprise bars), provenance (source used), and its signal contribution table.
|
||||
|
||||
## Task C4: Simulation tab
|
||||
`#/simulation` — Thai UI: enter capital, choose backtest/forward, render 3 buckets with orders; show unallocated cash and the "revised history, paper-only" caveat.
|
||||
|
||||
## Task C5: Provenance (real data)
|
||||
Dashboard provenance section reads from live cache metadata: source id, retrieved_at (daily cache), raw hash. No fixture labels.
|
||||
|
||||
---
|
||||
|
||||
# Data requirements / open items (NOT guessed)
|
||||
|
||||
- **auto_credit data source**: needs a real public/paid source for vehicle sales, auto loan growth, auto NPL. Not yet identified. `auto_credit` theme stays in registry as `enabled=False` until a source + collector exist.
|
||||
- **refining_energy data source**: crack/GRM spread or Thai refining/energy stats. Not yet identified. `enabled=False` until built.
|
||||
- **Full SET50 universe prices**: Yahoo history currently covers 8 symbols; production simulation needs price history for the full universe. Requires extending the price collector to all symbols (scrape/SETSMART/MT5).
|
||||
|
||||
The three-theme registry is the *interface*; this round builds tourism + siamchart fully (real, cached) and stubs auto/energy until their data exists. Simulation works on whatever real symbols have both a price series and a score.
|
||||
|
||||
---
|
||||
|
||||
# Verification
|
||||
|
||||
1. Full backend suite (`-W error unittest discover`) all pass (existing 140 + new).
|
||||
2. `cd frontend && npm run build` success.
|
||||
3. Browser (Thai): dashboard lists themes (enabled + disabled), combined signal-first table with dividend filter + sort, simulation returns allocation, per-theme detail works.
|
||||
4. `git diff --check`, static scan clean, independent fail-closed code review.
|
||||
5. Per-task commits.
|
||||
|
||||
---
|
||||
|
||||
# Closed/open per user's 10 points
|
||||
|
||||
| # | User requirement | Status in plan |
|
||||
|---|---|---|
|
||||
| 1 | 3 themes (tourism, auto, energy) | Registry + tourism live; auto/energy `enabled=False` pending data source |
|
||||
| 2 | combined = 60% theme + 40% siamchart | A2 |
|
||||
| 3 | 8-symbol OK for logic, prod full | Simulation scales to any symbol with price+score |
|
||||
| 4 | bucket2 = high score, no dividend | B2 |
|
||||
| 5 | paper→forward test = same engine; MT5 iface | B3, B4 |
|
||||
| 6 | real data + daily cache, provenance real | A4, C5 |
|
||||
| 7 | one signal-first table | C2 |
|
||||
| 8 | Thai UI | C1–C4 |
|
||||
| 9 | remove unused | C2 |
|
||||
| 10 | (mt5 scope) interface built, live gated | B4 |
|
||||
@@ -0,0 +1,203 @@
|
||||
# Multi-Theme Dashboard + Capital Simulation Engine Implementation Plan
|
||||
|
||||
> **For Hermes:** Execute task-by-task. Use `todo` progress tracking and per-task commits. TDD for logic, visual verification for UI/CSS.
|
||||
|
||||
**Goal:** Turn the current single-theme (tourism) demo into a **multi-theme dashboard** (combined overview page + per-theme detail pages) plus a **separate Simulation tab** that runs capital allocation (50/20/30) ranked by signal score, using the existing Siamchart fundamental snapshot and the existing Yahoo price history (2024-01-03 → 2026-08-24).
|
||||
|
||||
**Architecture:** A theme registry that each alternative factor registers into (tourism, siamchart-fundamental). The dashboard combines all themes' signals into a recommendation; each theme has its own detail page. The simulation engine consumes the combined signal scores + 2.5yr price history + dividend yields to allocate a user-entered capital across three buckets (min 100 shares/share).
|
||||
|
||||
**Tech Stack:** Existing Flask backend (`backend/app/`), Vite+Vue frontend (`frontend/src/`). New modules `backend/app/themes.py`, `backend/app/simulation.py`. New route `/api/v1/simulation`. Frontend route-based dashboard (`#/`, `#/theme/:id`, `#/simulation`).
|
||||
|
||||
---
|
||||
|
||||
## Current-state findings (from exploration)
|
||||
|
||||
- **Themes today:** `tourism` signal (`backend/app/tourism.py::compute_tourism_signal` → `{theme, theme_surprise, observations, signals, as_of}`) + `siamchart` factor view (`backend/app/siamchart_factors.py::build_factor_view` → per-symbol PE/EPS/Yield/P/BV/ROE/is_dividend).
|
||||
- **`/api/v1/factors`** already merges Siamchart fundamentals with tourism signal per symbol (added in `commit 8a6991b`).
|
||||
- **Price history EXISTS**: `backend/data/prices/snapshots/prices-yahoo-chart-2024-01-01-2026-08-24-a1cf5b3c2ecf.json` — `{benchmark_symbol: "SET50", series: {SYM: {bars: [{date, open, high, low, close, adjusted_close, volume}]}}}` covering 2024-01-03 → 2026-08-24 for 8 symbols (AOT, AWC, BEM, CPALL, CPN, CRC, MINT, PTT) + index_SET. ~1.3 MB per vintage.
|
||||
- **Fundamental snapshot**: `backend/data/siamchart/set50_master.json` — per-symbol EPS/PE/Yield%/is_dividend (49 symbols).
|
||||
- **Paper ledger** (`backend/app/paper.py`) is a manual record-a-fill tool — NOT the automated allocation we now build.
|
||||
|
||||
---
|
||||
|
||||
# PART A — Multi-Theme Backend Architecture
|
||||
|
||||
## Task A1: Create a theme registry
|
||||
|
||||
**Objective:** A single source enumerating all available themes and their factor/signal providers.
|
||||
|
||||
**Files:**
|
||||
- Create: `backend/app/themes.py`
|
||||
|
||||
**Step 1: Write test** → `backend/tests/test_themes.py`
|
||||
```python
|
||||
def test_registry_lists_themes():
|
||||
from app.themes import list_themes
|
||||
themes = list_themes()
|
||||
assert {"id": "tourism"} in themes
|
||||
assert {"id": "siamchart"} in themes
|
||||
```
|
||||
Run: `PYTHONPATH=backend .venv/bin/python -W error -m unittest tests.test_themes -v`
|
||||
Expected: FAIL (module missing).
|
||||
|
||||
**Step 2: Implement `themes.py`**
|
||||
```python
|
||||
THEMES = [
|
||||
{"id": "tourism", "label": "Tourism Pulse", "kind": "signal",
|
||||
"source": "bot_tourism", "provider": "compute_tourism_signal"},
|
||||
{"id": "siamchart", "label": "Siamchart Fundamentals", "kind": "fundamental",
|
||||
"source": "siamchart", "provider": "siamchart_factors"},
|
||||
]
|
||||
|
||||
def list_themes():
|
||||
return THEMES
|
||||
```
|
||||
**Step 3: rerun test** → PASS.
|
||||
|
||||
**Step 4: Commit:** `git add backend/app/themes.py backend/tests/test_themes.py && git commit -m "feat(backend): theme registry"`
|
||||
|
||||
---
|
||||
|
||||
## Task A2: Combined signal aggregation endpoint
|
||||
|
||||
**Objective:** `/api/v1/dashboard` returns an aggregate across all themes: per-symbol combined score (sum across themes that have a signal), side, the themes that fired, plus carousel info per theme.
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/__init__.py`
|
||||
- Create: `backend/tests/test_dashboard.py`
|
||||
|
||||
**Step 1: Test** — combined aggregation with a mock theme.
|
||||
**Step 2: Implement** an aggregate function in `themes.py` that consumes each theme's signals (tourism signals + siamchart scores) and combines per symbol.
|
||||
**Step 3: PASS + commit** `feat(backend): aggregated multi-theme dashboard endpoint`
|
||||
|
||||
---
|
||||
|
||||
## Task A3: Per-theme detail endpoint
|
||||
|
||||
**Objective:** `/api/v1/themes/<theme_id>` returns that theme's observations/surprise/signals for the detail page.
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/__init__.py`
|
||||
- Create: tests in `test_dashboard.py`
|
||||
|
||||
**Step:** route dispatch to the theme's provider; validate `theme_id` against registry; 404 unknown. PASS + commit.
|
||||
|
||||
---
|
||||
|
||||
# PART B — Simulation / Capital Allocation Engine
|
||||
|
||||
## Task B1: Price-history loader
|
||||
|
||||
**Objective:** Load the latest Yahoo price snapshot series for a symbol as date→adjusted_close.
|
||||
|
||||
**Files:**
|
||||
- Create: `backend/app/simulation.py`
|
||||
- Create: `backend/tests/test_simulation.py`
|
||||
|
||||
**Step 1: Test**
|
||||
```python
|
||||
def test_load_price_series(tmp_path):
|
||||
snap = {"benchmark_symbol":"SET50","series":{"PTT":{"bars":[
|
||||
{"date":"2024-01-03","adjusted_close":50.0},
|
||||
{"date":"2024-01-04","adjusted_close":51.0}]}}}
|
||||
# write temp snapshot, call loader
|
||||
series = load_price_series(snap, "PTT")
|
||||
assert series == {"2024-01-03":50.0,"2024-01-04":51.0}
|
||||
```
|
||||
**Step 2: Implement** `load_price_series(snapshot, symbol)` → `dict[date, adjusted_close]`; reject unknown symbol with `SimulationError`. PASS + commit `feat(backend): price series loader`.
|
||||
|
||||
---
|
||||
|
||||
## Task B2: Capital allocation core
|
||||
|
||||
**Objective:** Given capital, per-symbol signal score + is_dividend + dividend yield, allocate across three buckets:
|
||||
- **Bucket 1 (50%)**: highest signal score among **dividend-paying** names
|
||||
- **Bucket 2 (20%)**: highest signal score among **non-dividend** names (combine with leftover/overflow from bucket 1 shortfall)
|
||||
- **Bucket 3 (30%)**: highest dividend yield among names **not** already in bucket 1 (ignore profit)
|
||||
|
||||
Each bucket buys from its ranked list, **minimum 100 shares per symbol**, at latest price; leftover cash (from price-bucket rounding) flows to next bucket / stays unallocated.
|
||||
|
||||
**Files:** `backend/app/simulation.py`, `backend/tests/test_simulation.py`
|
||||
|
||||
**Step 1: Test** `test_allocate_buckets_basic` — small capital, verify 50/20/30 money split, min-100-share floor, ranking by score.
|
||||
**Step 2: Test edge:** insufficient capital for min 100 shares in a bucket → skip to next; no infinite loop.
|
||||
**Step 3: Implement** `allocate_capital(capital, factors, prices)` returning per-bucket orders + unallocated cash.
|
||||
**Step 4: PASS + commit** `feat(backend): capital allocation engine (50/20/30)`
|
||||
|
||||
---
|
||||
|
||||
## Task B3: Simulation endpoint
|
||||
|
||||
**Objective:** `POST /api/v1/simulation` takes `{capital}` and returns the allocation plan (per bucket, per-symbol qty/price/notional, total invested, unallocated).
|
||||
|
||||
**Files:** `backend/app/__init__.py`, tests.
|
||||
|
||||
**Step:** wire `allocate_capital` to the endpoint; validate capital>0 finite; 400 on bad input. PASS + commit `feat(backend): simulation endpoint`.
|
||||
|
||||
---
|
||||
|
||||
# PART C — Frontend Multi-Theme UI
|
||||
|
||||
## Task C1: Route-based shell (Dashboard + theme detail + simulation)
|
||||
|
||||
**Objective:** `App.vue` becomes route-aware (hash routing): `#/` dashboard, `#/theme/:id`, `#/simulation`. Sidebar nav splits into these.
|
||||
|
||||
**Files:** `frontend/src/App.vue`, `frontend/src/style.css`
|
||||
- Keep `Stock board`/`Signal board` semantics but restructure nav:
|
||||
- **Dashboard** (`#/`) — combined overview + stock recommendation
|
||||
- **Simulation** (`#/simulation`) — separate tab
|
||||
- **per-theme** (`#/theme/:id`) — theme detail
|
||||
- TDD skipped (visual); verify via dev server + browser.
|
||||
|
||||
**Verify:** `npm run build` passes; open dev server; nav switches views.
|
||||
|
||||
## Task C2: Combined Dashboard page
|
||||
|
||||
**Objective:** Overview aggregating all themes: theme surprise cards, combined stock recommendation table (with dividend filter + sortable columns — reuse existing logic), theme list with links.
|
||||
|
||||
**Files:** `frontend/src/App.vue`
|
||||
- Reuse `sortedFactorRows`/`dividendOnly`/`setSort` from current stock board.
|
||||
- Add theme-surprise strip + "combined" context.
|
||||
|
||||
## Task C3: Theme detail page
|
||||
|
||||
**Objective:** `#/theme/:id` shows that theme's observations (surprise bars), source lineage (provenance), and its own signal table.
|
||||
|
||||
**Files:** `frontend/src/App.vue`
|
||||
- Fetch `/api/v1/themes/:id`.
|
||||
|
||||
## Task C4: Simulation tab UI
|
||||
|
||||
**Objective:** `#/simulation` — input capital, POST `/api/v1/simulation`, render 3 buckets (each with the buy list, qty, notional; min-100 clarity), unallocated cash, and a note on the data limits (revised history, not PIT).
|
||||
|
||||
**Files:** `frontend/src/App.vue`, `style.css`
|
||||
- Verify via browser after wiring.
|
||||
|
||||
---
|
||||
|
||||
# Migration pitfalls this plan must respect (from `plan` skill)
|
||||
|
||||
- **Multi-theme wiring**: do not hardcode "tourism" prose; pull labels from `/api/v1/themes`.
|
||||
- **Simulation honesty**: clearly label output as a *paper/backtest* on **revised vendor history** (`point_in_time=false`) — never a validated PIT claim.
|
||||
- **Bucket edge cases**: min-100-share floor can leave a bucket with zero capital allocated → must flow to next bucket gracefully (tested).
|
||||
- **XSS**: all UI via Vue `{{ }}`, no `v-html`.
|
||||
- **Per-theme 404**: unknown theme_id must 404, not silently render empty.
|
||||
|
||||
---
|
||||
|
||||
# Verification (final)
|
||||
|
||||
1. `PYTHONPATH=backend .venv/bin/python -W error -m unittest discover -s backend/tests` → all OK (existing 140 + new).
|
||||
2. `cd frontend && npm run build` → success.
|
||||
3. Browser: dashboard lists themes; `#/simulation` with capital input returns an allocation table; dividend filter + sort still work.
|
||||
4. `git diff --check`, static scan (no secrets/eval/exec/pickle).
|
||||
5. Independent code review (fail-closed JSON) before commit + push.
|
||||
|
||||
---
|
||||
|
||||
# Open questions / assumptions (call out if wrong)
|
||||
|
||||
- **"Combined signal score"**: sum of normalized scores across themes that provide a signal for a symbol. If only one theme fires, its score is the combined score. (Assumed; the user said "signal score from factor combined".)
|
||||
- **Dividend filter for bucket 1 vs bucket 3**: bucket 1 = dividend-paying AND high score; bucket 3 = high dividend yield regardless of score, **excluding bucket-1 names**. User: "จ่ายเงินปันผลมากที่สุด (ไม่ซ้ำกับข้อ 1 และไม่สนเรื่องโอกาสทำกำไร)". Implemented as exclusion, not a forced different-name set.
|
||||
- **Prices**: only 8 symbols have Yahoo history (AOT, AWC, BEM, CPALL, CPN, CRC, MINT, PTT) — the simulation can only allocate among symbols with both a price series AND a factor score. Symbols without a price series are skipped with a warning.
|
||||
- **Min 100 shares** — quantity may exceed cash in bucket for high-priced names; we buy floor(available_cash / price / 100) * 100 shares, leftover flows onward.
|
||||
@@ -0,0 +1,68 @@
|
||||
# Dashboard Polish — Table UX, Per-Theme Narrative, Per-Symbol Analysis Page
|
||||
|
||||
> **For Hermes:** This plan covers the 7-point UX + analysis-transparency review. No code until user approves.
|
||||
|
||||
**Goal:** Make the stock table informative & sortable, explain each theme's analysis in narrative (not just a number), and give every symbol a dedicated detail view showing HOW the system analyzed it (weights, components, combined-score derivation) so the user can verify the analysis honours the agreed methodology.
|
||||
|
||||
---
|
||||
|
||||
## The 7 complaints → fix
|
||||
|
||||
| # | Complaint | Fix | Effort |
|
||||
|---|-----------|-----|--------|
|
||||
| 1 | Table header text เบียด/ไม่เต็มพื้นที่ | Full-width header, better line-height/whitespace | CSS |
|
||||
| 2 | "รวม" column ไม่ชัดว่าคืออะไร + เรียงไม่ได้ | Rename → **"คะแนนรวม"**; make it sortable; add tooltip "60% ธีม + 40% พื้นฐาน" | FE + sort |
|
||||
| 3 | ธีม กับ 05/บันทึกการวิเคราะห์ ซ้ำ | **Remove 05/บันทึกการวิเคราะห์** (theme panel already has thesis) | FE remove |
|
||||
| 4 | section-kicker ต้อง format เดียวกัน ("07 /" ออก) | Remove numeric prefixes → plain Thai kickers | FE |
|
||||
| 5 | Theme ต้องการคำอธิบาย/บรรยายผลวิเคราะห์ | Long-form narrative per theme (auto <th> hon 3) | BE + FE |
|
||||
| 6 | ตารางหุ้น ต้องมี column theme | Add "ธีม" column showing which theme(s) each symbol belongs to | FE |
|
||||
| 7 | แต่ละหุ้นต้องมี หน้า detail: คลิก แล้วเห็นการวิเคราะห์ทุกอย่าง ต่อหุ้น (ข้อมูล→น้ำหนัก→ที่มาคะแนนรวม) | New per-symbol endpoint + detail view (modal or page) | BE + FE |
|
||||
|
||||
---
|
||||
|
||||
## Backend tasks
|
||||
|
||||
### Task B7: Per-symbol analysis breakdown endpoint
|
||||
- `GET /api/v1/symbols/<symbol>` returns for one symbol:
|
||||
- `symbol`, `company_name`
|
||||
- `themes`: which theme(s) this symbol belongs to (from THEME_SYMBOLS) + each theme's factor reading + surprise contribution
|
||||
- `fundamentals`: PE, EPS, EPS YoY, dividend_yield, PBV, ROE (Siamchart)
|
||||
- `score_breakdown`:
|
||||
- `theme_score` = mean of the theme surprise scores covering this symbol (with per-theme lines)
|
||||
- `siamchart_score` = growth + yield*2, z-scored
|
||||
- `combined` = 0.6*theme_score + 0.4*siamchart_score (with the actual numbers, not just final)
|
||||
- `price`: latest close + date
|
||||
- Deterministic, reuses `themes.combine_score` logic per-symbol; NO new magic.
|
||||
|
||||
### Task B5: Long-form per-theme narrative
|
||||
- Add a `narrative` field to each theme read: 2-4 sentence Thai explanation of what the factor means, whether it's positive/negative, and what it implies for stocks in that group. Built deterministically from the factor reading + surprise sign (not hardcoded, not an LLM).
|
||||
|
||||
## Frontend tasks
|
||||
|
||||
### Task F1: Table header full-width (complaint 1)
|
||||
- Give `.stock-panel`/`.factor-table` a max-width-safe full-width layout, better padding/line-height so the subtitle + controls breathe.
|
||||
|
||||
### Task F2: Rename + sort "รวม" (complaint 2)
|
||||
- Header "รวม" → **"คะแนนรวม"** with a small `60/40` hint; add `combined` to the sortable keys (already have `setSort('combined')` — wire it to actually sort by combined score desc default).
|
||||
|
||||
### Task F3: Remove 05/บันทึกการวิเคราะห์ (complaint 3)
|
||||
- Delete the bottom-grid thesis section (superseded by theme panel narratives).
|
||||
|
||||
### Task F4: Uniform section-kicker (complaint 4)
|
||||
- Strip "07 /", "05 /" etc. → plain Thai kickers ("การจำลองการลงทุน", "ธีม", "ที่มาของข้อมูล", "ตารางหุ้น").
|
||||
|
||||
### Task F6: Add Theme column (complaint 6)
|
||||
- In stock table add a "ธีม" column: for each symbol show compact chips of the theme(s) it belongs to (e.g. "โรงกลั่น", "—" if none). Reuse `boardBySymbol` / THEME lookup.
|
||||
|
||||
### Task F7: Per-symbol detail view (complaint 7)
|
||||
- Clicking a symbol row opens a detail panel/modal showing the full `/api/v1/symbols/<symbol>` breakdown: themes + fundamentals + score components + how combined was derived (60/40). This is the transparent-analysis view.
|
||||
|
||||
---
|
||||
|
||||
## Verification
|
||||
- Backend: full suite passes; `GET /api/v1/symbols/AOT` returns full breakdown with correct combined derivation.
|
||||
- Frontend: `npm run build`; browser shows full-width table, "คะแนนรวม" sortable, theme column, no 05 section, uniform kickers, per-symbol modal works & shows derivation.
|
||||
- Screenshot evidence; push after user OK.
|
||||
|
||||
## Open questions
|
||||
None blocking — methodology is deterministic and already implemented in `themes.combine_score`; this plan surfaces it transparently rather than changing it.
|
||||
@@ -0,0 +1,99 @@
|
||||
# Dashboard Rebuild — Multi-theme + Real Thai Data
|
||||
|
||||
> **For Hermes:** Execute task-by-task, commit per task, verify with backend tests + browser. Plan mode — no code until user approves.
|
||||
|
||||
**Goal:** Rebuild the SET50 dashboard so it reflects REAL multi-theme Thai data (tourism + auto + energy + NPL), not the current tourism-only fixture, per the user's 10-point review.
|
||||
|
||||
**Architecture:** Replace the single-vertical `tourism_result`-driven dashboard with a multi-theme real-data source; add per-symbol theme exposure (multi-source factors PER theme); update all UI sections to read real data, Thai-only, and remove the 5 obsolete KPI cards + paper ledger.
|
||||
|
||||
---
|
||||
|
||||
## The 10 user complaints → fix
|
||||
|
||||
| # | Complaint | Root cause | Fix |
|
||||
|---|-----------|-----------|-----|
|
||||
| 1 | Theme Surprise ไม่เข้าใจ, ลบได้ | KPI card from tourism-only | **Remove** card |
|
||||
| 2 | สัญญาณที่ใช้งาน: ซื้อ 7 แต่โชว์ 8 | total=8 (incl neutral) mislabeled | Show long/short/neutral correctly, Thai |
|
||||
| 3 | สมุดบันทึก paper มีทำไม — ไม่มี paper trade แล้ว | legacy section | **Remove** (simulation replaces it) |
|
||||
| 4 | คุณภาพข้อมูล — ข้อมูลจริงรึยัง? | `TOURISM_SOURCE=fixture` default | **Switch to real BOT data**; show real source+as_of |
|
||||
| 5 | ประตู backtest (blocked) เอาออก | legacy gate | **Remove** card (research is exploratory/forward) |
|
||||
| 6 | แต่ละธีมควรดูหลายแหล่ง (ประชากร ฯลฯ) | 1 source/theme | **Add multi-source factors per theme** (see Data plan) |
|
||||
| 7 | ตารางหุ้น + ตารางสัญญาณ ควรรวมกัน | split | **Merge** into one combined table |
|
||||
| 8 | Theme surprise ไม่ครบ 3 ธีม | tourism-only | **3 theme surprise** (auto, energy, tourism) |
|
||||
| 9 | ที่มาข้อมูล ควรเป็นตาราง (แหล่ง+เวลา) | prose | **Table** of all sources + last fetched |
|
||||
| 10 | บันทึกการวิเคราะห์ มีแค่ 1 ธีม | tourism thesis | **Per-theme thesis** (3) + multi-source note |
|
||||
|
||||
**Overall:** "ข้อมูลทั้งหมดตอนนี้ยังไม่ได้ใช้ข้อมูลจริงใช่ไหม?" → ใช่, dashboard ใช้ `tourism_result` (fixture default). Rebuild to real.
|
||||
|
||||
---
|
||||
|
||||
## User-confirmed decisions (2026-08-25)
|
||||
1. **Real data ONLY** — switch to BOT real (no fixture fallback); dashboard fails if no real data.
|
||||
2. **Theme surprise = z-score** of each theme's headline factor (uniform across all themes).
|
||||
3. **Multi-source per theme (A+B)**: wire existing multi-source (auto = volume + NPL + production + export); AND add broader macro (population/GDP/inflation) — **found BOT SDDS page (bot.or.th/en/statistics/sdds.html) is server-rendered and scrapable WITHOUT auth**: provides GDP (Q2/2026 4,793.5bn), Private Consumption +4.9%, Private Investment +18.1%, Manufacturing −3.1%, Population 70,472k, Headline Inflation 1.95%, Unemployment 0.93%. This is the macro backdrop layer (complaint #6).
|
||||
|
||||
## Macro backdrop factor (new) — BOT SDDS collector
|
||||
- Create `backend/app/macro_thai.py` — scrape BOT SDDS HTML for: private consumption index %YoY, private investment %YoY, mfg production %YoY, population (thousands), headline inflation, core inflation, unemployment. Real Thai macro backdrop.
|
||||
- Wire into a "macro" theme/context read + into the sources table.
|
||||
|
||||
## Backend task list
|
||||
|
||||
### Task A: Real multi-theme dashboard source module
|
||||
- Create `backend/app/dashboard.py` — assembles REAL data from all collectors:
|
||||
- tourism (BOT real, via collector), auto_credit (Trading Econ + **auto_npl** BOT), energy (TOP), siamchart fundamentals, prices
|
||||
- Returns `{themes: [{id, name, frequency, read_* , surprise}], board: [{symbol, combined_score, dividend, ...}], sources: [{from, source, as_of, fetched_at}], thesis_per_theme: {...}}`
|
||||
- **Multi-source per theme (complaint #6):** registry mapping theme → list of factor sources (not 1). E.g. auto theme = {new_car_sales_yoy (TradingEcon), auto_npl_pct (BOT), vehicle_production, auto_exports}. Add aggregatable fields.
|
||||
- **3 theme surprise (#8):** compute surprise per theme (z-score of the theme's headline factor), not just tourism.
|
||||
|
||||
### Task B: Switch create_app to real data
|
||||
- `backend/app/__init__.py`: default `TOURISM_SOURCE` → `bot` (real), or better: build `multi_dashboard` from collectors at startup, keep tourism as one theme. `_load_default_snapshot` no longer the dashboard root.
|
||||
- `dashboard/summary`, `/signals`, `/factors` endpoints → read from `dashboard.py` real assembly, not `tourism_result`.
|
||||
|
||||
### Task C: Sources table endpoint
|
||||
- `dashboard.py` collects `sources` list: each {from (e.g. "TradingEconomics"), source, url, as_of, fetched_at, frequency}. Expose in `/api/v1/themes` + summary.
|
||||
|
||||
### Task D: Per-theme thesis (#10)
|
||||
- `dashboard.py` builds a short deterministic thesis per theme from that theme's factor readings (not a hardcoded tourism sentence).
|
||||
|
||||
## Frontend task list
|
||||
|
||||
### Task F: Remove 5 obsolete items (#1,#3,#5)
|
||||
- Delete cards: Theme Surprise (#1), คุณภาพข้อมูล (#4 replaced by honest sources), ประตู backtest (#5), สมุดบันทึก paper (#3) → card 2 (สัญญาณ) only + 3-theme panel.
|
||||
- Remove paper-ledger UI + backtest-gate UI blocks (already partially removed paper ledger; remove backtest KPI).
|
||||
|
||||
### Task G: Correct signal count (#2)
|
||||
- Show `long` / `short` / `neutral` as separate Thai chips; value = long only, with "+X ซื้อ −Y ขาย" clearly, no off-by-one.
|
||||
|
||||
### Task H: Merge stock + signal tables (#7)
|
||||
- Single combined table: [สีสัญญาณ, symbol, theme(s), combined_score, dividend, PE, EPS YoY, Yield, P/BV, ROE] — one table, sortable, dividend filter.
|
||||
|
||||
### Task I: Sources table UI (#9)
|
||||
- Render `sources` as a `<table>`: ตัวจาก, แหล่ง, ข้อมูล, as_of, fetched_at, frequency.
|
||||
|
||||
### Task J: 3-theme surprise + thesis (#8,#10)
|
||||
- Theme panel shows 3 themes, each with its own surprise + read + thesis.
|
||||
|
||||
### Task K: Thai-only consistency + visual verify
|
||||
- Audit all remaining English; keep only technical terms. Browser verify at 1440/1024/768. Screenshot for user.
|
||||
|
||||
---
|
||||
|
||||
## Multi-source factor registry (complaint #6) — where to add data
|
||||
For "แต่ละธีมดูข้อมูลรอบด้านของประเทศ" — extend themes to multiple Thai sources:
|
||||
- **Auto**: new_car_sales_yoy (TradingEcon) + auto_npl_pct (BOT) + vehicle_production + auto_exports (TradingEcon) [already in collector]
|
||||
- **Energy**: TOP net_profit/ebitda + Thai retail fuel/EPPO + (optional) import/refining
|
||||
- **Tourism**: BOT tourism surprise + arrivals + hotel occupancy
|
||||
- **Macro backdrop (new)**: Thai population / GDP (BOT API — needs auth, mark deferred) per user's "จำนวนประชากร"
|
||||
|
||||
**Note:** Full multi-source (population/GDP via BOT portal API) requires API key registration — mark as a separate later task; this plan wires the already-available multi-source readings per theme.
|
||||
|
||||
## Verification
|
||||
- Backend: full suite passes; live `/api/v1/themes` shows 3 themes with real Thai readings + sources table + per-theme thesis; no fixture.
|
||||
- Frontend: `npm run build`; browser shows combined single table, 3-theme surprise, sources table, no removed cards; Thai-only.
|
||||
- Screenshot evidence for user review before push (push gate).
|
||||
|
||||
## Open questions / risks
|
||||
1. **Real-vs-fixture default:** Should dashboard run on BOT real data by default (needs a fetch), or keep a cache so it works offline? → Recommend: real BOT via daily cache, fallback to last-good.
|
||||
2. **Population/GDP macro**: needs BOT portal API key (user registers). Defer unless user provides key.
|
||||
3. **Theme surprise definition**: need concrete per-theme surprise metric — z-score on each theme's headline factor (auto YoY, energy net profit trend, tourism surprise). Confirm with user if ambiguous.
|
||||
4. **Push gate**: after visual verify, user approves before push (per repo convention).
|
||||
@@ -0,0 +1,95 @@
|
||||
# Full-App Consistency Refactor — single source of truth + per-symbol selection
|
||||
|
||||
> **For Hermes:** Execute after user approval. Fixes two debts at once:
|
||||
> (a) theme mapping/data duplicated & diverged across backend/frontend;
|
||||
> (b) theme selection is FLAT — every symbol in a theme gets the same surprise
|
||||
> score, so there's no real "เลือกหุ้น" (which name benefits most within theme).
|
||||
|
||||
**Root problems:**
|
||||
1. Theme registry + labels live in 3 places that diverge (`themes.py` correct,
|
||||
`dashboard.py` maco-proxy, `__init__.py` old `/api/v1/themes` still 3 themes,
|
||||
`App.vue` hardcoded `THEME_BY_SYMBOL`/`themeLabelById`).
|
||||
2. **Selection is not real:** `_build_board` assigns the SAME `surprise` to every
|
||||
symbol in a theme (flat). A strong BBL vs weak TTB get identical theme score.
|
||||
The user wants each theme to *analyze and pick* — i.e. differentiate per-symbol
|
||||
quality/benefit within the theme.
|
||||
|
||||
---
|
||||
|
||||
## What "theme analyzes & selects stocks" means (per-theme pipeline)
|
||||
For EVERY theme, a symbol in that theme gets:
|
||||
theme_score_for_symbol =
|
||||
theme_surprise (macro/theme tailwind, common to all in theme)
|
||||
× firm_quality (per-symbol relative strength within the theme)
|
||||
|
||||
`firm_quality` is deterministic, derived from the symbol's own fundamentals
|
||||
relative to its THEME cohort (not the whole market), e.g.:
|
||||
- banks: ROE, NIM proxy (ROE/EPS), loan book health (EPS growth)
|
||||
- energy: PTT/TOP margins via ROE + yield
|
||||
- retail: margin/EPS growth
|
||||
- generic: ROE vs theme median, EPS growth vs theme median, dividend floor
|
||||
This way within a hot theme the *better-run* names rank higher → real stock picking.
|
||||
|
||||
We generalize the existing 60/40 so theme_score is no longer flat:
|
||||
combined = 0.6 * (theme_surprise × quality) + 0.4 * siamchart_score
|
||||
|
||||
---
|
||||
|
||||
## Refactor plan
|
||||
|
||||
### Backend
|
||||
**Task B0 — per-symbol theme quality (selection):**
|
||||
- Add `themes.quality_within_theme(symbol, theme_id, factor_view) -> float` that
|
||||
computes a symbol's relative quality within its theme cohort (ROE/EPS-growth vs
|
||||
theme median, dividend floor). deterministic, unit-testable.
|
||||
- In `dashboard._build_board`, when applying a theme surprise to a symbol, multiply
|
||||
by `quality_within_theme` so symbols in the same theme differentiate.
|
||||
- Expose `quality` + `theme_score breakdown` in `/api/v1/symbols/<x>` so it's transparent.
|
||||
|
||||
**Task B1 — single source of truth:**
|
||||
- `themes.py` add `theme_of(symbol)`, `label_of(theme)`, `quality_within_theme`.
|
||||
- `dashboard.build()` returns `symbol_theme_map` + board rows carry per-symbol `themes` + `theme_score`.
|
||||
|
||||
**Task B3 — remove old `/api/v1/themes` (3 themes, dup logic):**
|
||||
- Delegate to `RealDashboard.build()` so `/api/v1/themes` == `/api/v1/dashboard` theme set (13, same labels/surprises). Remove dup auto/energy sign code.
|
||||
|
||||
**Task B4 — single fetch path:**
|
||||
- RealDashboard.build() is the one place that fetches auto/energy/macro; endpoints + scheduler consume it (no dupe fetch).
|
||||
|
||||
### Frontend
|
||||
**Task F1 — delete hardcoded `THEME_BY_SYMBOL`/`themeLabelById`:**
|
||||
- theme column + modal come from `/api/v1/dashboard` (board[].themes, themes[].label_th) + `/api/v1/symbols/<x>` breakdown. No local map.
|
||||
|
||||
**Task F2 — modal shows per-symbol selection logic:**
|
||||
- Add to symbol view: the `quality` within each theme + how theme surprise × quality = theme score, so stock-picking is explainable.
|
||||
|
||||
### Tests
|
||||
- `test_themes`: quality_within_theme differentiates (strong vs weak name), unit.
|
||||
- `test_dashboard`/`test_api`: `/api/v1/themes` == `/api/v1/dashboard` theme set; board rows have per-symbol themes; two symbols in same theme get different theme_score when quality differs.
|
||||
|
||||
### Files
|
||||
- `backend/app/themes.py`, `backend/app/dashboard.py`, `backend/app/__init__.py`
|
||||
- `frontend/src/App.vue`
|
||||
- `backend/tests/test_themes.py`, `test_dashboard.py`, `test_api.py`
|
||||
|
||||
## Acceptance (definition of done)
|
||||
1. Two banks (BBL strong, TTB weak) get DIFFERENT theme score within banks theme — shows real stock selection, not flat.
|
||||
2. Editing themes.py propagates to `/api/v1/themes`, `/api/v1/dashboard`, `/api/v1/symbols`, frontend — no frontend change needed.
|
||||
3. `/api/v1/themes` == `/api/v1/dashboard` theme set (consistency test).
|
||||
4. Modal explains: theme surprise × firm quality = theme score per symbol.
|
||||
5. npm run build + full backend suite pass; browser shows BBL>TTB theme score when quality differs.
|
||||
|
||||
### Files
|
||||
- `backend/app/themes.py` (add theme_of/label_of helpers)
|
||||
- `backend/app/dashboard.py` (symbol_theme_map in build; board row.themes)
|
||||
- `backend/app/__init__.py` (themes endpoint → delegate; de-dup; board.themes)
|
||||
- `frontend/src/App.vue` (remove hardcode maps; derive from API)
|
||||
- `backend/tests/test_dashboard.py`, `backend/tests/test_api.py` (consistency tests)
|
||||
|
||||
## Acceptance (definition of done)
|
||||
1. Changing a theme in `themes.py` propagates to `/api/v1/themes`, `/api/v1/dashboard`, `/api/v1/symbols/<x>`, and the frontend column/modal — with NO change to frontend code.
|
||||
2. No duplicate theme mapping in frontend.
|
||||
3. `npm run build` + full backend suite pass; browser shows BBL=ธนาคาร from API.
|
||||
|
||||
## Open question / tradeoff
|
||||
- One cache/fetch per data refresh vs per-day: keep single `RealDashboard.build()` as the one fetch path (scheduler + endpoints both call it) so data is consistent within a cycle. Accept minor latency first call.
|
||||
@@ -0,0 +1,148 @@
|
||||
# Architecture Plan — Declarative Factor/Theme Analysis Engine
|
||||
|
||||
> Status: DRAFT — pending user approval (decision gate G0).
|
||||
> Author: Macky. Date: 2026-08-26.
|
||||
|
||||
## Goal
|
||||
Rebuild the scoring system so that **adding/removing a data source or factor is a config change, not an edit to scoring functions**. Every theme gets a full analyze-and-select pipeline built from registered, declarative factors. This makes the platform easy to extend as the user keeps finding new Thai data sources.
|
||||
|
||||
## Why this is needed (current debt)
|
||||
Today the analysis is **hardcoded**:
|
||||
- `dashboard._theme_surprises()` — per-theme surprise logic written inline (tourism special, auto NPL composite, energy TOP, then macro-proxy branches).
|
||||
- `dashboard._theme_narrative()` — per-theme narrative strings hardcoded.
|
||||
- `dashboard.build()` — proxy_reads dict hardcoded.
|
||||
- `App.vue` — `THEME_BY_SYMBOL` + `themeLabelById` hardcoded (duplicate of backend).
|
||||
- `__init__.py` — old `/api/v1/themes` still builds only 3 themes.
|
||||
|
||||
Every new source = editing functions and strings in 3+ places → exactly the "จุดนึงเสร็จ จุดอื่นไม่ตาม" problem.
|
||||
|
||||
## Target Architecture
|
||||
|
||||
```
|
||||
┌──────────────────────────────┐
|
||||
│ FACTOR REGISTRY (config) │
|
||||
┌──────────────────▶ (declarative, data-driven) │
|
||||
│ └──────────────────────────────┘
|
||||
│ reads reads
|
||||
▼ ▼
|
||||
┌───────────────┐ fetch/parse ┌──────────────────────┐
|
||||
│ COLLECTORS │─────────────▶ │ FACTOR PIPELINE │
|
||||
│ (per source) │ raw observable │ surprise / z-score / │
|
||||
└───────────────┘ │ frequency alignment │
|
||||
▲ └──────────────────────┘
|
||||
│ registry.fetcher │ per-factor value
|
||||
└──┘ ▼
|
||||
┌──────────────────────┐
|
||||
│ THEME SCORER │
|
||||
│ factors ✕ weights │
|
||||
│ ✕ firm_quality │
|
||||
└──────────────────────┘
|
||||
│ theme_score
|
||||
▼
|
||||
┌──────────────────────┐
|
||||
│ COMBINE (60/40) + │
|
||||
│ SELECT / board │
|
||||
└──────────────────────┘
|
||||
│
|
||||
▼
|
||||
/api/v1/themes, /api/v1/dashboard,
|
||||
/api/v1/symbols/<x>, frontend (read-only)
|
||||
```
|
||||
|
||||
## Key Decisions
|
||||
| Decision | Choice | Rationale | Alternatives |
|
||||
|---|---|---|---|
|
||||
| Factor = declarative unit | `FACTORS` registry: dict of `{key, source, fetch_fn, frequency, sign, weight, periods}` | add source = add one dict entry | hardcoded functions (rejected) |
|
||||
| Theme = composition of factors | `THEMES` registry: `{id, label_th, symbol_map, factors:[{factor_key, weight}]}` | theme reuses factors; new theme = add entry | inline per-theme logic (rejected) |
|
||||
| Source of truth | `themes.py`/`factors.py` registries (backend) | one place; frontend reads via API | App.vue hardcode (remove) |
|
||||
| Per-symbol selection | `quality_within_theme(symbol, theme, factor_view)` | differentiates strong vs weak within a theme | flat surprise (rejected) |
|
||||
| Frequency alignment | each factor carries `frequency`; scorer aligns by period (as-of semantics), never mixes timestamps | user's explicit requirement | naive mixing (rejected) |
|
||||
|
||||
## Decision Gates (one per milestone → user approves before code)
|
||||
|
||||
### G0 — Approve declarative registry design
|
||||
**Acceptance:** user approves FACTORS + THEMES registry schema & that adding a source = one config entry.
|
||||
**Exit:** proceed to B0.
|
||||
|
||||
### G1 — Per-symbol selection works
|
||||
**Acceptance:** two banks with different fundamentals get **different** theme_score within banks theme (BBL strong > TTB weak), unit-tested.
|
||||
**Exit:** proceed to frontend.
|
||||
|
||||
### G2 — Frontend no longer hardcodes themes
|
||||
**Acceptance:** edit `themes.py` (add theme/factor) → `/api/v1/themes`, `/api/v1/dashboard`, `/api/v1/symbols/<x>`, and the board column/modal all pick it up with zero frontend change.
|
||||
**Exit:** done.
|
||||
|
||||
## Data Model
|
||||
**FACTORS** (in `backend/app/factors.py`):
|
||||
```python
|
||||
FACTORS: dict[str, dict] = {
|
||||
"tourism_arrivals_yoy": {
|
||||
"name_th": "นักท่องเที่ยว",
|
||||
"source": "BOT", "frequency": "monthly",
|
||||
"fetch": "bot_tourism", # module name; returns dict with numeric value
|
||||
"value_key": "arrivals_yoy", # key of the numeric value
|
||||
"sign": 1, # +1 = higher is bullish for theme
|
||||
"weight": 1.0, # (themes can override)
|
||||
},
|
||||
"auto_sales_yoy": {"source":"TradingEconomics","frequency":"monthly","fetch":"auto_credit","value_key":"new_car_sales_yoy","sign":1},
|
||||
"auto_npl": {"source":"BOT","frequency":"quarterly","fetch":"auto_npl","value_key":"pct_of_npls","sign":-1},
|
||||
"energy_top_netmarg": {"source":"TOP","frequency":"quarterly","fetch":"energy_thai","value_key":"net_margin","sign":1},
|
||||
"macro_consumption": {"source":"BOT","frequency":"monthly","fetch":"macro_thai","value_key":"private_consumption_yoy","sign":1},
|
||||
"macro_investment": {"source":"BOT","frequency":"monthly","fetch":"macro_thai","value_key":"private_investment_yoy","sign":1},
|
||||
"macro_inflation": {"source":"BOT","frequency":"monthly","fetch":"macro_thai","value_key":"headline_inflation_yoy","sign":-1},
|
||||
"macro_mfg": {"source":"BOT","frequency":"monthly","fetch":"macro_thai","value_key":"manufacturing_yoy","sign":1},
|
||||
}
|
||||
```
|
||||
|
||||
**THEMES** (in `backend/app/themes.py` — keeps symbol_map + label):
|
||||
```python
|
||||
THEMES: dict[str, dict] = {
|
||||
"auto_credit": {
|
||||
"label_th": "รถยนต์/สินเชื่อ", "frequency": "monthly",
|
||||
"factors": [{"key":"auto_sales_yoy","weight":1.0},{"key":"auto_npl","weight":-0.5}],
|
||||
"symbols": {...},
|
||||
},
|
||||
"banks": {
|
||||
"label_th": "ธนาคาร", "frequency": "quarterly",
|
||||
"factors": [{"key":"macro_investment","weight":1.0},{"key":"macro_inflation","weight":-0.3}],
|
||||
"symbols": {...},
|
||||
},
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
**surprise per theme** = weighted, sign-aware blend of its factors (each factor z-scored / normalized per its frequency cohort → frequency-aligned, no naive mixing).
|
||||
|
||||
**theme_score per symbol** = theme_surprise × `quality_within_theme(symbol, theme, factor_view)`.
|
||||
|
||||
**combined** = 0.6 × theme_score + 0.4 × siamchart_score.
|
||||
|
||||
## Module Boundaries
|
||||
```
|
||||
factors.py — FACTORS registry + normalize/z-score helper (single source)
|
||||
themes.py — THEMES registry (symbol_map, labels, factor refs), quality_within_theme, theme_of, label_of, combine_score
|
||||
dashboard.py — orchestrator: fetch registered factors once, compute surprises, build board/macro/sources (no per-theme hardcode)
|
||||
collectors/ — bot_tourism, auto_credit, auto_npl, energy_thai, macro_thai (return dict, registered in FACTORS.fetch)
|
||||
__init__.py — endpoints only; /api/v1/themes delegates to dashboard.build(); /api/v1/symbols uses themes helpers
|
||||
App.vue — PURE read-only; theme column/labels/board from /api/v1/dashboard; NO hardcoded theme maps
|
||||
```
|
||||
|
||||
## Explicit Non-Goals (v1)
|
||||
- No live trading / MT5 execution (paper/backtest only, unchanged).
|
||||
- No new collectors yet — this refactor *enables* easy addition; sources are added as follow-up (user will name them).
|
||||
- No LLM involvement in scoring (deterministic only).
|
||||
- No changing the 60/40 or 50/20/30 business rules — only making them data-driven.
|
||||
|
||||
## Open Questions (for G0)
|
||||
1. Should factor weights live per-theme (override) or global? → proposal: per-theme override with global default (flexible).
|
||||
2. Do we keep the current 3 real collectors as the first factors registered (yes), and new sources added later by the user?
|
||||
|
||||
---
|
||||
|
||||
## Acceptance (definition of done — all gates pass)
|
||||
1. Adding a new factor = 1 dict entry in `FACTORS` + (optionally) a theme factor line — no scoring-function edit.
|
||||
2. `/api/v1/themes` == `/api/v1/dashboard` theme set (13, same labels/surprises) — consistency test.
|
||||
3. BBL vs TTB get different banks theme_score by quality — selection proof test.
|
||||
4. Frontend has NO hardcoded theme maps; column + modal label from API.
|
||||
5. Modal shows `theme surprise × firm quality = theme score` per symbol.
|
||||
6. `npm run build` + full backend suite pass; browser BBL > TTB when quality differs.
|
||||
@@ -0,0 +1,88 @@
|
||||
# Research + Data-Source + Simulation Backtest — plan (5-point)
|
||||
|
||||
> For Hermes: execute after user approval. This covers:
|
||||
> 1. Literature review → formula improvements
|
||||
> 2. New data sources per theme
|
||||
> 3. Frontend sources table = NOT mock, auto from backend FACTORS registry
|
||||
> 4. Simulation: real backtest engine w/ custom start/end date + P&L
|
||||
> 5. Sources table shows next-update column
|
||||
|
||||
## Findings (facts, verified)
|
||||
|
||||
**Sources table is hardcoded (point 3 true):** `dashboard._build_sources` returns a
|
||||
hardcoded 5-row list (TradingEconomics, BOT NPL, Thai Oil, BOT Economy, Tourism).
|
||||
It does NOT come from the FACTORS registry, so adding a factor does NOT add a source
|
||||
row automatically. Must wire sources from FACTORS registry (single source of truth).
|
||||
|
||||
**Simulation is NOT a real backtest (point 4 true):** `simulation.allocate_capital`
|
||||
allocates once at latest price. Both "backtest" and "forward" modes just differ in
|
||||
whether an MT5 order is sent. There is no start/end date, no rebalancing over time,
|
||||
no performance/P&L, and results are not persisted (vanish on refresh). This matches
|
||||
the user's confusion exactly — the two modes don't do what the labels imply.
|
||||
|
||||
**5 data sources today** (real): TradingEconomics (auto sales) · BOT NPL · Thai Oil
|
||||
(TOP quarterly) · BOT Thai Economy (macro) · BOT Tourism — all real, but hardcoded
|
||||
in the sources table.
|
||||
|
||||
---
|
||||
|
||||
## Work items
|
||||
|
||||
### 1. Literature / methodology research → formula improvements
|
||||
- Research: factor-based Thai-equity scoring, alternative-data alpha, market-regime
|
||||
timing, cross-frequency factor combination (mixed cadence). Deliver: a short
|
||||
recommendation doc with concrete refinements to the current formula
|
||||
(60/40, quality_within_theme, regime gate), grounded in citations.
|
||||
- Output: `docs/methodology-research.md`; proposals applied only after user OK.
|
||||
|
||||
### 2. Additional data sources per theme
|
||||
- Research & (where cheap/feasible) wire one new honest Thai source per theme:
|
||||
- banks → BOT commercial-bank loan growth / NPL (real, report already seen)
|
||||
- retail → consumer-comfort/retail index
|
||||
- utilities → BOT electricity demand proxy
|
||||
- telecom → subscriber data (if public)
|
||||
- property → BOT housing / transfer volume
|
||||
- Add as FACTORS registry entries (declarative — that's the whole point). Sources
|
||||
that need auth (BOT Portal API) are gated by user-provided key.
|
||||
|
||||
### 3. Sources table auto-derived (not mock, not hardcoded)
|
||||
- `dashboard._build_sources` → derive from FACTORS registry: iterate FACTORS,
|
||||
group by source module, emit {แหล่ง, ขอบเขต, data_value, as_of, fetched_at}.
|
||||
- Frontend sources table consumes `/api/v1/dashboard.sources` — so adding a FACTOR
|
||||
auto-appends its source row. No hardcoded list in backend or frontend.
|
||||
|
||||
### 4. Real backtest engine (replaces forward-only allocation)
|
||||
- New `backend/app/backtest.py`: takes {start_date, end_date, capital, bucket_weights,
|
||||
rebalance} and RUNS the allocation across time using the Yahoo price series:
|
||||
- at each rebalance date, recompute combined scores (theme+firm+quarterlies) on
|
||||
*point-in-time* basis (no future leak), allocate 50/20/30, track holdings.
|
||||
- mark-to-market daily; accrue dividends; end → report:
|
||||
`{capital, invested, final_value, price_pnl, dividend_income, net_return, win_rate, trades}`
|
||||
- Backtest section in UI: pick start/end date, run, see performance summary.
|
||||
- Persist run results (keep history) so refresh doesn't lose them.
|
||||
|
||||
### 5. Next-update column
|
||||
- Each source row gains `next_update_after` (from frequency → next scheduled
|
||||
refresh time). Show "อัปเดตอีกครั้ง ~X" in the sources table.
|
||||
|
||||
## Files
|
||||
- `docs/methodology-research.md` (new, point 1)
|
||||
- `backend/app/factors.py` (more factors; sources derive here)
|
||||
- `backend/app/dashboard.py` (sources FROM registry + next_update)
|
||||
- `backend/app/backtest.py` (new engine, point 4)
|
||||
- `backend/app/__init__.py` (backtest endpoint, sources wiring)
|
||||
- `frontend/src/App.vue` (backtest section + next-update col + sources from API)
|
||||
- tests
|
||||
|
||||
## Acceptance
|
||||
1. Adding a FACTOR to `factors.py` auto-appends a sources-table row (no manual edit).
|
||||
2. `/api/v1/dashboard/sources` has 5+ rows, all real, each with next_update_after.
|
||||
3. Backtest with {start,end} returns a full P&L report (price + dividend + net), and
|
||||
results persist (not lost on refresh).
|
||||
4. Literature doc recommends ≥1 concrete formula refinement, cited.
|
||||
5. npm build + full suite pass; browser shows backtest section + next-update column.
|
||||
|
||||
## Open decisions for user
|
||||
- D1: rebalancing frequency in backtest (monthly / quarterly / weekly)?
|
||||
- D2: do BOT Portal API sources require your API key, or only auth-free ones for now?
|
||||
- D3: backtest default range (last 12 months / last N quarters)?
|
||||
@@ -0,0 +1,396 @@
|
||||
# Event-Driven PIT Backtest Implementation Plan
|
||||
|
||||
> **For Hermes:** Execute task-by-task. Use TDD for accounting/event logic, keep one task in progress, commit by phase, and run `requesting-code-review` before delivery.
|
||||
|
||||
**Goal:** Replace the current calendar-rebalance/backtest proxy with a strict point-in-time, event-driven portfolio simulation that reinvests sale proceeds and paid dividends, respects 100-share lots, records realized/unrealized P&L, and reconciles final equity exactly.
|
||||
|
||||
**Architecture:** Build a deterministic event calendar from data releases, execution dates, dividend entitlement/payment dates, and the end valuation date. Feed those events through a portfolio ledger that owns cash, holdings, average cost, dividend receivables, orders, realized P&L, and costs. The API derives readiness/default dates from actual PIT coverage and blocks rather than silently falling back to current data.
|
||||
|
||||
**Tech Stack:** Python 3.11, Flask, filesystem PIT stores, Vue/Vite, unittest/pytest.
|
||||
|
||||
---
|
||||
|
||||
## Confirmed Decisions
|
||||
|
||||
| Decision | Chosen default | Rationale |
|
||||
|---|---|---|
|
||||
| Backtest readiness | Strict PIT coverage for every required scoring input; otherwise block and report missing coverage | Prevents mixed-PIT results from looking valid |
|
||||
| Signal execution | Freeze signal on release date D; execute at next available trading-day close after D | Avoids same-day close look-ahead |
|
||||
| Dividend timing | Entitlement at ex-date; cash becomes available exactly 30 calendar days after ex-date | User-approved deterministic timing assumption; expose it as `ex_date_plus_30d` rather than claiming an observed payment date |
|
||||
| Cost basis | Average cost | Simple, auditable, common portfolio accounting |
|
||||
| Fees/taxes | All-in fee 0.3% of notional on every buy and every sell; do not add VAT/tax again | Explicit user decision; deterministic and auditable |
|
||||
| Same-day releases | Coalesce all releases known by the execution cutoff into one frozen signal and one rebalance | Avoids churn from multiple events on the same day |
|
||||
| End date on holiday/weekend | Value at latest trading close on or before end date | Deterministic and realistic |
|
||||
|
||||
These decisions were confirmed by the user and are implementation requirements.
|
||||
|
||||
---
|
||||
|
||||
## Current-State Gap Matrix
|
||||
|
||||
| Requirement | Current behavior | Gap |
|
||||
|---|---|---|
|
||||
| Default start = first date advice is genuinely available | API/UI hardcode `2024-06-01` | No readiness calculation; current disk has no factor vintages or Siamchart vintage manifest |
|
||||
| Default end = yesterday | API/UI hardcode `2026-06-01` | On 2026-08-28 +07, expected default is 2026-08-27 |
|
||||
| Recompute only when new information arrives | `_rebalance_dates()` emits monthly/quarterly dates (`backend/app/backtest.py:103-125`) | Calendar-driven, not release/event-driven |
|
||||
| Strict PIT | Optional `score_fn`; current data fallback exists | Current local data has 0 factor-vintage files and 0 Siamchart vintage snapshots, so no strict PIT-ready start exists |
|
||||
| Execute after signal is known | `_latest_close(..., d)` uses close on rebalance date | Can use the same close that occurred before/while data was released |
|
||||
| Dividend entitlement and cash timing | `credit_dividends()` is called only at end, using final holdings (`backtest.py:253-268`) | Wrong holdings-at-ex-date, no mid-run cash credit, no reinvestment, historic dividends can be overcounted |
|
||||
| Sale P&L | Sell proceeds update cash only (`backtest.py:232-241`) | No cost basis, realized P&L, fees, or per-trade ledger |
|
||||
| Reinvest gains/dividends | Sale cash can fund buys in the same rebalance; dividends are added only after all rebalances | Dividends cannot fund later buys; profit/cash trace is absent |
|
||||
| 100-share lots | `allocate_capital()` floors to 100 shares | Already present; must preserve during target reconciliation |
|
||||
| Final report | final holdings, total value, combined price P&L, dividend total | Must split realized/unrealized P&L, cash, receivables, costs, trades, and prove reconciliation |
|
||||
| Current data coverage | Price snapshot: 9 symbols, 2024-01-03 to common 2026-07-17; no factor vintages/Siamchart manifest on disk | Strict PIT backtest should currently block, not manufacture a default start |
|
||||
|
||||
---
|
||||
|
||||
## Target Event Flow
|
||||
|
||||
```text
|
||||
Coverage/readiness
|
||||
→ earliest date where ALL PIT inputs + executable prices exist
|
||||
→ initial recommendation event at start
|
||||
→ freeze target signal
|
||||
→ next trading day execution (100-share lots)
|
||||
→ for each data release:
|
||||
coalesce same-day changes
|
||||
recompute recommendation from PIT state
|
||||
if target changes: sell first → credit proceeds/realized P&L → buy using current cash
|
||||
→ for each dividend:
|
||||
ex-date: record entitlement using shares held before ex-date
|
||||
ex-date + 30 calendar days: credit cash; available to next rebalance
|
||||
→ end date:
|
||||
mark holdings to latest close ≤ end
|
||||
report cash + market value + dividend receivable (separate)
|
||||
reconcile all P&L components
|
||||
```
|
||||
|
||||
Accounting invariant:
|
||||
|
||||
```text
|
||||
ending_equity - initial_capital
|
||||
= realized_trading_pnl
|
||||
+ unrealized_trading_pnl
|
||||
+ dividend_cash_received
|
||||
+ accrued_dividend_receivable
|
||||
- transaction_costs
|
||||
```
|
||||
|
||||
`price_pnl = realized_trading_pnl + unrealized_trading_pnl` for compatibility.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Add Strict Backtest Coverage and Default-Date Readiness
|
||||
|
||||
**Objective:** Derive valid start/end defaults from actual PIT stores and block when coverage is incomplete.
|
||||
|
||||
**Files:**
|
||||
- Create: `backend/app/backtest_readiness.py`
|
||||
- Modify: `backend/app/factor_vintages.py`
|
||||
- Modify: `backend/app/siamchart_vintages.py`
|
||||
- Modify: `backend/app/prices.py` or add a read-only adapter for price coverage
|
||||
- Modify: `backend/app/__init__.py`
|
||||
- Test: `backend/tests/test_backtest_readiness.py`
|
||||
|
||||
**Steps:**
|
||||
1. Write failing tests for:
|
||||
- no factor vintages → `ready=false`, missing factor list
|
||||
- no Siamchart snapshot → blocked
|
||||
- price coverage starting after PIT factors → recommended start equals latest of first-ready dates
|
||||
- recommended end = yesterday in Bangkok, bounded by latest price date
|
||||
- user start earlier than readiness → HTTP 400 with exact missing coverage
|
||||
2. Add store coverage APIs:
|
||||
- `FactorVintageStore.first_release(factor_key)` and coverage summary
|
||||
- `SiamchartVintageStore.first_retrieved_at()`
|
||||
- price coverage: earliest/latest executable trading dates by required universe
|
||||
3. Implement `BacktestReadiness` response:
|
||||
- `ready`, `recommended_start`, `recommended_end`, `missing`, `coverage`, `timezone`
|
||||
4. Add `GET /api/v1/backtest/readiness`.
|
||||
5. Change `POST /api/v1/backtest` defaults to readiness-derived dates; never hardcode dates.
|
||||
6. Verify targeted tests and API smoke.
|
||||
|
||||
**Acceptance:** Current local dataset returns `ready=false` because factor/Siamchart PIT history is absent; it does not start a purported PIT run.
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Build the Unified Backtest Event Calendar
|
||||
|
||||
**Objective:** Rebalance on information changes, not arbitrary monthly/quarterly dates.
|
||||
|
||||
**Files:**
|
||||
- Create: `backend/app/backtest_events.py`
|
||||
- Modify: `backend/app/factor_vintages.py`
|
||||
- Modify: `backend/app/siamchart_vintages.py`
|
||||
- Modify: `backend/app/dividend_ledger.py`
|
||||
- Test: `backend/tests/test_backtest_events.py`
|
||||
|
||||
**Steps:**
|
||||
1. Define typed/dataclass events:
|
||||
- `SignalReleaseEvent(released_at, sources, factor_keys)`
|
||||
- `ExecutionEvent(signal_date, execution_date)`
|
||||
- `DividendEntitlementEvent(ex_date, symbol, per_share)`
|
||||
- `DividendPaymentEvent(assumed_payment_date=ex_date+30d, entitlement_id, timing_method="ex_date_plus_30d")`
|
||||
- `EndValuationEvent(end_date)`
|
||||
2. Add chronological iterators to factor and Siamchart vintage stores.
|
||||
3. Build release calendar from all PIT changes within `[start, end]`.
|
||||
4. Coalesce releases on the same date.
|
||||
5. Map each signal date to the next available trading date strictly after the release date.
|
||||
6. Include dividend entitlement/payment events and final valuation event.
|
||||
7. Create an assumed payment event exactly 30 calendar days after ex-date. Keep the dividend as a receivable until that event, then credit spendable cash. Expose the timing assumption in every event/result.
|
||||
8. Test ordering, holiday/weekend handling, coalescing, and no-look-ahead execution.
|
||||
|
||||
**Acceptance:** A factor release three months after start generates one new frozen signal and, only if targets differ, one rebalance on the next trading day.
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Implement the Portfolio Accounting Ledger
|
||||
|
||||
**Objective:** Own all cash, holdings, cost basis, trades, dividends, and P&L in one auditable component.
|
||||
|
||||
**Files:**
|
||||
- Create: `backend/app/portfolio_ledger.py`
|
||||
- Test: `backend/tests/test_portfolio_ledger.py`
|
||||
|
||||
**Data model:**
|
||||
|
||||
```python
|
||||
Position(symbol, qty, average_cost)
|
||||
Trade(date, signal_date, symbol, side, qty, price, notional,
|
||||
cost_basis_released, realized_pnl, fees, cash_after, reason)
|
||||
DividendReceivable(symbol, ex_date, assumed_payment_date,
|
||||
timing_method="ex_date_plus_30d", qty_entitled,
|
||||
per_share, amount, status)
|
||||
PortfolioState(cash, positions, receivables, realized_pnl,
|
||||
dividend_cash, fees, trades)
|
||||
```
|
||||
|
||||
**Steps:**
|
||||
1. Write RED tests for average-cost buys, partial sells, full sells, realized P&L, and no negative cash.
|
||||
2. Implement `buy()`:
|
||||
- qty positive and multiple of 100
|
||||
- all-in fee = `notional * 0.003`
|
||||
- cost + fee <= cash
|
||||
- recompute weighted average cost
|
||||
3. Implement `sell()`:
|
||||
- qty positive/multiple of 100 and <= position
|
||||
- all-in fee = `notional * 0.003`
|
||||
- realized P&L = proceeds - released average cost - sell fee
|
||||
- credit net proceeds (`notional - fee`) to cash before later buys
|
||||
4. Implement dividend entitlement at ex-date using quantity held before ex-date.
|
||||
5. Implement payment-date cash credit; paid dividend can fund later orders.
|
||||
6. Keep unpaid dividends as receivables, not spendable cash.
|
||||
7. Add mark-to-market and reconciliation methods.
|
||||
8. Test cash conservation and accounting identity after mixed buys/sells/dividends.
|
||||
|
||||
**Acceptance:** Profitable sales and paid dividends increase cash available to subsequent 100-share-lot purchases; unpaid receivables do not.
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Reconcile Target Portfolio with Lot and Cash Constraints
|
||||
|
||||
**Objective:** Convert each frozen recommendation into executable sell/buy orders using current total equity and current cash.
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/simulation.py`
|
||||
- Create or modify: `backend/app/portfolio_rebalancer.py`
|
||||
- Test: `backend/tests/test_portfolio_rebalancer.py`
|
||||
|
||||
**Steps:**
|
||||
1. Preserve canonical 50/20/30 allocation rules and 100-share lots.
|
||||
2. Compute target quantities from current equity (cash + market value + paid dividends; exclude receivables).
|
||||
3. Generate sells first, execute them, then recompute available cash.
|
||||
4. Generate buys from remaining target deficits, never exceeding cash.
|
||||
5. If a target lot is unaffordable, skip it and retain cash; never buy odd lots.
|
||||
6. Rebalance only when target quantities differ from current quantities.
|
||||
7. Add tests for:
|
||||
- sale profit funds next purchase
|
||||
- dividend payment funds next purchase
|
||||
- insufficient cash leaves cash and skips order
|
||||
- unchanged recommendation produces zero trades
|
||||
- no negative cash under rounding/fees
|
||||
|
||||
**Acceptance:** Every trade is in 100-share multiples, and ending cash is always non-negative.
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Rewrite Backtest Engine as Event Processor
|
||||
|
||||
**Objective:** Replace `_rebalance_dates()` calendar loop with the event calendar and portfolio ledger.
|
||||
|
||||
**Files:**
|
||||
- Rewrite: `backend/app/backtest.py`
|
||||
- Modify: `backend/app/pit_scorer.py`
|
||||
- Test: `backend/tests/test_backtest.py`
|
||||
- Test: `backend/tests/test_backtest_integration.py`
|
||||
|
||||
**Steps:**
|
||||
1. RED test the complete scenario:
|
||||
- start recommendation buys A
|
||||
- release three months later changes target to B
|
||||
- sell A at profit
|
||||
- dividend entitlement/payment occurs
|
||||
- sale proceeds + paid dividend fund B purchase
|
||||
- final holdings/value and P&L reconcile
|
||||
2. Initialize from strict PIT readiness and initial signal.
|
||||
3. Process events in order:
|
||||
- release → freeze scores/target
|
||||
- execution → reconcile portfolio
|
||||
- ex-date → entitlement
|
||||
- payment → cash credit
|
||||
- end → mark-to-market
|
||||
4. Record every release, rebalance, trade, and dividend event.
|
||||
5. Ensure `leakage_guard=true` only if every score at every release is PIT; otherwise reject strict mode.
|
||||
6. Remove monthly/quarterly frequency as the primary trigger. Optionally retain a separate explicit `scheduled` research mode, clearly non-default/non-event-driven.
|
||||
7. Verify no double-counted dividends and no repeated historical credits.
|
||||
|
||||
**Acceptance:** Engine output exactly follows the user-described lifecycle and passes accounting reconciliation for every tested scenario.
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Expand Backtest Result Contract and Durable Run Storage
|
||||
|
||||
**Objective:** Return all requested end-state and P&L breakdowns with a durable audit trail.
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/backtest.py`
|
||||
- Create: `backend/app/backtest_store.py`
|
||||
- Modify: `backend/app/__init__.py`
|
||||
- Test: `backend/tests/test_backtest_store.py`
|
||||
- Modify: API tests in `backend/tests/test_api.py`
|
||||
|
||||
**Response v2:**
|
||||
|
||||
```json
|
||||
{
|
||||
"start": "...",
|
||||
"end": "...",
|
||||
"initial_capital": 1000000,
|
||||
"ending_cash": 12345,
|
||||
"ending_market_value": 1100000,
|
||||
"dividend_receivable": 500,
|
||||
"final_equity": 1112845,
|
||||
"net_change": 112845,
|
||||
"net_return": 0.112845,
|
||||
"realized_trading_pnl": 45000,
|
||||
"unrealized_trading_pnl": 50000,
|
||||
"price_pnl": 95000,
|
||||
"dividend_cash_received": 18000,
|
||||
"transaction_costs": 155,
|
||||
"fee_rate": 0.003,
|
||||
"holdings": [{"symbol":"...","qty":100,"average_cost":...,"last_price":...,"market_value":...,"unrealized_pnl":...}],
|
||||
"trades": [...],
|
||||
"dividends": [...],
|
||||
"rebalance_events": [...],
|
||||
"accounting_reconciled": true,
|
||||
"leakage_guard": true
|
||||
}
|
||||
```
|
||||
|
||||
**Steps:**
|
||||
1. Add result dataclasses and compatibility aliases (`final_value`, `dividend_income`).
|
||||
2. Add durable JSON run store (atomic writes) rather than process-local `backtest_runs`.
|
||||
3. Persist exact input coverage, event calendar, and scorer provenance with each run.
|
||||
4. Add reconciliation assertions before serializing; fail closed if imbalance exceeds tolerance.
|
||||
5. Test reload after app restart and API history output.
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Update Frontend Defaults, Controls, and Report
|
||||
|
||||
**Objective:** Make UI defaults/readiness and results reflect the new engine honestly.
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/src/App.vue`
|
||||
- Test/build: `frontend/package.json` existing build
|
||||
|
||||
**Steps:**
|
||||
1. On load, call `/api/v1/backtest/readiness`.
|
||||
2. Set start to `recommended_start` and end to `recommended_end`; remove hardcoded `2024-06-01` / `2026-06-01`.
|
||||
3. If readiness is blocked, disable Run and show exact missing coverage.
|
||||
4. Replace “รายเดือน/รายไตรมาส” primary control with “ตามข้อมูลใหม่ (event-driven)”. Keep scheduled frequency only under advanced/descriptive mode if retained.
|
||||
5. Display:
|
||||
- final holdings with qty, average cost, latest price, market value, unrealized P&L
|
||||
- final equity, net change, return
|
||||
- dividend cash received and dividend receivable
|
||||
- realized trading P&L, unrealized P&L, total price P&L, fees
|
||||
- event timeline / trade table
|
||||
6. Keep visible PIT/non-PIT and dated-ledger/proxy badges.
|
||||
7. Run production build and verify rendered result state.
|
||||
|
||||
---
|
||||
|
||||
### Task 8: Verification and Independent Review Gate
|
||||
|
||||
**Objective:** Prove correctness before shipping.
|
||||
|
||||
**Files:**
|
||||
- Create: `docs/test-evidence/YYYY-MM-DD-event-driven-backtest.md`
|
||||
- Update: `docs/engineering-log.md`
|
||||
- Update: `docs/HANDOFF.md`
|
||||
|
||||
**Required tests/gates:**
|
||||
1. Targeted event-calendar suite.
|
||||
2. Portfolio-ledger suite.
|
||||
3. Rebalancer suite.
|
||||
4. Full backtest integration suite.
|
||||
5. Full backend suite.
|
||||
6. Frontend production build.
|
||||
7. Static security scan; no secrets/debug leftovers.
|
||||
8. `git diff --check`, compileall.
|
||||
9. Live API probe with a deterministic temporary PIT fixture.
|
||||
10. Browser verification of readiness-blocked and completed-result states.
|
||||
11. Fresh independent reviewer subagent; fail closed on any logic/security blocker.
|
||||
12. Auto-fix/re-review max two cycles.
|
||||
|
||||
**Critical invariants:**
|
||||
- cash never negative
|
||||
- all buy/sell quantities multiples of 100
|
||||
- no trade before signal is knowable
|
||||
- no dividend entitlement for shares bought on/after ex-date
|
||||
- unpaid dividends never fund purchases
|
||||
- paid dividends can fund subsequent purchases
|
||||
- realized P&L uses average cost
|
||||
- unchanged target creates no trade
|
||||
- final accounting identity reconciles within one satang/rounding tolerance
|
||||
- current local data returns readiness blocked rather than fake PIT performance
|
||||
|
||||
---
|
||||
|
||||
## Files Likely to Change
|
||||
|
||||
- `backend/app/backtest.py`
|
||||
- `backend/app/backtest_readiness.py` (new)
|
||||
- `backend/app/backtest_events.py` (new)
|
||||
- `backend/app/portfolio_ledger.py` (new)
|
||||
- `backend/app/portfolio_rebalancer.py` (new)
|
||||
- `backend/app/backtest_store.py` (new)
|
||||
- `backend/app/dividend_ledger.py`
|
||||
- `backend/app/factor_vintages.py`
|
||||
- `backend/app/siamchart_vintages.py`
|
||||
- `backend/app/prices.py`
|
||||
- `backend/app/simulation.py`
|
||||
- `backend/app/__init__.py`
|
||||
- `backend/tests/test_backtest*.py`
|
||||
- new focused backend test modules
|
||||
- `frontend/src/App.vue`
|
||||
- engineering/test-evidence docs
|
||||
|
||||
## Explicit Non-Goals
|
||||
|
||||
- Live order execution / MT5 dispatch
|
||||
- Guessing historical factor values that were never recorded
|
||||
- Claiming PIT performance before coverage readiness passes
|
||||
- Broker-specific fee assumptions without configuration
|
||||
- Odd-lot trading
|
||||
|
||||
## Main Risks
|
||||
|
||||
1. **No current strict PIT-ready window:** the local store has no factor vintages/Siamchart manifest. The correct initial UI state is blocked.
|
||||
2. **Dividend payment timing is assumed:** current Siamchart data supplies ex-date+DPS, not payment date. The user confirmed `assumed_payment_date = ex_date + 30 calendar days`; every result must disclose `timing_method=ex_date_plus_30d`.
|
||||
3. **Price quality:** current Yahoo revised history is explicitly non-PIT; strict validated backtests need an evidence-bearing price archive contract.
|
||||
4. **Universe coverage:** current price snapshot contains 9 symbols, not the full 49-symbol board.
|
||||
5. **Response compatibility:** current UI/API expect scalar holdings and `price_pnl`; v2 needs compatibility aliases during migration.
|
||||
|
||||
## Open Questions
|
||||
|
||||
None for the core accounting/event model. The implementation decisions above are confirmed.
|
||||
@@ -0,0 +1,107 @@
|
||||
# Architecture Plan — Additional Data Sources per Theme + Use-in-Analysis Enforcement
|
||||
|
||||
> Status: SUPERSEDED / largely IMPLEMENTED (2026-08-29). The use-in-analysis
|
||||
> invariant + sign fix are done and committed (`fcc0da9`); the external-sector
|
||||
> gap (this plan's BOT report-60 target) is covered by `thai_trade.py`
|
||||
> (TradingEconomics current-account/exports/imports); commercial-loan coverage
|
||||
> is provided by `te_loan_growth` (TE loans-to-fin-corp) and `te_consumer_credit`.
|
||||
> See `2026-08-29_data-source-expansion-phase-2.md` for the actual delivered work
|
||||
> and the remaining backlog (REIC/EPPO/NBTC/energy-breadth).
|
||||
> Author: Macky. Date: 2026-08-29.
|
||||
|
||||
## Goal
|
||||
Close the "few sources per theme" gap AND lock the user's rule — every data point fetched must feed analysis, not just display. This is the follow-up the declarative factor engine (2026-08-26 plan) explicitly deferred: "no new collectors yet; sources are added as follow-up."
|
||||
|
||||
Two deliverables:
|
||||
1. **Wiring convention that guarantees use-in-analysis** — a build/test pattern so a new source cannot be added without being consumed by `compute_theme_surprises`.
|
||||
2. **Two new high-feasibility Thai sources**, wired end-to-end, verified against live pages: **BOT Balance of Payments** (report 60) and **BOT Commercial-bank loans** (reportID confirmed at build). A **medium-feasibility** source (**REIC house-price/transfer**) is scoped but flagged for a feasibility spike before committing.
|
||||
|
||||
## Why this is needed (evidence — verified against live sources this session)
|
||||
- 6 of 13 themes (`telecom_it`, `property`, `healthcare`, `consumer_staples`, `petrochem_materials`, `retail`) rest on **one BOT macro page**. Source count is genuinely thin.
|
||||
- Found + fixed (this session, prior commit pending): `core_inflation_yoy` and `unemployment_pct` were **fetched but never used**; worse, every `sign:-1` factor (NPL/inflation/unemployment) used a **negative** theme weight → double-negative → **higher NPL raised the theme score**. Both fixed in `factors.py`/`themes.py` with regression tests. This plan prevents recurrence and adds genuinely *new providers*, not just new fields on the same page.
|
||||
- **Feasibility verified live**: BOT `ReportPage.aspx?reportID=60` (Balance of Payments) responds to the exact `dgExcel` form-POST flow already implemented in `bot_tourism.py` (200, parseable — exports/imports/current-account series extracted this session). REIC homepage is a portal — data lives on subpages/endpoints (medium feasibility).
|
||||
|
||||
## Why the current architecture makes this cheap
|
||||
Adding a factor already needs **no scoring-function change** (`factors.py` registry + a theme factor line). The new work is only:
|
||||
- a collector module exposing `.to_dict()`,
|
||||
- registry + theme wiring,
|
||||
- a scheduler `_REFRESH_JOBS` entry (so it collects + appears in source-health log),
|
||||
- a `_source_label` provenance entry,
|
||||
- tests.
|
||||
|
||||
## Decision Gates (approve before code)
|
||||
- **G0** — Approve the 2 source choices + the mandatory-use test contract (below). Exit → build B0.
|
||||
- **G1** — Collector parses a frozen fixture; factor value extracted; **used-in-analysis test passes**. Exit → wire.
|
||||
- **G2** — `/api/v1/dashboard` shows the new source row + `source_summary` factor_keys increases; board surprises change with it. Exit → done.
|
||||
|
||||
## New collectors
|
||||
|
||||
### B0 — Thailand External Sector / Trade (`thai_trade.py`) [high feasibility — VERIFIED current]
|
||||
- **PIVOT from BOT BOP report 60:** probing live this session showed the BOT statistics portal's `reportID=60` only carries data **through 2011** (its `drpToYear` options cap at `2011xxxx`) — stale, not fit for a 2026 platform. Per the plan's gate ("do not ship a factor reading a wrong/stale series") we source the external sector from **TradingEconomics Thailand trade**, which is **live through June 2026** and reuses the exact `auto_credit.py` scraping pattern (same site/infobox):
|
||||
- `https://tradingeconomics.com/thailand/current-account` → current-account balance (USD mn, June 2026 verified)
|
||||
- `https://tradingeconomics.com/thailand/exports` → exports (USD mn, 2026 verified)
|
||||
- `https://tradingeconomics.com/thailand/imports` → imports (USD mn, 2026 verified)
|
||||
- Factors (declarative additions):
|
||||
- `external_current_account` — current-account balance → sign +1 (strong external position supportive). Feeds **tourism**, **exploration**, **petrochem_materials**, **retail**.
|
||||
- `external_exports` — exports USD mn → sign +1. Feeds **petrochem_materials**, **exploration**, **telecom_it**.
|
||||
- `external_imports` — imports USD mn (domestic demand) → sign +1. Feeds **retail**, **consumer_staples**, **property**.
|
||||
- Frequency: monthly. Scheduler cadence: monthly.
|
||||
- Test: frozen fixture (one value sentence) → parse → assert current account / exports / imports; used-in-analysis test asserts a change in the fed themes.
|
||||
|
||||
### B1 — BOT Commercial-bank loans (`bot_bank_loans.py`) [high feasibility — flow VERIFIED, reportID TBD]
|
||||
- Same `dgExcel` adapter, new reportID. The exact BOT report for commercial-bank loans/deposits is **confirmed accessible in principle** (report 60 proved the flow); its numeric reportID is discovered at build time from BOT's statistics index / report search (do NOT hardcode an unverified ID).
|
||||
- Fields expected: total loans outstanding, deposits, NPL (commercial banks), **loan growth YoY** as derived factor.
|
||||
- Factors:
|
||||
- `bank_loan_growth` — commercial-bank loan growth YoY → sign +1. Feeds **banks** (primary), **nonbank_finance**, **property** (mortgage-linked).
|
||||
- `bank_deposit_growth` — deposit growth → sign +1 (funding base). Feeds **banks**.
|
||||
- Frequency: monthly (BOT reports these monthly). Scheduler cadence: monthly.
|
||||
- **Gate**: if the found reportID/data is not cleanly loan-related, fall back to BOT "credit by sector" report and re-scope the factor — do not ship a factor reading a wrong series.
|
||||
|
||||
### B2 — REIC house-price / transfer index (`reic_housing.py`) [MEDIUM feasibility — SPIKE FIRST]
|
||||
- Homepage is a portal (verified). The house-price index / residential transfer data live on a subpage or a data endpoint (likely JSON/PDF). **Spike task before G0 sign-off on this one**: locate the real data URL, confirm it is scrapeable without an API key.
|
||||
- If feasible → factor `reic_housing_price_index` / `reic_transfer_value_yoy` → sign +1 → feeds **property**.
|
||||
- If the only clean access is a PDF chart with no numeric series → **defer** (do not ship a display-only scrape). This is the exact "แค่ดึงข้อมูลมาเฉย ๆ" the user forbids.
|
||||
|
||||
## Wiring checklist per source (all must land)
|
||||
1. `backend/app/<module>.py` — dataclass + `to_dict()` + `fetch_<module>()` (+ frozen-fixture parse fn).
|
||||
2. `factors.py` — FACTORS entries (source/frequency/fetch/value_key/sign/center/span).
|
||||
3. `themes.py` — factor lines with **positive** weights on the sign-correct themes (the sign lives in the factor).
|
||||
4. `scheduler.py` — `_REFRESH_JOBS` entry (module/fn/fetch_module/frequency) so it collects + shows in the health log.
|
||||
5. `dashboard.py` — `_build_sources` `_source_label` map entry (provenance table).
|
||||
6. `__init__.py` — no endpoint change needed (dashboard drives the UI); verify `/api/v1/dashboard` picks it up (G2).
|
||||
|
||||
## Use-in-analysis enforcement (the user's rule, made a test)
|
||||
Two contracts, added as tests so "fetched but not used" can never silently return:
|
||||
- **Contract A (value_key resolves):** every `FACTORS.value_key` must be a real field the registered fetch module emits. Already added (`test_every_factor_value_key_resolves_to_a_fetched_field`). Extend it as new modules land.
|
||||
- **Contract B (new factor moves scores):** for each new factor, a test feeds a neutral vs a hot value and asserts the target theme surprise changes **in the right direction** (bearish factors lower it). Pattern already added (`test_new_macro_factors_actually_move_scores`, `test_bearish_factors_move_score_the_right_way`). One such test per new factor.
|
||||
|
||||
This dual contract is the build guarantee that fulfills "มีแหล่งข้อมูลใหม่ → ต้องใช้ในการวิเคราะห์จริง".
|
||||
|
||||
## Data Model sketch
|
||||
```python
|
||||
# factors.py
|
||||
"macro_current_account": {"source":"BOT BOP","frequency":"monthly",
|
||||
"fetch":"bot_bop","value_key":"current_account_balance_mb",
|
||||
"sign":1, "center":0.0, "span":80000.0},
|
||||
"bank_loan_growth": {"source":"BOT CB loans","frequency":"monthly",
|
||||
"fetch":"bot_bank_loans","value_key":"loan_growth_yoy",
|
||||
"sign":1, "center":5.0, "span":10.0},
|
||||
|
||||
# themes.py — positive weights; direction is in the factor
|
||||
"banks": { "factors": [ {"key":"macro_investment","weight":1.0},
|
||||
{"key":"bank_loan_growth","weight":0.8},
|
||||
... ] },
|
||||
```
|
||||
|
||||
## Non-Goals (v1)
|
||||
- No new factors on the existing single BOT macro page beyond the two already wired (core inflation, unemployment) — avoid the "one page, many pseudo-independent factors" trap.
|
||||
- No live trading / MT5 changes. No LLM in scoring. No API-key sources (free/scrapeable only).
|
||||
- Do not ship a REIC scrape unless a clean numeric series exists.
|
||||
|
||||
## Acceptance (definition of done)
|
||||
1. Thailand external-sector (TradingEconomics trade) collector + 3 factors land, verified against a frozen fixture and a live fetch (current through 2026 — not the stale BOT-60 series).
|
||||
2. BOT commercial-bank-loan collector + factors land (reportID confirmed; else scoped fallback).
|
||||
3. REIC either lands with a real series **or** is explicitly deferred (no display-only scrape).
|
||||
4. Every new factor has Contract A + Contract B tests green.
|
||||
5. Full backend suite (352 → target ≥ 366) + `npm run build` pass.
|
||||
6. `/api/v1/dashboard` `sources` + `source_summary.factor_keys` increase; board surprises visibly move with a hot value.
|
||||
@@ -0,0 +1,175 @@
|
||||
# Data Source Expansion Plan — Phase 2 (more Thai sources per theme)
|
||||
|
||||
> **For Hermes:** Execute task-by-task. One task in progress at a time; commit by phase; run `requesting-code-review` before delivery. Every new source MUST end wired into `FACTORS` (one dict entry) **and** referenced by at least one `THEMES[].factors` row — so it feeds `compute_theme_surprises()`, never just the source table. Follow the existing collector template (`backend/app/thai_trade.py`, `auto_credit.py`). Run the full backend suite + `npm run build` after each phase.
|
||||
|
||||
**Goal:** Add genuinely new Thai data sources for the themes that today rely on a single BOT macro proxy (banks, retail, property, telecom_it, nonbank_finance, healthcare, utilities/energy), each wired into the factor engine so it changes theme surprises — not merely the provenance table.
|
||||
|
||||
**Architecture (unchanged, declarative):**
|
||||
```
|
||||
new source → collector module (fetch_<x>() → Snapshot.to_dict())
|
||||
→ FACTORS entry {name_th, source, frequency, fetch, value_key, sign, weight, center, span}
|
||||
→ THEMES[<theme>].factors [{key, weight}]
|
||||
→ compute_theme_surprises() picks it up with zero scoring-fn change
|
||||
```
|
||||
Adding a factor = 1 registry entry + (optionally) a theme factor line. No scoring random. This is already proven by `thai_trade`.
|
||||
|
||||
**Current state (verified, baseline green: 352/352 tests):**
|
||||
- 7 live sources: `bot_tourism`, `auto_credit`, `auto_npl`, `bank_npl`, `energy_thai`, `macro_thai`, `thai_trade`.
|
||||
- 17 FACTORS registered. All `value_key` resolve to a real fetched field (locked by `test_every_factor_value_key_resolves_to_a_fetched_field`).
|
||||
- Sign convention FIXED this session: `sign` lives only in the factor; theme weights are positive magnitude. Regression-locked by `test_bearish_factors_move_score_the_right_way` (higher NPL ⇒ lower score, etc.).
|
||||
- `thai_trade.py` (TradingEconomics current-account) is the reference collector: server-rendered HTML, `_fetch`/`parse`/`fetch_<x>`/`to_dict`, registered in scheduler `_REFRESH_JOBS` + dashboard `_fetch_with_cache` + FACTORS.
|
||||
|
||||
---
|
||||
|
||||
## Confirmed Decisions (from user: "วางแผนได้เลย")
|
||||
| Decision | Chosen | Rationale |
|
||||
|---|---|---|
|
||||
| Scope | Phase A (macro-deepening) first, Phase B (sector) next | Fastest correctness win, lowest scrap fragility |
|
||||
| New-source gate | Feasibility spike per source BEFORE building collector | Don't ship a wrong/stale/unscrapable series (same gate `thai_trade.py` used) |
|
||||
| Integration | Every new FACTOR must appear in ≥1 THEMES factor line + scheduler + dashboard cache | User rule: new data must feed analysis, not just be fetched |
|
||||
| Test | One value-key-resolution + one direction test per new source | Locks "used in analysis" invariant |
|
||||
|
||||
## Pending user decision (gate G0 — before Phase A code)
|
||||
1. **Which sources to prioritize** — recommendation in priority order below. User may reorder/substitute.
|
||||
2. Confirm each target URL is acceptable (some BOT/REIC/EPPO pages are heavy; a couple may need a different page).
|
||||
|
||||
---
|
||||
|
||||
## Current-State Gap Matrix (per theme, what feeds it today)
|
||||
| Theme | Sources today | Gap / weakest link |
|
||||
|---|---|---|
|
||||
| banks | BOT macro (invest/inflation/NPL) — 3 fields, all BOT | No rate/loan-setting input; NPL only "financial sector" proxy |
|
||||
| retail | BOT macro (consumption/inflation/unemployment) + TE imports | No direct retail-sales / consumer-mood series |
|
||||
| consumer_staples | BOT macro + TE imports | Same as retail |
|
||||
| telecom_it | BOT macro (consumption/investment) + TE exports | No telecom-specific (subs/data) series |
|
||||
| property | BOT macro (invest/consumption/inflation) + TE imports | No real-estate-specific (transfer/mortgage) series |
|
||||
| nonbank_finance | BOT macro + auto NPL + unemployment | No household-credit / consumer-loan series |
|
||||
| healthcare | BOT macro (consumption/unemployment) | No healthcare/tourism-medical series |
|
||||
| utilities | BOT macro (mfg) + TOP margin | No electricity-demand / generation series |
|
||||
| tourism | BOT tourism + macro consumption + TE current acct | Covered well; optional: hotel occupancy |
|
||||
| auto_credit | TE vehicle + BOT auto NPL | Covered well |
|
||||
| refining_energy / exploration / petrochem | TOP + macro mfg/inflation + TE exports | Only TOP company; no commodity/oil price |
|
||||
|
||||
---
|
||||
|
||||
## Phase A — deepen macro-proxy themes (priority order)
|
||||
Each is a collector + FACTORS entry ×N + THEME wiring + tests.
|
||||
|
||||
### A1. BOT policy/loan-rate + credit — banks, nonbank_finance
|
||||
- Target: BOT monetary-policy / rate page (e.g. `bot.or.th` policy rate) + BOT credit/loan-growth report.
|
||||
- Factors: `bank_policy_rate` (sign −1 for banks? higher rate squeezes demand), `bank_loan_growth_yoy` (sign +1).
|
||||
- Feasibility: spike must confirm a scrapeable numeric series on a BOT page.
|
||||
|
||||
### A2. Household / consumer credit — nonbank_finance (+ banks)
|
||||
- Target: BOT consumer-loan (สินเชื่อส่วนบุคคล/บัตรเครดิต) report.
|
||||
- Factor: `consumer_credit_yoy` (sign +1), `consumer_credit_npl` (sign −1).
|
||||
- Feasibility: spike on BOT statistics page.
|
||||
|
||||
### A3. Retail sales index — retail, consumer_staples
|
||||
- Target: BOT or TradingEconomics "retail sales" Thailand YoY.
|
||||
- Factor: `retail_sales_yoy` (sign +1).
|
||||
- Feasibility: TE has a Thailand retail-sales page (same inc as auto_credit).
|
||||
|
||||
### A4. Consumer confidence — retail, consumer_staples, nonbank_finance
|
||||
- Target: UTCC / Kasikorn Research consumer-confidence index (free HTML).
|
||||
- Factor: `consumer_confidence` (sign +1).
|
||||
- Feasibility: spike — some sources require login; fallback to TradingEconomics "consumer confidence".
|
||||
|
||||
## Phase B — sector-specific (IMPLEMENTED 2026-08-29 via single-page snapshots)
|
||||
### B1. Property: `te_property_prices` (residential property prices % YoY) — DONE, feeds property theme
|
||||
### B3. Energy breadth: `energy_irpc` (IRPC net margin, 3M26 +10.27%) — DONE, feeds refining_energy/exploration/utilities
|
||||
### B4. Telecom/backdrop: `te_business_confidence` — DONE, feeds telecom_it + property + healthcare
|
||||
### B5. Healthcare: consumer/business backdrop wired in — DONE (macro + business confidence)
|
||||
Added to `te_thailand.py` + new `energy_irpc.py`, same reviewed pattern. Full suite 368.
|
||||
|
||||
## Deferred / blocked by feasibility (2026-08-29 spike results — all JS-rendered or anti-bot)
|
||||
- **REIC** (property transfer): JS SPA, data loads via XHR — not plain-HTML scrapable.
|
||||
Would need browser_exec or `har-derived-api-client` (XHR reverse-engineering).
|
||||
- **EPPO** (utilities electricity): WordPress/JS pages, no static numeric table.
|
||||
- **NBTC** (telecom data): HTTP 403 anti-bot block.
|
||||
- **PTTEP** (energy): JS shell (no server-rendered tables); PTT/BCP URLs 404/DNS.
|
||||
Only **IRPC** among the energy names exposed a server-rendered financial table.
|
||||
These are NOT quick plain-HTML collectors — they need a browser/XHR approach or a
|
||||
logged-in/authorized session. Do them as a separate effort if the analysis needs
|
||||
them, not as simple additions to this collector family.
|
||||
|
||||
## Status updates (2026-08-29, follow-up asks)
|
||||
- **Flexible scoring**: board no longer crashes on any single source failure —
|
||||
`_fetch_with_cache` degrades (returns {} → theme drops that source; previous
|
||||
good value kept as stale by the daily cache). Verified all-sources-down builds
|
||||
13 themes.
|
||||
- **Per-source calc detail**: `symbolDetail.factor_sources` shows, per theme, each
|
||||
factor's source → raw → normalized → weight → contribution (audit trail for the
|
||||
owner to tune weights). Also exposed in `/api/v1/dashboard` as `factor_sources`.
|
||||
- **HAR feasibility (deferred sources)**: captured REIC via `har-derived-api-client`
|
||||
(Playwright drove the JS SPA → HAR → derived XHR `POST /Home/Web_All_Num_View`).
|
||||
Method WORKS and endpoint is derivable, but the homepage XHR returned an empty
|
||||
body — real property data needs a deeper interaction (navigate to a Transfer
|
||||
page and click to load its data). A full REIC collector is a larger follow-up,
|
||||
not a quick add. NBTC's 403 is an IP/fingerprint anti-bot block that HAR replay
|
||||
(plain HTTP) likely canNOT bypass — skip NBTC unless a session/credential exists.
|
||||
|
||||
## REIC deep-dive verdict (2026-08-29 — spike gate result)
|
||||
THOROUGHLY tested via Playwright + HAR:
|
||||
- No reusable JSON XHR — `Web_All_Num_View` returns an **empty body** (status 200,
|
||||
size 0) on both the homepage and the Transfer page.
|
||||
- The homepage shows "โอนกรรมสิทธิ์อสังหาริมทรัพย์ ทั่วประเทศ มิ.ย.69 และ Q2/69" as a
|
||||
**label/link only**, not an inline numeric value.
|
||||
- The actual transfer numbers (17.6% growth, unit counts) live on **login/member-
|
||||
gated detail pages** or JS-rendered charts that don't put the raw number in the
|
||||
DOM without a session.
|
||||
- Transfer sub-page `/Product/Transfer/1/71/1` returns a near-empty body (673B).
|
||||
Verdict: a low-cost REIC collector is **NOT feasible** (would require full
|
||||
Playwright-in-Docker on every refresh + a membership login). Property theme already
|
||||
has `te_property_prices` (TE residential +1.26% YoY) as a clean real source, so
|
||||
REIC is passed on rather than forcing a fragile collector. Recorded for reference.
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Task Breakdown
|
||||
### Task A0 — Feasibility spikes (gate, not build)
|
||||
For each candidate URL, fetch + confirm a stable numeric series parses. Write a throwaway script under `backend/scripts/spike_<source>.py`; record OK/FAIL + exact as_of in the plan log. Only pass a source to A1..A4 if its spike yields a current, non-stale value.
|
||||
- Exit: a table of "source → scrapable? → value → period".
|
||||
|
||||
### Task A1 — BOT rate/loan + credit factors
|
||||
- Add module `backend/app/bot_rates.py` (or extend existing) with Snapshot + `fetch_<x>()` + `.to_dict()`.
|
||||
- Register FACTORS (policy_rate, loan_growth…) + wire into `banks`/`nonbank_finance` THEMES.
|
||||
- Add `_REFRESH_JOBS` row + dashboard cache line.
|
||||
- Tests: parse test (fixture HTML), value-key-resolution, direction test (higher loan growth ⇒ higher banks surprise; higher rate policy ⇒ lower demand).
|
||||
- Verify: full backend suite green; `/api/v1/dashboard` themes show the new factors in `sources`.
|
||||
|
||||
### Task A2 — Household/consumer credit (nonbank_finance)
|
||||
- Same pattern as A1; factor `consumer_credit_yoy` (+1), `consumer_credit_npl` (−1) into `nonbank_finance` (+ maybe banks).
|
||||
- Tests + suite green.
|
||||
|
||||
### Task A3 — Retail sales (retail, consumer_staples)
|
||||
- Collector on TE Thailand retail-sales page; factor `retail_sales_yoy` (+1) into retail + consumer_staples.
|
||||
- Tests + suite green.
|
||||
|
||||
### Task A4 — Consumer confidence (retail, consumer_staples, nonbank_finance)
|
||||
- Collector; factor `consumer_confidence` (+1). Use TE fallback if UTCC is paywalled.
|
||||
- Tests + suite green.
|
||||
|
||||
### Task A5 — Frontend macro chips / theme cards
|
||||
- Add the new read values to `App.vue` theme cards / macro chips (single-colour, no new library, follow existing `theme-read-value` pattern).
|
||||
- `npm run build` green; visual check at 320×568 and 500×768 (mobile single-column).
|
||||
|
||||
### Task B1..B5 — Phase B (only after Phase A accepted)
|
||||
- Same per-source pattern; each with spike, collector, FACTORS+THEME wiring, scheduler row, dashboard cache, tests.
|
||||
|
||||
---
|
||||
|
||||
## Acceptance (definition of done)
|
||||
1. Every new FACTOR appears in ≥1 `THEMES[].factors` and is referenced by dashboard `_build_sources` (auto from registry) — **no source shows in the table without feeding a surprise**.
|
||||
2. `test_every_factor_value_key_resolves_to_a_fetched_field` still passes for every new factor (value_key is a real fetched field).
|
||||
3. Direction tests assert the intended sign for each new factor (e.g. higher loan growth ⇒ higher bank theme score).
|
||||
4. Full backend suite green (was 352) + `npm run build` green.
|
||||
5. Scheduler `_REFRESH_JOBS` + dashboard cache include every new source.
|
||||
6. `/api/v1/dashboard` sources table length tracks FACTORS count; new theme reads appear on the dashboard.
|
||||
|
||||
## Open questions for G0
|
||||
- Priority/order of A1–A4 (recommended order above; user may reorder).
|
||||
- Source substitution if a spike fails: fallback list provided per task.
|
||||
- Should B1–B5 (Phase B) be planned into this same milestone or a separate one after Phase A ships and is reviewed?
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
# SET50 alternative-data platform - single-container image.
|
||||
# Serves: built Vue SPA (frontend/dist) via nginx, proxying /api to the
|
||||
# Flask backend (127.0.0.1:5000). Data persists under /app/backend/data
|
||||
# (mount a volume there or set DATA_DIR to a mounted path).
|
||||
#
|
||||
# Build strategy: PREBUILT frontend dist (no node/npm/vite in this image) —
|
||||
# build with `cd frontend && npm run build` and commit frontend/dist/.
|
||||
FROM python:3.11-slim
|
||||
|
||||
# nginx for serving the SPA
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends nginx \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& rm -f /etc/nginx/sites-enabled/default /etc/nginx/conf.d/default.conf 2>/dev/null || true
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# 1) frontend static (prebuilt) — must exist on-disk (committed)
|
||||
COPY frontend/dist/ ./frontend/dist/
|
||||
|
||||
# 2) backend deps + code
|
||||
COPY backend/requirements.txt ./backend/requirements.txt
|
||||
RUN pip install --no-cache-dir -r backend/requirements.txt
|
||||
COPY backend/ ./backend/
|
||||
|
||||
# 3) deploy config (nginx conf + entrypoint)
|
||||
COPY deploy/nginx.conf /etc/nginx/conf.d/set50.conf
|
||||
COPY deploy/entrypoint.sh /usr/local/bin/entrypoint.sh
|
||||
RUN chmod +x /usr/local/bin/entrypoint.sh
|
||||
|
||||
# persistent data (factor vintages, dividend ledger, forward runs, prices)
|
||||
ENV DATA_DIR=/app/backend/data
|
||||
ENV HOST=0.0.0.0
|
||||
ENV PORT=5000
|
||||
VOLUME ["/app/backend/data"]
|
||||
|
||||
EXPOSE 80
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||
CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1/api/v1/dashboard/summary', timeout=4).status==200 else 1)"
|
||||
|
||||
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
|
||||
@@ -20,7 +20,7 @@ No external webhook receiver and no live MT5 execution are enabled.
|
||||
```bash
|
||||
python -m venv .venv
|
||||
.venv/bin/pip install -r backend/requirements.txt
|
||||
PAPER_WRITE_TOKEN=local-paper-token TOURISM_SOURCE=fixture PYTHONPATH=backend .venv/bin/python backend/run.py
|
||||
PAPER_AUTH_MODE=demo HOST=127.0.0.1 TOURISM_SOURCE=fixture PYTHONPATH=backend .venv/bin/python backend/run.py
|
||||
```
|
||||
|
||||
Health check:
|
||||
@@ -41,18 +41,20 @@ npm run dev -- --host 127.0.0.1
|
||||
|
||||
Open `http://127.0.0.1:5173`.
|
||||
|
||||
The frontend reads the live API through Vite's `/api` proxy. Paper writes require the operator to unlock an HttpOnly browser session using the backend `PAPER_WRITE_TOKEN`; the token is never embedded in the frontend bundle. The paper-entry action records an assumed fill in the local paper ledger only; it never sends an order.
|
||||
The frontend reads the live API through Vite's `/api` proxy. The local command above uses explicit loopback-only `PAPER_AUTH_MODE=demo`: paper writes do not require a session token, and the dashboard shows a demo warning. This mode is for a single local operator only; it must not be bound to a network interface or used for live execution. For shared or network access, use `PAPER_AUTH_MODE=token`, set `PAPER_WRITE_TOKEN` in the server environment, and require the HttpOnly browser session; the token is never embedded in the frontend bundle. The paper-entry action records an assumed fill in the local paper ledger only; it never sends an order.
|
||||
|
||||
For HTTPS/non-local deployment, set `PAPER_COOKIE_SECURE=1`. Paper entries persist atomically under `backend/data/paper/ledger.json` by default. Sessions remain in-memory and single-process; use a shared session store before running multiple workers or replicas.
|
||||
For HTTPS/non-local deployment, use protected token mode and set `PAPER_COOKIE_SECURE=1`. Paper entries persist atomically under `backend/data/paper/ledger.json` by default. Sessions remain in-memory and single-process; use a shared session store before running multiple workers or replicas.
|
||||
|
||||
## Run with the real BOT Tourism source
|
||||
|
||||
Use the BOT-backed adapter when network access is available:
|
||||
|
||||
```bash
|
||||
PAPER_WRITE_TOKEN=local-paper-token TOURISM_SOURCE=bot PYTHONPATH=backend .venv/bin/python backend/run.py
|
||||
PAPER_AUTH_MODE=demo HOST=127.0.0.1 TOURISM_SOURCE=bot PYTHONPATH=backend .venv/bin/python backend/run.py
|
||||
```
|
||||
|
||||
For a shared/network BOT deployment, replace `PAPER_AUTH_MODE=demo` with `PAPER_AUTH_MODE=token` and provide `PAPER_WRITE_TOKEN` through the server environment. The backend rejects demo mode when `HOST`/`PAPER_BIND_HOST` is not loopback.
|
||||
|
||||
At startup the adapter performs a read-only GET/POST against the BOT Tourism Indicators report, parses the available monthly history, computes the latest year-over-year arrival observation against a trailing 12-point baseline, and stores the raw HTML plus normalized snapshot under `backend/data/` (ignored by git). The dashboard labels provisional BOT data as `provisional`, not `high`.
|
||||
|
||||
Data-health and replay endpoints:
|
||||
@@ -107,10 +109,12 @@ cd frontend && npm run build
|
||||
- No webhook receiver yet
|
||||
- No MT5 bridge yet
|
||||
|
||||
The next implementation step is replacing or supplementing revised vendor history with a point-in-time daily price source, while continuing to collect independent BOT releases.
|
||||
The PIT archive contract is implemented, but a real provider archive and release-time evidence are still required. Continue collecting independent BOT releases and do not promote revised vendor history by configuration alone.
|
||||
|
||||
The event-study gate is now exposed through `/api/v1/backtest/tourism`. It returns HTTP `409` with `status=blocked` when the independent-vintage minimum is not met, and it explicitly reports that a point-in-time daily price series is still required. The pure engine accepts events, daily prices, benchmark prices, event windows, and cost assumptions; it does not fetch or invent market prices.
|
||||
|
||||
The accepted PIT contract is `pit-daily-v1`. It requires explicit provider release/evidence metadata, an IANA market timezone per series, timezone-aware per-bar `session_date`/`known_at`/OHLC/adjusted-close/volume, and immutable raw/normalized/manifest hash binding. PIT event-study mode rejects missing or market-locally future-known prices. The current Yahoo collector intentionally remains `quality=revised_vendor_history` and `point_in_time=false`.
|
||||
|
||||
## Run a frozen research check
|
||||
|
||||
The research runner persists either a deterministic event-study result or a blocked report. A blocked report is still useful: it records the exact vintage IDs, hashes, price snapshot, configuration, and gate reason that prevented the study.
|
||||
@@ -135,6 +139,15 @@ GET /api/v1/research/tourism/latest
|
||||
|
||||
The default live state intentionally returns `status=blocked`: the current archive has one independent BOT release and the Yahoo price snapshot is marked `point_in_time=false`. The runner never converts that data into a backtest by inference.
|
||||
|
||||
Research reports written before integrity hashes were introduced are intentionally not auto-migrated. Migrate a trusted local research store explicitly before loading it:
|
||||
|
||||
```bash
|
||||
PYTHONPATH=backend .venv/bin/python backend/scripts/migrate_research_report_hashes.py \
|
||||
--root backend/data/research
|
||||
```
|
||||
|
||||
The migration validates report identity and manifest metadata, writes the canonical report and manifest-entry hashes, and fails closed on malformed or partially migrated entries.
|
||||
|
||||
## Collect daily price snapshots
|
||||
|
||||
The initial research price provider uses Yahoo Finance Chart API with SET ticker mappings. It stores OHLCV plus adjusted close for the eight exposure names and `^SET.BK` as `SET50`. This is **revised vendor history**, not point-in-time market data, so the snapshot is visible for data plumbing but cannot unlock the backtest gate:
|
||||
|
||||
+196
-113
@@ -142,14 +142,14 @@ def create_app(config: dict[str, Any] | None = None) -> Flask:
|
||||
app.extensions["paper_ledger"] = ledger
|
||||
app.extensions["paper_sessions"] = paper_sessions
|
||||
app.extensions["allowed_symbols"] = allowed_symbols
|
||||
from .forward_test import ForwardTestStore
|
||||
app.extensions["forward_store"] = ForwardTestStore(
|
||||
app.config.get("FORWARD_STORE_PATH") or (data_root / "forward" / "runs.json")
|
||||
)
|
||||
from .dividend_ledger import DividendLedger
|
||||
app.extensions["dividend_ledger"] = DividendLedger(
|
||||
app.config.get("DIVIDEND_LEDGER_PATH") or (data_root / "dividends" / "ledger.json")
|
||||
)
|
||||
from .backtest_store import BacktestStore
|
||||
app.extensions["backtest_store"] = BacktestStore(
|
||||
app.config.get("BACKTEST_STORE_PATH") or (data_root / "backtest" / "runs.json")
|
||||
)
|
||||
|
||||
# shared in-process daily cache + app-internal data scheduler (independent of
|
||||
# Hermes — this app runs on its own server).
|
||||
@@ -159,7 +159,10 @@ def create_app(config: dict[str, Any] | None = None) -> Flask:
|
||||
app.extensions["daily_cache"] = cache
|
||||
if not app.config.get("TESTING"):
|
||||
interval_s = int(os.getenv("REFRESH_INTERVAL_SECONDS", "3600"))
|
||||
scheduler = AppDataScheduler(cache, Path(__file__).resolve().parents[1] / "data", interval_seconds=interval_s)
|
||||
div_cooldown_s = int(os.getenv("DIVIDEND_REFRESH_COOLDOWN_SECONDS", str(6 * 3600)))
|
||||
scheduler = AppDataScheduler(cache, Path(__file__).resolve().parents[1] / "data",
|
||||
interval_seconds=interval_s,
|
||||
dividend_cooldown_seconds=div_cooldown_s)
|
||||
scheduler.start()
|
||||
app.extensions["data_scheduler"] = scheduler
|
||||
|
||||
@@ -605,16 +608,17 @@ def create_app(config: dict[str, Any] | None = None) -> Flask:
|
||||
)
|
||||
|
||||
|
||||
@app.route("/api/v1/simulation", methods=["POST"])
|
||||
def simulation():
|
||||
"""Capital-allocation simulation (paper/backtest; never a real order).
|
||||
@app.route("/api/v1/suggestion", methods=["POST"])
|
||||
def suggestion():
|
||||
"""Capital-allocation suggestion (non-PIT live recommendation; paper).
|
||||
|
||||
Body: {capital: float, mode: "backtest"|"forward"}.
|
||||
Body: {capital: float}.
|
||||
Uses the SAME canonical combined score as /api/v1/dashboard (via
|
||||
`default_scores`) — not a separate 3-theme recompute — so the "จำลอง"
|
||||
allocation can never disagree with the board on which names rank highest.
|
||||
Prices come from the latest Yahoo snapshot; allocation uses the 50/20/30
|
||||
dividend buckets. Output is paper/backtest on revised history (non-PIT).
|
||||
`default_scores`) — not a separate 3-theme recompute — so the "จัดสรรทุน"
|
||||
(suggestion) can never disagree with the board on which names rank
|
||||
highest. Prices come from the latest Yahoo snapshot; allocation uses the
|
||||
50/20/30 dividend buckets. This is a live recommendation on current
|
||||
data (non-PIT), never a real order.
|
||||
"""
|
||||
from app import simulation as sim
|
||||
|
||||
@@ -623,7 +627,6 @@ def create_app(config: dict[str, Any] | None = None) -> Flask:
|
||||
capital = float(payload.get("capital", 0))
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({"error": "capital must be a number"}), 400
|
||||
mode = payload.get("mode", "backtest") in ("backtest", "forward") and payload.get("mode", "backtest")
|
||||
if capital <= 0:
|
||||
return jsonify({"error": "capital must be > 0"}), 400
|
||||
|
||||
@@ -642,6 +645,31 @@ def create_app(config: dict[str, Any] | None = None) -> Flask:
|
||||
# No collector detail in the response (avoid leaking internal state).
|
||||
return jsonify({"error": "dashboard scores unavailable"}), 503
|
||||
|
||||
# Owner's "ทำกำไร" = price likely to rise in 3-6 months -> price-trend
|
||||
# momentum (NOT EPS growth). theme_signal = mean surprise of the themes a
|
||||
# symbol belongs to; buckets 1/2 require theme_signal > 0.
|
||||
try:
|
||||
from app import themes as _th
|
||||
trend = _th.price_trend_score(series)
|
||||
except Exception:
|
||||
trend = {}
|
||||
theme_sig_by_sym: dict[str, float] = {}
|
||||
try:
|
||||
from app.dashboard import RealDashboard
|
||||
from app import daily_cache as _dc
|
||||
_cache = app.extensions.setdefault("daily_cache", _dc.DailyCache())
|
||||
dash = RealDashboard((app.extensions.get("tourism_result") or {}).get("signals", []), _cache).build()
|
||||
except Exception:
|
||||
dash = {}
|
||||
theme_surprises = {t.get("id"): t.get("surprise") for t in dash.get("themes", [])}
|
||||
board_by_sym = {r.get("symbol"): r for r in dash.get("board", [])}
|
||||
for sym in score_by_symbol:
|
||||
ths = [s for s in (board_by_sym.get(sym, {}).get("themes") or [])
|
||||
if theme_surprises.get(s) is not None]
|
||||
theme_sig_by_sym[sym] = (
|
||||
(sum(theme_surprises[s] for s in ths) / len(ths)) if ths else 0.0
|
||||
)
|
||||
|
||||
candidates = []
|
||||
for sym, meta in score_by_symbol.items():
|
||||
price = prices.get(sym)
|
||||
@@ -654,6 +682,8 @@ def create_app(config: dict[str, Any] | None = None) -> Flask:
|
||||
combined_score=meta.get("combined", 0.0),
|
||||
is_dividend=bool(meta.get("is_dividend")),
|
||||
dividend_yield=float(meta.get("dividend_yield") or 0.0),
|
||||
momentum=float(trend.get(sym, 0.0)),
|
||||
theme_signal=float(theme_sig_by_sym.get(sym, 0.0)),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -666,10 +696,10 @@ def create_app(config: dict[str, Any] | None = None) -> Flask:
|
||||
current = app.extensions.get("tourism_result") or {}
|
||||
return jsonify(
|
||||
{
|
||||
"mode": mode,
|
||||
"mode": "suggestion",
|
||||
"capital": capital,
|
||||
"as_of": current.get("as_of"),
|
||||
"data_note": "paper/backtest on revised vendor history (non-PIT) — not validated evidence",
|
||||
"data_note": "suggestion on current board (non-PIT) — not validated evidence",
|
||||
**result.to_dict(),
|
||||
}
|
||||
)
|
||||
@@ -714,6 +744,7 @@ def create_app(config: dict[str, Any] | None = None) -> Flask:
|
||||
from app import daily_cache
|
||||
cache = app.extensions.setdefault("daily_cache", daily_cache.DailyCache())
|
||||
current = app.extensions.get("tourism_result")
|
||||
dash = {}
|
||||
try:
|
||||
dash = RealDashboard((current or {}).get("signals", []), cache).build()
|
||||
theme_surprises = {t["id"]: t.get("surprise") for t in dash.get("themes", [])}
|
||||
@@ -735,8 +766,157 @@ def create_app(config: dict[str, Any] | None = None) -> Flask:
|
||||
latest_price=price, price_date=price_date,
|
||||
momentum=themes_mod._load_momentum(),
|
||||
)
|
||||
# per-source factor-level audit: for each theme this symbol belongs to,
|
||||
# show source -> raw -> normalized -> weight -> contribution so the owner
|
||||
# sees exactly how each source scored and how the weights were applied.
|
||||
fetch_data = dash.get("fetch_data", {})
|
||||
detail["factor_sources"] = {
|
||||
tid: themes_mod.factor_source_breakdown(fetch_data, tid)
|
||||
for tid in detail.get("themes", [])
|
||||
}
|
||||
# fallback: if the dashboard fetch was empty (degraded), rebuild it once
|
||||
if not fetch_data:
|
||||
try:
|
||||
from app import daily_cache as _dc
|
||||
cache2 = _dc.DailyCache()
|
||||
dash2 = RealDashboard((current or {}).get("signals", []), cache2).build()
|
||||
fetch_data2 = dash2.get("fetch_data", {})
|
||||
detail["factor_sources"] = {
|
||||
tid: themes_mod.factor_source_breakdown(fetch_data2, tid)
|
||||
for tid in detail.get("themes", [])
|
||||
}
|
||||
except Exception:
|
||||
pass
|
||||
return jsonify(detail)
|
||||
|
||||
@app.get("/api/v1/backtest/readiness")
|
||||
def backtest_readiness_endpoint():
|
||||
"""Strict PIT backtest readiness + recommended default dates.
|
||||
|
||||
The backtest must not start before advice is genuinely available. This
|
||||
endpoint reports whether the PIT stores (factor vintages + Siamchart
|
||||
vintage manifest) plus price data cover any usable [start, end] window,
|
||||
and returns the recommended default start/end the UI should prefill.
|
||||
It fails closed (ready=false + missing list) when coverage is absent.
|
||||
"""
|
||||
from pathlib import Path as _Path
|
||||
from .backtest_readiness import evaluate_readiness
|
||||
from .factor_vintages import FactorVintageStore
|
||||
from .siamchart_vintages import SiamchartVintageStore
|
||||
from .simulation import load_price_snapshot, SimulationError
|
||||
|
||||
data_root = _Path(__file__).resolve().parents[1] / "data"
|
||||
fstore = FactorVintageStore(data_root)
|
||||
sstore = SiamchartVintageStore(data_root)
|
||||
try:
|
||||
series = load_price_snapshot()
|
||||
except SimulationError:
|
||||
series = None
|
||||
start = request.args.get("start")
|
||||
end = request.args.get("end")
|
||||
res = evaluate_readiness(
|
||||
factor_store=fstore, siamchart_store=sstore,
|
||||
price_series=series, start=start, end=end,
|
||||
)
|
||||
return jsonify(res.to_dict())
|
||||
|
||||
@app.post("/api/v1/backtest/run")
|
||||
def backtest_run_endpoint():
|
||||
"""Run a strict, event-driven PIT backtest and persist the result.
|
||||
|
||||
Fails closed on readiness: if the requested window (or the derived
|
||||
default window) is not fully PIT-covered, returns 400 listing the
|
||||
missing inputs rather than fabricating an invalid run.
|
||||
"""
|
||||
from .backtest_readiness import evaluate_readiness
|
||||
from .backtest_engine import run_event_backtest
|
||||
from .factor_vintages import FactorVintageStore
|
||||
from .siamchart_vintages import SiamchartVintageStore
|
||||
from .simulation import load_price_snapshot
|
||||
from .pit_scorer import PitScoreProvider, make_pit_score_fn
|
||||
from pathlib import Path as _Path
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
data_root = _Path(__file__).resolve().parents[1] / "data"
|
||||
fstore = FactorVintageStore(data_root)
|
||||
sstore = SiamchartVintageStore(data_root)
|
||||
price_series = load_price_snapshot()
|
||||
|
||||
# readiness gate (starts below fail closed)
|
||||
start = body.get("start")
|
||||
end = body.get("end")
|
||||
ready = evaluate_readiness(
|
||||
factor_store=fstore, siamchart_store=sstore,
|
||||
price_series=price_series, start=start, end=end,
|
||||
)
|
||||
if not ready.ready:
|
||||
return jsonify({
|
||||
"error": "not enough PIT coverage for this backtest window",
|
||||
"missing": ready.missing,
|
||||
"recommended_start": ready.recommended_start,
|
||||
"recommended_end": ready.recommended_end,
|
||||
"coverage": ready.coverage,
|
||||
}), 400
|
||||
start = start or ready.recommended_start
|
||||
end = end or ready.recommended_end
|
||||
assert start is not None and end is not None # readiness guarantees this
|
||||
capital = float(body.get("capital") or 1_000_000)
|
||||
|
||||
# seed siamchart vintage baseline + PIT scorer
|
||||
_seed_siamchart_vintage(sstore)
|
||||
provider = PitScoreProvider(fstore, _load_siamchart_snapshot(),
|
||||
siamchart_store=sstore)
|
||||
score_fn = make_pit_score_fn(provider)
|
||||
|
||||
use_ledger = bool(body.get("use_ledger"))
|
||||
ledger = None
|
||||
if use_ledger:
|
||||
stored = app.extensions.get("dividend_ledger")
|
||||
if stored is not None and stored.symbols():
|
||||
ledger = stored
|
||||
else:
|
||||
from .dividend_ledger import build_dps_ledger
|
||||
ledger = build_dps_ledger(_load_siamchart_snapshot())
|
||||
|
||||
res = run_event_backtest(
|
||||
start=start, end=end, capital=capital,
|
||||
factor_store=fstore, siamchart_store=sstore,
|
||||
dividend_ledger=ledger, price_series=price_series,
|
||||
score_fn=score_fn,
|
||||
)
|
||||
record = res.to_dict()
|
||||
record["use_ledger"] = use_ledger
|
||||
persisted = app.extensions["backtest_store"].add(record)
|
||||
return jsonify(persisted), 201
|
||||
|
||||
@app.get("/api/v1/backtest/run/<run_id>")
|
||||
def backtest_run_get(run_id: str):
|
||||
store = app.extensions["backtest_store"]
|
||||
rec = store.get(run_id)
|
||||
if rec is None:
|
||||
return jsonify({"error": "run not found"}), 404
|
||||
return jsonify(rec)
|
||||
|
||||
@app.get("/api/v1/backtest/run")
|
||||
def backtest_runs_direct():
|
||||
store = app.extensions["backtest_store"]
|
||||
return jsonify({"runs": store.all()})
|
||||
|
||||
@app.get("/api/v1/scheduler/sources")
|
||||
def scheduler_sources():
|
||||
"""Source-health log for the data scheduler (refresh cadence + failures).
|
||||
|
||||
Lets the frontend show each source's last outcome and copy the failure
|
||||
detail for diagnosis (e.g. a source that changed its page structure is
|
||||
categorized as `structure`, a network blip as `network`). Empty when no
|
||||
scheduler is wired (e.g. TESTING or a read-only host) or no tick yet.
|
||||
"""
|
||||
sched = app.extensions.get("data_scheduler")
|
||||
if sched is None:
|
||||
return jsonify({"sources": []})
|
||||
limit = int(request.args.get("limit", "200"))
|
||||
return jsonify({"sources": sched._load_source_health(limit)})
|
||||
|
||||
@app.post("/api/v1/backtest")
|
||||
def run_backtest_endpoint():
|
||||
"""Run a real backtest over [start, end] with capital; persist result."""
|
||||
@@ -796,103 +976,6 @@ def create_app(config: dict[str, Any] | None = None) -> Flask:
|
||||
runs = app.extensions.get("backtest_runs", [])
|
||||
return jsonify({"runs": runs})
|
||||
|
||||
@app.get("/api/v1/forward")
|
||||
def forward_list():
|
||||
"""List all durable forward-test runs (real lifecycle, not cosmetic)."""
|
||||
store = app.extensions["forward_store"]
|
||||
return jsonify({"runs": store.list()})
|
||||
|
||||
@app.get("/api/v1/forward/<run_id>")
|
||||
def forward_get(run_id: str):
|
||||
store = app.extensions["forward_store"]
|
||||
run = store.get(run_id)
|
||||
if run is None:
|
||||
return jsonify({"error": "unknown forward run"}), 404
|
||||
return jsonify(run)
|
||||
|
||||
@app.post("/api/v1/forward")
|
||||
def forward_create():
|
||||
"""CREATE + EXECUTE a forward run with frozen signals.
|
||||
|
||||
Body: {capital, use_pit: bool, as_of: "YYYY-MM-DD"}.
|
||||
Freezes the current (or PIT-as-of) combined per-symbol scores and fills
|
||||
the 50/20/30 buckets at post-freeze prices. The score set is immutable
|
||||
from this point (a real frozen-signal lifecycle).
|
||||
"""
|
||||
from .forward_test import ForwardError
|
||||
store = app.extensions["forward_store"]
|
||||
body = request.get_json(silent=True) or {}
|
||||
try:
|
||||
capital = float(body.get("capital", 0))
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({"error": "capital must be a number"}), 400
|
||||
if capital <= 0:
|
||||
return jsonify({"error": "capital must be > 0"}), 400
|
||||
use_pit = bool(body.get("use_pit"))
|
||||
as_of = body.get("as_of")
|
||||
try:
|
||||
from app import simulation as sim
|
||||
series = sim.load_price_snapshot()
|
||||
prices = sim.latest_prices(series)
|
||||
if use_pit:
|
||||
from .pit_scorer import PitScoreProvider, make_pit_score_fn
|
||||
from .factor_vintages import FactorVintageStore
|
||||
from .siamchart_vintages import SiamchartVintageStore
|
||||
froot = Path(__file__).resolve().parents[1] / "data"
|
||||
sstore = SiamchartVintageStore(froot)
|
||||
_seed_siamchart_vintage(sstore)
|
||||
provider = PitScoreProvider(FactorVintageStore(froot),
|
||||
_load_siamchart_snapshot(),
|
||||
siamchart_store=sstore)
|
||||
score_fn = make_pit_score_fn(provider)
|
||||
score_by_symbol = score_fn(symbols=[], as_of=as_of) or {}
|
||||
non_pit = not any(
|
||||
isinstance(m, dict) and isinstance(m.get("pit_meta"), dict)
|
||||
and bool(m.get("pit_meta", {}).get("pit"))
|
||||
for m in score_by_symbol.values()
|
||||
)
|
||||
else:
|
||||
from .dashboard import default_scores
|
||||
score_by_symbol = default_scores(None) or {}
|
||||
non_pit = True
|
||||
frozen = {}
|
||||
for sym, meta in (score_by_symbol or {}).items():
|
||||
if sym in prices:
|
||||
frozen[sym] = {
|
||||
"combined": float(meta.get("combined", 0.0)),
|
||||
"is_dividend": bool(meta.get("is_dividend")),
|
||||
"dividend_yield": float(meta.get("dividend_yield") or 0.0),
|
||||
}
|
||||
run = store.create(capital, frozen, as_of=as_of or "now", non_pit=non_pit)
|
||||
executed = store.execute(run["id"], prices)
|
||||
return jsonify(executed), 201
|
||||
except (ForwardError, sim.SimulationError, OSError) as exc:
|
||||
return jsonify({"error": str(exc)}), 400
|
||||
|
||||
@app.post("/api/v1/forward/<run_id>/mark")
|
||||
def forward_mark(run_id: str):
|
||||
from .forward_test import ForwardError
|
||||
from app import simulation as sim
|
||||
store = app.extensions["forward_store"]
|
||||
try:
|
||||
series = sim.load_price_snapshot()
|
||||
prices = sim.latest_prices(series)
|
||||
return jsonify(store.mark(run_id, prices))
|
||||
except (ForwardError, sim.SimulationError, OSError) as exc:
|
||||
return jsonify({"error": str(exc)}), 400
|
||||
|
||||
@app.post("/api/v1/forward/<run_id>/mature")
|
||||
def forward_mature(run_id: str):
|
||||
from .forward_test import ForwardError
|
||||
from app import simulation as sim
|
||||
store = app.extensions["forward_store"]
|
||||
try:
|
||||
series = sim.load_price_snapshot()
|
||||
prices = sim.latest_prices(series)
|
||||
return jsonify(store.mature(run_id, prices))
|
||||
except (ForwardError, sim.SimulationError, OSError) as exc:
|
||||
return jsonify({"error": str(exc)}), 400
|
||||
|
||||
@app.post("/api/v1/dividends/update")
|
||||
def dividends_update():
|
||||
"""Fetch real dated dividend history for every snapshot symbol and
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
"""Event-driven PIT backtest engine (Task 5).
|
||||
|
||||
Replaces the calendar-rebalance loop with a strict point-in-time event
|
||||
processor. It consumes the unified event calendar (Task 2), the portfolio
|
||||
ledger (Task 3), and the lot/cash rebalancer (Task 4) to simulate exactly the
|
||||
user-described lifecycle:
|
||||
|
||||
1. An initial signal is frozen at the run start (advice knows only what was
|
||||
released by then), and executed at the next trading day.
|
||||
2. Each new data release freezes a new signal; if the target changes, the
|
||||
portfolio is rebalanced on the next trading day after the release.
|
||||
3. Dividends are entitled on ex-date (shares held before it) and their cash
|
||||
becomes available exactly 30 calendar days later, funding later buys.
|
||||
4. Sales realize P&L (average cost, minus a 0.3% all-in fee) and free up cash
|
||||
before subsequent buys.
|
||||
5. At the end date the portfolio is marked to market and every P&L component
|
||||
is reported and reconciled.
|
||||
|
||||
Every score is computed with only data knowable at the release timestamp
|
||||
(``score_fn(symbols, as_of)``): if the supplied scorer is PIT-aware and returns
|
||||
``pit_meta`` proving it, ``leakage_guard`` is True; otherwise it is False.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
from .backtest_events import (
|
||||
DIVIDEND_PAYMENT_LAG_DAYS,
|
||||
DividendEntitlementEvent,
|
||||
DividendPaymentEvent,
|
||||
EndValuationEvent,
|
||||
SignalReleaseEvent,
|
||||
_date_from_ts,
|
||||
build_event_calendar,
|
||||
next_trading_day,
|
||||
)
|
||||
from .portfolio_ledger import PortfolioLedger
|
||||
from .portfolio_rebalancer import PortfolioRebalancer, build_candidates
|
||||
|
||||
|
||||
@dataclass
|
||||
class EventBacktestResult:
|
||||
start: str
|
||||
end: str
|
||||
capital: float
|
||||
ledger: Optional[PortfolioLedger] = None
|
||||
leakage_guard: bool = False
|
||||
rebalances: int = 0
|
||||
events: list = field(default_factory=list)
|
||||
# summary fields (filled by to_dict)
|
||||
ending_cash: float = 0.0
|
||||
ending_market_value: float = 0.0
|
||||
final_equity: float = 0.0
|
||||
realized_trading_pnl: float = 0.0
|
||||
unrealized_trading_pnl: float = 0.0
|
||||
price_pnl: float = 0.0
|
||||
dividend_cash_received: float = 0.0
|
||||
dividend_receivable: float = 0.0
|
||||
transaction_costs: float = 0.0
|
||||
net_return: float = 0.0
|
||||
account_reconciled: bool = False
|
||||
_final_prices: dict = field(default_factory=dict, repr=False)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
prices = self._final_prices or {}
|
||||
rec = self.ledger.reconcile(prices) if self.ledger else {}
|
||||
holdings = [
|
||||
{
|
||||
"symbol": p.symbol, "qty": p.qty,
|
||||
"average_cost": round(p.average_cost, 4),
|
||||
"last_price": round(prices.get(p.symbol, 0.0), 4),
|
||||
"market_value": round(p.qty * prices.get(p.symbol, 0.0), 2),
|
||||
"unrealized_pnl": round(p.qty * (prices.get(p.symbol, 0.0) - p.average_cost), 2),
|
||||
}
|
||||
for p in (self.ledger.positions() if self.ledger else [])
|
||||
]
|
||||
return {
|
||||
"start": self.start, "end": self.end,
|
||||
"capital": self.capital,
|
||||
"ending_cash": round(self.ending_cash, 2),
|
||||
"ending_market_value": round(self.ending_market_value, 2),
|
||||
"dividend_receivable": round(self.dividend_receivable, 2),
|
||||
"final_equity": round(self.final_equity, 2),
|
||||
"net_change": round(self.final_equity - self.capital, 2),
|
||||
"net_return": round(self.net_return, 4),
|
||||
"realized_trading_pnl": round(self.realized_trading_pnl, 2),
|
||||
"unrealized_trading_pnl": round(self.unrealized_trading_pnl, 2),
|
||||
"price_pnl": round(self.price_pnl, 2),
|
||||
"dividend_cash_received": round(self.dividend_cash_received, 2),
|
||||
"transaction_costs": round(self.transaction_costs, 2),
|
||||
"fee_rate": 0.003,
|
||||
"dividend_timing": "ex_date_plus_30d",
|
||||
"holdings": holdings,
|
||||
"trades": [t.to_dict() for t in (self.ledger.state.trades if self.ledger else [])],
|
||||
"dividends": (self.ledger.state.dividends if self.ledger else []),
|
||||
"rebalances": self.rebalances,
|
||||
"leakage_guard": self.leakage_guard,
|
||||
"accounting_reconciled": self.account_reconciled,
|
||||
# compatibility aliases for the existing UI/API
|
||||
"final_value": round(self.final_equity, 2),
|
||||
"dividend_income": round(self.dividend_cash_received, 2),
|
||||
"dividend_method": "dated_ledger",
|
||||
"holdings_map": {p.symbol: p.qty for p in (self.ledger.positions() if self.ledger else [])},
|
||||
}
|
||||
|
||||
|
||||
def _latest_close(series: dict, sym: str, date: dt.date) -> Optional[float]:
|
||||
bars = (series.get(sym) or {}).get("bars", [])
|
||||
chosen = None
|
||||
for b in bars:
|
||||
d = str(b.get("date") or "")[:10]
|
||||
try:
|
||||
bd = dt.date.fromisoformat(d)
|
||||
except ValueError:
|
||||
continue
|
||||
if bd <= date:
|
||||
chosen = b.get("adjusted_close")
|
||||
return float(chosen) if chosen is not None else None
|
||||
|
||||
|
||||
def run_event_backtest(
|
||||
*,
|
||||
start: str,
|
||||
end: str,
|
||||
capital: float = 1_000_000,
|
||||
factor_store: Any = None,
|
||||
siamchart_store: Any = None,
|
||||
dividend_ledger: Any = None,
|
||||
price_series: dict | None = None,
|
||||
score_fn: Optional[Callable] = None,
|
||||
symbols: Optional[list[str]] = None,
|
||||
) -> EventBacktestResult:
|
||||
"""Run the event-driven PIT backtest over [start, end]."""
|
||||
from .simulation import load_price_snapshot
|
||||
if price_series is None:
|
||||
price_series = load_price_snapshot()
|
||||
if not price_series:
|
||||
raise ValueError("no price data for backtest")
|
||||
|
||||
ledger = PortfolioLedger(capital)
|
||||
result = EventBacktestResult(start=start, end=end, capital=float(capital))
|
||||
result.ledger = ledger
|
||||
|
||||
s_date = dt.date.fromisoformat(start)
|
||||
e_date = dt.date.fromisoformat(end)
|
||||
|
||||
# Build the event timeline.
|
||||
calendar = build_event_calendar(
|
||||
factor_store=factor_store,
|
||||
siamchart_store=siamchart_store,
|
||||
dividend_ledger=dividend_ledger,
|
||||
start=start, end=end,
|
||||
)
|
||||
|
||||
# Collect signal releases (chronological) and pair each to an execution.
|
||||
signal_events = [ev for ev in calendar if isinstance(ev, SignalReleaseEvent)]
|
||||
# ensure an initial signal at the start so the first allocation happens
|
||||
init_signal = SignalReleaseEvent(released_at=start + "T00:00:00+07:00")
|
||||
all_signals = [init_signal] + signal_events
|
||||
|
||||
# Map each signal to its next trading day.
|
||||
exec_map: dict[dt.date, SignalReleaseEvent] = {}
|
||||
for sig in all_signals:
|
||||
nxt = next_trading_day(price_series, sig.date)
|
||||
if nxt is None:
|
||||
continue
|
||||
if nxt > e_date:
|
||||
continue
|
||||
# if multiple signals map to the same execution day, keep the latest
|
||||
exec_map[nxt] = sig
|
||||
|
||||
# Also collect dividend events from the calendar with their own ordering.
|
||||
dividend_events = [
|
||||
ev for ev in calendar
|
||||
if isinstance(ev, (DividendEntitlementEvent, DividendPaymentEvent))
|
||||
]
|
||||
|
||||
# Merge all dated actions into one timeline.
|
||||
# Each day holds a list of (action, payload) where action is one of
|
||||
# "rebalance", "dividend_entitlement", "dividend_payment".
|
||||
#
|
||||
# Within a day, actions must run in a market-correct order that honours the
|
||||
# invariants:
|
||||
# 1) dividend_entitlement BEFORE rebalance — an entitlement is captured
|
||||
# from the position held *before* that day's trades, so shares acquired
|
||||
# on the ex-date do NOT qualify (confirmed invariant #4);
|
||||
# 2) dividend_payment BEFORE rebalance — cash that settles on this day is
|
||||
# available to fund that day's buys;
|
||||
# 3) rebalance last.
|
||||
# We sort each day's actions by this priority rather than trusting insertion
|
||||
# order.
|
||||
_ORDER = {"dividend_entitlement": 0, "dividend_payment": 1, "rebalance": 2}
|
||||
timeline: dict[dt.date, list[tuple[str, Any]]] = {}
|
||||
for ev in dividend_events:
|
||||
timeline.setdefault(ev.date, []).append((ev.kind, ev))
|
||||
for exec_day, sig in exec_map.items():
|
||||
timeline.setdefault(exec_day, []).append(("rebalance", sig))
|
||||
for day in list(timeline.keys()):
|
||||
timeline[day].sort(key=lambda pair: _ORDER.get(pair[0], 3))
|
||||
|
||||
last_scores: dict = {}
|
||||
leakage_guard = False
|
||||
|
||||
def freeze_scores(sig: SignalReleaseEvent) -> None:
|
||||
nonlocal last_scores, leakage_guard
|
||||
as_of = sig.released_at
|
||||
syms = symbols or list(price_series.keys())
|
||||
if score_fn is None:
|
||||
# Strict event-driven mode must never fall back to the live board:
|
||||
# default_scores() builds the CURRENT board with no as_of handling,
|
||||
# so freezing it at a historical release would be look-ahead even
|
||||
# though it does not set leakage_guard. Fail closed instead.
|
||||
raise ValueError(
|
||||
"strict event-driven backtest requires a PIT score_fn; "
|
||||
"refusing to fall back to the live (non-PIT) board"
|
||||
)
|
||||
sc = score_fn(syms, as_of) or {}
|
||||
# leakage_guard only when the scores attest PIT provenance
|
||||
any_pit = any(
|
||||
isinstance(m, dict) and isinstance(m.get("pit_meta"), dict)
|
||||
and bool(m.get("pit_meta", {}).get("pit"))
|
||||
for m in sc.values()
|
||||
)
|
||||
if any_pit:
|
||||
leakage_guard = True
|
||||
last_scores = sc
|
||||
|
||||
def execute_rebalance(exec_day: dt.date, sig: SignalReleaseEvent) -> None:
|
||||
nonlocal result
|
||||
cands = build_candidates(last_scores, price_series, exec_day)
|
||||
if not cands:
|
||||
return
|
||||
rb = PortfolioRebalancer(ledger, price_series, cands)
|
||||
r = rb.rebalance(date=exec_day, signal_date=sig.date)
|
||||
result.rebalances += 1
|
||||
result.events.append({
|
||||
"type": "rebalance", "signal_date": sig.date.isoformat(),
|
||||
"execution_date": exec_day.isoformat(),
|
||||
"trades": len(r.trades), "notes": r.notes,
|
||||
})
|
||||
|
||||
# ---------- process timeline ----------
|
||||
for day in sorted(timeline.keys()):
|
||||
for action, payload in timeline[day]:
|
||||
if action == "rebalance":
|
||||
sig = payload # SignalReleaseEvent
|
||||
freeze_scores(sig)
|
||||
execute_rebalance(day, sig)
|
||||
elif action == "dividend_entitlement":
|
||||
ledger.record_dividend_entitlement(
|
||||
payload.symbol, payload.ex_date, payload.per_share
|
||||
)
|
||||
elif action == "dividend_payment":
|
||||
ledger.pay_due_dividends(payload.payment_date)
|
||||
# payout any dividend whose assumed payment date is reached by today
|
||||
ledger.pay_due_dividends(day.isoformat())
|
||||
|
||||
# ---------- final mark-to-market ----------
|
||||
# value every held symbol at the end date (latest close on-or-before end)
|
||||
final_prices: dict[str, float] = {}
|
||||
for sym in list(price_series.keys()):
|
||||
px = _latest_close(price_series, sym, e_date)
|
||||
if px is not None:
|
||||
final_prices[sym] = px
|
||||
ledger.pay_due_dividends(end)
|
||||
rec = ledger.reconcile(final_prices)
|
||||
|
||||
result._final_prices = final_prices
|
||||
result.ending_cash = rec["cash"]
|
||||
result.ending_market_value = rec["market_value"]
|
||||
result.final_equity = rec["equity"]
|
||||
result.realized_trading_pnl = rec["realized_trading_pnl"]
|
||||
result.unrealized_trading_pnl = rec["unrealized_trading_pnl"]
|
||||
result.price_pnl = rec["realized_trading_pnl"] + rec["unrealized_trading_pnl"]
|
||||
result.dividend_cash_received = rec["dividend_cash_received"]
|
||||
result.dividend_receivable = rec["dividend_receivable"]
|
||||
result.transaction_costs = rec["transaction_costs"]
|
||||
result.net_return = (rec["equity"] - capital) / capital if capital else 0.0
|
||||
result.account_reconciled = rec["balanced"]
|
||||
result.leakage_guard = leakage_guard
|
||||
return result
|
||||
@@ -0,0 +1,334 @@
|
||||
"""Unified event-driven backtest calendar (Task 2).
|
||||
|
||||
A backtest must rebalance when *information changes*, not on an arbitrary
|
||||
monthly/quarterly grid. This module derives a chronological event calendar from
|
||||
the actual PIT sources:
|
||||
|
||||
* factor releases (``FactorVintageStore`` rows carry ``released_at``)
|
||||
* Siamchart snapshot retrievals (the vintage manifest)
|
||||
* dividend entitlements (ex-date) and payments (ex-date + 30 calendar days
|
||||
per the confirmed timing assumption ``ex_date_plus_30d``)
|
||||
* the end-of-run valuation date
|
||||
|
||||
Each *signal* event (a release that may change the target) is paired with the
|
||||
next available execution date after it — the trade must not see a price that
|
||||
did not exist yet. Events are coalesced by day so a day with several releases
|
||||
produces exactly one frozen signal and at most one rebalance.
|
||||
|
||||
All events are plain dataclasses so the engine (Task 5) can consume them
|
||||
without coupling to the stores.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Iterable, Optional
|
||||
|
||||
# Timezone-aware default for timestamps the calendar normalises to dates.
|
||||
_TZ_BANGKOK = dt.timezone(dt.timedelta(hours=7))
|
||||
|
||||
# Dividend cash becomes available this many calendar days after ex-date.
|
||||
# Confirmed user decision (timing assumption, not an observed pay date).
|
||||
DIVIDEND_PAYMENT_LAG_DAYS = 30
|
||||
|
||||
|
||||
class BacktestEventError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _parse_date(value: Any) -> dt.date:
|
||||
if isinstance(value, dt.date):
|
||||
return value
|
||||
try:
|
||||
return dt.date.fromisoformat(str(value)[:10])
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise BacktestEventError(f"invalid date: {value!r}") from exc
|
||||
|
||||
|
||||
def _date_from_ts(value: Any) -> Optional[dt.date]:
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
return _parse_date(value)
|
||||
except BacktestEventError:
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Event types
|
||||
# ---------------------------------------------------------------------------
|
||||
@dataclass(frozen=True)
|
||||
class SignalReleaseEvent:
|
||||
"""One or more data sources produced new information on ``released_at``.
|
||||
|
||||
``sources`` names which changed (e.g. ``["factor:energy_net_margin"]`` or
|
||||
``["siamchart"]``). The engine freezes the target using only data knowable
|
||||
by ``released_at`` (anti-look-ahead).
|
||||
"""
|
||||
|
||||
released_at: str
|
||||
sources: list[str] = field(default_factory=list)
|
||||
kind: str = "signal"
|
||||
|
||||
@property
|
||||
def date(self) -> dt.date:
|
||||
return _parse_date(self.released_at)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExecutionEvent:
|
||||
"""The next available trading date to execute the signal frozen on
|
||||
``signal_date``. Never before the signal's release date."""
|
||||
|
||||
signal_date: str
|
||||
execution_date: str
|
||||
kind: str = "execution"
|
||||
|
||||
@property
|
||||
def date(self) -> dt.date:
|
||||
return _parse_date(self.execution_date)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DividendEntitlementEvent:
|
||||
"""Shares held *before* ``ex_date`` qualify for this dividend."""
|
||||
|
||||
symbol: str
|
||||
ex_date: str
|
||||
per_share: float
|
||||
kind: str = "dividend_entitlement"
|
||||
|
||||
@property
|
||||
def date(self) -> dt.date:
|
||||
return _parse_date(self.ex_date)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DividendPaymentEvent:
|
||||
"""Cash becomes available on ``payment_date``.
|
||||
|
||||
``timing_method = ex_date_plus_30d`` because the Siamchart source supplies
|
||||
ex-date + DPS but not an observed payment date; the confirmed assumption is
|
||||
that cash settles exactly ``DIVIDEND_PAYMENT_LAG_DAYS`` after ex-date.
|
||||
"""
|
||||
|
||||
symbol: str
|
||||
ex_date: str
|
||||
payment_date: str
|
||||
per_share: float
|
||||
timing_method: str = "ex_date_plus_30d"
|
||||
kind: str = "dividend_payment"
|
||||
|
||||
@property
|
||||
def date(self) -> dt.date:
|
||||
return _parse_date(self.payment_date)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EndValuationEvent:
|
||||
"""Mark holdings to market at/after ``end_date`` (final valuation)."""
|
||||
|
||||
end_date: str
|
||||
kind: str = "end_valuation"
|
||||
|
||||
@property
|
||||
def date(self) -> dt.date:
|
||||
return _parse_date(self.end_date)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Calendar builders
|
||||
# ---------------------------------------------------------------------------
|
||||
def _yield_signal_dates(factor_store: Any, start: dt.date, end: dt.date) -> list[SignalReleaseEvent]:
|
||||
"""Factor releases within [start, end], one event per released_at day."""
|
||||
from .backtest_readiness import _factor_keys_required
|
||||
|
||||
factors = _factor_keys_required()
|
||||
by_day: dict[dt.date, list[str]] = {}
|
||||
for key in factors:
|
||||
try:
|
||||
rows = factor_store.series(key)
|
||||
except Exception:
|
||||
rows = []
|
||||
for r in rows:
|
||||
d = _date_from_ts(r.get("released_at")) or _date_from_ts(r.get("observed_at"))
|
||||
if d is None or d < start or d > end:
|
||||
continue
|
||||
by_day.setdefault(d, []).append(f"factor:{key}")
|
||||
return [
|
||||
SignalReleaseEvent(
|
||||
released_at=d.isoformat(),
|
||||
sources=sorted(set(srcs)),
|
||||
)
|
||||
for d, srcs in sorted(by_day.items())
|
||||
]
|
||||
|
||||
|
||||
def _yield_siamchart_signals(
|
||||
siamchart_store: Any, start: dt.date, end: dt.date
|
||||
) -> list[SignalReleaseEvent]:
|
||||
"""Siamchart snapshot retrievals within [start, end], coalesced by day."""
|
||||
by_day: dict[dt.date, int] = {}
|
||||
try:
|
||||
ids = siamchart_store.list_ids()
|
||||
except Exception:
|
||||
ids = []
|
||||
for sid in ids:
|
||||
# read each snapshot's retrieved_at from the manifest if available
|
||||
d = None
|
||||
try:
|
||||
manifest = siamchart_store._load_manifest()
|
||||
entry = manifest.get("snapshots", {}).get(str(sid), {})
|
||||
d = _date_from_ts(entry.get("retrieved_at"))
|
||||
except Exception:
|
||||
d = None
|
||||
if d is None:
|
||||
# fallback: probe snapshot_at at a far-future cutoff for the newest
|
||||
# (only usable when the store is single-snapshot).
|
||||
try:
|
||||
snap = siamchart_store.snapshot_at(
|
||||
dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat()
|
||||
)
|
||||
d = _date_from_ts(snap.get("_retrieved_at") or snap.get("retrieved_at"))
|
||||
except Exception:
|
||||
d = None
|
||||
if d is not None and start <= d <= end:
|
||||
by_day[d] = by_day.get(d, 0) + 1
|
||||
return [
|
||||
SignalReleaseEvent(released_at=d.isoformat(), sources=["siamchart"])
|
||||
for d in sorted(by_day)
|
||||
]
|
||||
|
||||
|
||||
def _yield_dividend_events(ledger: Any, start: dt.date, end: dt.date) -> list:
|
||||
"""Dividend entitlement + payment events for dated (non-estimate) entries."""
|
||||
events: list = []
|
||||
if ledger is None:
|
||||
return events
|
||||
try:
|
||||
symbols = ledger.symbols()
|
||||
except Exception:
|
||||
return events
|
||||
for sym in symbols:
|
||||
try:
|
||||
entries = ledger.entries(sym)
|
||||
except Exception:
|
||||
entries = []
|
||||
for e in entries:
|
||||
if e.get("estimate"):
|
||||
continue # estimates are not dated cash flows
|
||||
ex_date = e.get("ex_date")
|
||||
if not ex_date:
|
||||
continue
|
||||
try:
|
||||
ex = _parse_date(ex_date)
|
||||
except BacktestEventError:
|
||||
continue
|
||||
per_share = float(e.get("per_share") or 0.0)
|
||||
if per_share <= 0:
|
||||
continue
|
||||
if start <= ex <= end:
|
||||
events.append(DividendEntitlementEvent(
|
||||
symbol=sym, ex_date=ex.isoformat(), per_share=per_share,
|
||||
))
|
||||
pay = ex + dt.timedelta(days=DIVIDEND_PAYMENT_LAG_DAYS)
|
||||
if start <= pay <= end:
|
||||
events.append(DividendPaymentEvent(
|
||||
symbol=sym, ex_date=ex.isoformat(),
|
||||
payment_date=pay.isoformat(), per_share=per_share,
|
||||
))
|
||||
return events
|
||||
|
||||
|
||||
def build_event_calendar(
|
||||
*,
|
||||
factor_store: Any = None,
|
||||
siamchart_store: Any = None,
|
||||
dividend_ledger: Any = None,
|
||||
start: str,
|
||||
end: str,
|
||||
) -> list:
|
||||
"""Build the full chronological event list for [start, end].
|
||||
|
||||
Events are returned **sorted by date**, with signal events (factor/Siamchart
|
||||
releases) interleaved with dividend and end events. Same-day releases are
|
||||
coalesced so a single day yields one signal.
|
||||
|
||||
Execution pairing is the engine's job (Task 5), but this builder guarantees
|
||||
only events within the window are produced and that the end valuation event
|
||||
is present.
|
||||
"""
|
||||
s = _parse_date(start)
|
||||
e = _parse_date(end)
|
||||
if s > e:
|
||||
raise BacktestEventError("end must be on/after start")
|
||||
|
||||
events: list = []
|
||||
events.extend(_yield_signal_dates(factor_store, s, e))
|
||||
events.extend(_yield_siamchart_signals(siamchart_store, s, e))
|
||||
events.extend(_yield_dividend_events(dividend_ledger, s, e))
|
||||
events.append(EndValuationEvent(end_date=e.isoformat()))
|
||||
|
||||
# stable sort by event date
|
||||
events.sort(key=_event_sort_key)
|
||||
return events
|
||||
|
||||
|
||||
def _event_sort_key(ev: Any):
|
||||
if hasattr(ev, "date"):
|
||||
return ev.date.isoformat()
|
||||
return ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Execution-date mapping
|
||||
# ---------------------------------------------------------------------------
|
||||
def _trading_days(price_series: dict[str, Any]) -> set[dt.date]:
|
||||
"""Union of all distinct bar dates across symbols (the tradable calendar)."""
|
||||
days: set[dt.date] = set()
|
||||
for sym, s in (price_series or {}).items():
|
||||
for b in (s or {}).get("bars", []):
|
||||
d = _date_from_ts(b.get("date"))
|
||||
if d is not None:
|
||||
days.add(d)
|
||||
return days
|
||||
|
||||
|
||||
def next_trading_day(price_series: dict[str, Any], after: dt.date) -> Optional[dt.date]:
|
||||
"""Strictly-first trading day after ``after`` in the price calendar.
|
||||
|
||||
Returns None if no trading day exists strictly after ``after``. This is the
|
||||
anti-look-ahead execution rule: the trade cannot see a price that was not
|
||||
yet known on the release day.
|
||||
"""
|
||||
trading = _trading_days(price_series)
|
||||
future = [d for d in trading if d > after]
|
||||
return min(future) if future else None
|
||||
|
||||
|
||||
def pair_signal_executions(
|
||||
signals: Iterable[SignalReleaseEvent],
|
||||
price_series: dict[str, Any],
|
||||
end: dt.date,
|
||||
) -> list[ExecutionEvent]:
|
||||
"""Map each signal to the next trading day after its release, capped at end.
|
||||
|
||||
A signal whose next trading day falls beyond the run end cannot execute and
|
||||
is dropped (the engine simply values the final holdings at end instead).
|
||||
"""
|
||||
trading = _trading_days(price_series)
|
||||
out: list[ExecutionEvent] = []
|
||||
for sig in signals:
|
||||
sdate = sig.date
|
||||
future = [d for d in trading if d > sdate]
|
||||
if not future:
|
||||
continue
|
||||
exec_day = min(future)
|
||||
if exec_day > end:
|
||||
continue # cannot execute within the backtest horizon
|
||||
out.append(ExecutionEvent(
|
||||
signal_date=sdate.isoformat(), execution_date=exec_day.isoformat(),
|
||||
))
|
||||
out.sort(key=lambda e: e.date)
|
||||
return out
|
||||
@@ -0,0 +1,466 @@
|
||||
"""Strict PIT backtest readiness + default-date derivation (Task 1).
|
||||
|
||||
The backtest must not silently start before advice is genuinely available.
|
||||
This module answers two things:
|
||||
|
||||
* ``ready`` — whether every input the backtest needs is PIT-available over
|
||||
some [start, end] window (factor releases, a Siamchart snapshot, and
|
||||
executable prices for the universe).
|
||||
* ``recommended_start`` / ``recommended_end`` — the defaults the API/UI
|
||||
should prefill. The recommended end is "yesterday" in Bangkok (the last
|
||||
complete trading availability), and the recommended start is the earliest
|
||||
date at which every PIT input is release-available *and* at least one
|
||||
executable price exists.
|
||||
|
||||
Fail-closed semantics: this module never manufactures a start date from data
|
||||
that does not exist. If any required input has no coverage through the window
|
||||
it reports ``ready=false`` and lists what is missing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Optional
|
||||
|
||||
_TZ_BANGKOK = dt.timezone(dt.timedelta(hours=7))
|
||||
|
||||
|
||||
class BacktestReadinessError(Exception):
|
||||
"""Raised when coverage cannot be evaluated safely."""
|
||||
|
||||
|
||||
def bangkok_now() -> dt.datetime:
|
||||
"""Current wall-clock in Bangkok (Asia/Bangkok, UTC+7, no DST)."""
|
||||
return dt.datetime.now(dt.timezone.utc).astimezone(_TZ_BANGKOK)
|
||||
|
||||
|
||||
def yesterday_bangkok() -> dt.date:
|
||||
"""Recommended default end: yesterday in Bangkok."""
|
||||
return (bangkok_now() - dt.timedelta(days=1)).date()
|
||||
|
||||
|
||||
def _parse_date(value: Any) -> dt.date:
|
||||
try:
|
||||
if isinstance(value, str):
|
||||
return dt.date.fromisoformat(str(value)[:10])
|
||||
if isinstance(value, dt.datetime):
|
||||
return value.date()
|
||||
if isinstance(value, dt.date):
|
||||
return value
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise BacktestReadinessError(f"invalid date: {value!r}") from exc
|
||||
raise BacktestReadinessError(f"invalid date: {value!r}")
|
||||
|
||||
|
||||
def _date_from_ts(value: Any) -> Optional[dt.date]:
|
||||
"""Extract a date from an ISO-8601 timestamp, tolerant of partial input."""
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
return _parse_date(value)
|
||||
except BacktestReadinessError:
|
||||
return None
|
||||
|
||||
|
||||
def _factor_keys_required() -> list[str]:
|
||||
"""The registry factors the PIT scorer needs (single source of truth)."""
|
||||
from .factors import FACTORS
|
||||
if isinstance(FACTORS, dict):
|
||||
return [str(k) for k in FACTORS.keys()]
|
||||
# defensive fallback (registry is a dict today; keep a tolerant path)
|
||||
keys: list[str] = []
|
||||
for item in FACTORS: # type: ignore[union-attr]
|
||||
if isinstance(item, dict) and isinstance(item.get("key"), str):
|
||||
keys.append(str(item.get("key")))
|
||||
return keys
|
||||
|
||||
|
||||
def _required_symbols() -> list[str]:
|
||||
"""The universe the backtest trades. Uses the board registry when present,
|
||||
else falls back to anything found in the price series at evaluation time."""
|
||||
try:
|
||||
from .themes import THEME_SYMBOLS
|
||||
out: list[str] = []
|
||||
if isinstance(THEME_SYMBOLS, dict):
|
||||
for v in THEME_SYMBOLS.values():
|
||||
if isinstance(v, str):
|
||||
out.append(v)
|
||||
elif isinstance(v, list):
|
||||
for s in v:
|
||||
if isinstance(s, str):
|
||||
out.append(s)
|
||||
elif isinstance(THEME_SYMBOLS, list):
|
||||
for s in THEME_SYMBOLS:
|
||||
if isinstance(s, str):
|
||||
out.append(s)
|
||||
return sorted(set(out))
|
||||
except Exception: # pragma: no cover - registry unavailable
|
||||
return []
|
||||
|
||||
|
||||
@dataclass
|
||||
class DataCoverage:
|
||||
"""Per-source earliest-available date summary for one requested window."""
|
||||
|
||||
source: str
|
||||
available: bool
|
||||
earliest: Optional[dt.date] = None
|
||||
latest: Optional[dt.date] = None
|
||||
detail: str = ""
|
||||
missing_count: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class BacktestReadiness:
|
||||
"""Strict PIT readiness verdict + recommended default dates."""
|
||||
|
||||
ready: bool
|
||||
recommended_start: Optional[str] = None
|
||||
recommended_end: Optional[str] = None
|
||||
reason: str = ""
|
||||
missing: list[str] = field(default_factory=list)
|
||||
coverage: list[DataCoverage] = field(default_factory=list)
|
||||
timezone: str = "Asia/Bangkok"
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"ready": self.ready,
|
||||
"recommended_start": self.recommended_start,
|
||||
"recommended_end": self.recommended_end,
|
||||
"reason": self.reason,
|
||||
"missing": self.missing,
|
||||
"coverage": [
|
||||
{
|
||||
"source": c.source,
|
||||
"available": c.available,
|
||||
"earliest": c.earliest.isoformat() if c.earliest else None,
|
||||
"latest": c.latest.isoformat() if c.latest else None,
|
||||
"detail": c.detail,
|
||||
"missing_count": c.missing_count,
|
||||
}
|
||||
for c in self.coverage
|
||||
],
|
||||
"timezone": self.timezone,
|
||||
}
|
||||
|
||||
|
||||
def _price_coverage(series: dict[str, Any]) -> DataCoverage:
|
||||
"""Earliest/latest trading date shared across the available symbols.
|
||||
|
||||
Uses the intersection of symbol availability so that the recommended start
|
||||
is a date every held symbol can actually be valued, not just one symbol.
|
||||
"""
|
||||
min_dates: list[dt.date] = []
|
||||
max_dates: list[dt.date] = []
|
||||
for sym, s in series.items():
|
||||
bars = (s or {}).get("bars", [])
|
||||
if not bars:
|
||||
continue
|
||||
dates = [b.get("date") for b in bars if b.get("date")]
|
||||
dates = [d for d in dates if d is not None]
|
||||
if not dates:
|
||||
continue
|
||||
parsed = [_parse_date(d) for d in dates]
|
||||
min_dates.append(min(parsed))
|
||||
max_dates.append(max(parsed))
|
||||
if not min_dates:
|
||||
return DataCoverage(
|
||||
source="price", available=False, detail="no price bars on disk",
|
||||
)
|
||||
return DataCoverage(
|
||||
source="price",
|
||||
available=True,
|
||||
earliest=max(min_dates),
|
||||
latest=min(max_dates),
|
||||
detail=f"{len(min_dates)} symbols",
|
||||
)
|
||||
|
||||
|
||||
def evaluate_readiness(
|
||||
*,
|
||||
factor_store: Any = None,
|
||||
siamchart_store: Any = None,
|
||||
price_series: Optional[dict[str, Any]] = None,
|
||||
start: Optional[str] = None,
|
||||
end: Optional[str] = None,
|
||||
) -> BacktestReadiness:
|
||||
"""Evaluate strict PIT readiness and derive recommended default dates.
|
||||
|
||||
Args:
|
||||
factor_store: a FactorVintageStore (or object exposing ``series(key)``
|
||||
and ``value_at(key, as_of)``).
|
||||
siamchart_store: a SiamchartVintageStore exposing ``list_ids()`` and
|
||||
``snapshot_at(as_of)``.
|
||||
price_series: the Yahoo price series dict ``{sym: {bars: [...]}}``.
|
||||
start/end: optional explicit window; if given, readiness is evaluated
|
||||
only against ``[start, end]``.
|
||||
|
||||
"Ready" requires only a *usable* window — NOT that every factor is present
|
||||
(the owner's rule: scoring is deliberately flexible, a theme scores from
|
||||
whatever subset of factors was knowable that day, so a backtest may run as
|
||||
soon as there is enough data to estimate, even if some sources are missing
|
||||
or don't provide history):
|
||||
1. at least one registry factor has a released value by the start date;
|
||||
2. a Siamchart snapshot retrieved no later than the start date;
|
||||
3. at least one executable price in the window for every required symbol.
|
||||
Missing inputs are still reported for transparency, but a partial window is
|
||||
runnable rather than rejected. ``recommended_start`` is the EARLIEST date at
|
||||
which usable data exists (the oldest history the system holds), and
|
||||
``recommended_end`` defaults to the last complete trading day (yesterday).
|
||||
"""
|
||||
miss: list[str] = []
|
||||
cov: list[DataCoverage] = []
|
||||
|
||||
today = yesterday_bangkok()
|
||||
# When an explicit start is requested, coverage is evaluated *at* that
|
||||
# start (the inputs must be knowable by then). Otherwise evaluate through
|
||||
# the end date to discover whether a usable window exists at all.
|
||||
if start is not None:
|
||||
coverage_cutoff = _parse_date(start)
|
||||
else:
|
||||
coverage_cutoff = _date_from_ts(end) or today
|
||||
|
||||
# ---------------- price ----------------
|
||||
if price_series is None:
|
||||
from .simulation import load_price_snapshot
|
||||
try:
|
||||
price_series = load_price_snapshot()
|
||||
except Exception as exc: # SimulationError / OSError / JSON
|
||||
price_series = {}
|
||||
cov.append(DataCoverage(
|
||||
source="price", available=False, detail=f"cannot load: {exc}",
|
||||
))
|
||||
miss.append("price")
|
||||
fac_cov, fac_miss, _earliest = _factor_coverage(
|
||||
factor_store, coverage_cutoff
|
||||
)
|
||||
cov.extend(fac_cov)
|
||||
miss.extend(fac_miss)
|
||||
return BacktestReadiness(
|
||||
ready=False, reason="price coverage missing", missing=miss,
|
||||
coverage=cov, recommended_end=today.isoformat(),
|
||||
)
|
||||
pc = _price_coverage(price_series)
|
||||
cov.append(pc)
|
||||
if not pc.available:
|
||||
miss.append("price")
|
||||
|
||||
# ---------------- factor ----------------
|
||||
fac_cov, fac_miss, fac_earliest = _factor_coverage(
|
||||
factor_store, coverage_cutoff
|
||||
)
|
||||
cov.extend(fac_cov)
|
||||
miss.extend(fac_miss)
|
||||
|
||||
# ---------------- siamchart ----------------
|
||||
scv, sc_earliest = _siamchart_coverage(siamchart_store, coverage_cutoff)
|
||||
cov.append(scv)
|
||||
if not scv.available:
|
||||
miss.append("siamchart")
|
||||
|
||||
# recommended start = the EARLIEST date a run is genuinely executable from —
|
||||
# i.e. the oldest price data (you must be able to value the holdings). Factors
|
||||
# and Siamchart are flexible (they may start later; scoring just uses whatever
|
||||
# subset was known by each day), but price is the hard floor. So the default
|
||||
# start is the oldest available executable price, per the owner's wish to
|
||||
# backtest over the oldest history the system holds.
|
||||
recommended_end = _date_from_ts(end) or today
|
||||
if start is not None:
|
||||
recommended_start = _parse_date(start)
|
||||
elif pc.available and pc.earliest is not None:
|
||||
recommended_start = pc.earliest
|
||||
else:
|
||||
candidates = [d for d in (fac_earliest, sc_earliest) if d is not None]
|
||||
recommended_start = min(candidates) if candidates else None
|
||||
|
||||
# cap recommended start so it never exceeds the end
|
||||
if recommended_start and recommended_end and recommended_start > recommended_end:
|
||||
recommended_start = recommended_end
|
||||
|
||||
# ---- usable-window gate (NOT all-factors-present) ---------------------
|
||||
# Scoring is flexible: a theme scores from whatever factors were known by
|
||||
# as_of, so the backtest is runnable once we have a price series, a Siamchart
|
||||
# snapshot, and *at least one* released factor. Missing individual factors
|
||||
# are still reported in `missing` for transparency but do NOT block the run.
|
||||
hard_block = (
|
||||
not pc.available
|
||||
or not scv.available
|
||||
or fac_earliest is None # no factor has any released value at all
|
||||
)
|
||||
if start is not None:
|
||||
s = _parse_date(start)
|
||||
e_ = _parse_date(end) if end else today
|
||||
# price must be executable AT the start: an explicit start that predates
|
||||
# all usable price history would otherwise manufacture a false PIT window.
|
||||
if pc.available and pc.earliest is not None and s < pc.earliest:
|
||||
hard_block = True
|
||||
miss.append("price")
|
||||
# an explicit start with no factor released by it is unusable
|
||||
if fac_earliest is None or s < fac_earliest:
|
||||
hard_block = True
|
||||
if "factor" not in miss:
|
||||
miss.append("factor")
|
||||
ready = (not hard_block) and s <= e_
|
||||
else:
|
||||
ready = (not hard_block) and bool(recommended_start)
|
||||
if not scv.available and "siamchart" not in miss:
|
||||
miss.append("siamchart")
|
||||
if not pc.available and "price" not in miss:
|
||||
miss.append("price")
|
||||
if fac_earliest is None and "factor" not in miss:
|
||||
miss.append("factor")
|
||||
|
||||
reason = ""
|
||||
rs = recommended_start.isoformat() if recommended_start else None
|
||||
re_iso = recommended_end.isoformat()
|
||||
if ready:
|
||||
fac_missing_n = fac_cov[0].missing_count if (fac_cov and fac_cov[0].source == "factor") else 0
|
||||
reason = (
|
||||
f"usable PIT coverage from {rs} to {re_iso}"
|
||||
+ (f" ({fac_missing_n} factors without history)"
|
||||
if fac_missing_n else "")
|
||||
)
|
||||
elif hard_block:
|
||||
blockers = []
|
||||
if not pc.available:
|
||||
blockers.append("price")
|
||||
if not scv.available:
|
||||
blockers.append("siamchart")
|
||||
if fac_earliest is None:
|
||||
blockers.append("no factor has any released value")
|
||||
reason = "missing hard inputs: " + ", ".join(blockers)
|
||||
else:
|
||||
reason = "no usable PIT-ready window"
|
||||
|
||||
return BacktestReadiness(
|
||||
ready=ready,
|
||||
recommended_start=recommended_start.isoformat() if recommended_start else None,
|
||||
recommended_end=re_iso,
|
||||
reason=reason,
|
||||
missing=sorted(set(miss)),
|
||||
coverage=cov,
|
||||
)
|
||||
|
||||
|
||||
def _factor_coverage(
|
||||
store: Any, cutoff: Optional[dt.date]
|
||||
) -> tuple[list[DataCoverage], list[str], Optional[dt.date]]:
|
||||
"""Earliest released date across all registry factors, or missing list."""
|
||||
if store is None:
|
||||
return [
|
||||
DataCoverage(
|
||||
source="factor", available=False, detail="factor store not provided",
|
||||
)
|
||||
], ["factor"], None
|
||||
factors = _factor_keys_required()
|
||||
earliest_dates: list[dt.date] = []
|
||||
missing_factor: list[str] = []
|
||||
cutoff_ts = None
|
||||
if cutoff is not None:
|
||||
cutoff_ts = dt.datetime.combine(cutoff, dt.time.min, tzinfo=_TZ_BANGKOK)
|
||||
for key in factors:
|
||||
try:
|
||||
rows = store.series(key)
|
||||
except Exception:
|
||||
rows = []
|
||||
release_dates = [
|
||||
_date_from_ts(r.get("released_at")) or _date_from_ts(r.get("observed_at"))
|
||||
for r in rows
|
||||
]
|
||||
release_dates = [d for d in release_dates if d is not None]
|
||||
if cutoff_ts is not None:
|
||||
release_dates = [
|
||||
d for d in release_dates
|
||||
if _release_le(d, cutoff_ts)
|
||||
]
|
||||
if not release_dates:
|
||||
missing_factor.append(key)
|
||||
continue
|
||||
if cutoff_ts is None:
|
||||
earliest_dates.append(min(release_dates))
|
||||
else:
|
||||
earliest_dates.append(min(release_dates))
|
||||
cov = DataCoverage(
|
||||
source="factor",
|
||||
available=not missing_factor,
|
||||
earliest=min(earliest_dates) if earliest_dates else None,
|
||||
missing_count=len(missing_factor),
|
||||
detail=(
|
||||
f"{len(earliest_dates)}/{len(factors)} factors have released values"
|
||||
if earliest_dates
|
||||
else "no factor has a released value"
|
||||
),
|
||||
)
|
||||
# umbrella missing token so consumers see "factor" plus per-key detail
|
||||
missing_tokens: list[str] = ["factor"] if missing_factor else []
|
||||
missing_tokens.extend(missing_factor)
|
||||
return [cov], missing_tokens, (min(earliest_dates) if earliest_dates else None)
|
||||
|
||||
|
||||
def _release_le(d: dt.date, cutoff_dt: dt.datetime) -> bool:
|
||||
"""True if a release date is at/before the cutoff (same-day counts)."""
|
||||
day = dt.datetime.combine(d, dt.time.min, tzinfo=_TZ_BANGKOK)
|
||||
return day <= cutoff_dt
|
||||
|
||||
|
||||
def _siamchart_coverage(
|
||||
store: Any, cutoff: Optional[dt.date] = None
|
||||
) -> tuple[DataCoverage, Optional[dt.date]]:
|
||||
"""Earliest retrieved Siamchart snapshot date (or missing).
|
||||
|
||||
When ``cutoff`` is given, the snapshot must have been retrieved by that
|
||||
date (strict PIT: it must be knowable at the requested start).
|
||||
"""
|
||||
if store is None:
|
||||
return DataCoverage(
|
||||
source="siamchart", available=False, detail="siamchart store not provided"
|
||||
), None
|
||||
try:
|
||||
ids = store.list_ids()
|
||||
except Exception:
|
||||
ids = []
|
||||
if not ids:
|
||||
return DataCoverage(
|
||||
source="siamchart", available=False,
|
||||
detail="no snapshots in siamchart vintage store",
|
||||
), None
|
||||
# Collect retrieval timestamps of every stored snapshot. The real store
|
||||
# exposes its manifest; a fake may only answer snapshot_at(now) (newest).
|
||||
retrieved_dates: list[dt.date] = []
|
||||
try:
|
||||
manifest = store._load_manifest() # real SiamchartVintageStore
|
||||
for e in manifest.get("snapshots", {}).values():
|
||||
d = _date_from_ts(e.get("retrieved_at"))
|
||||
if d is not None:
|
||||
retrieved_dates.append(d)
|
||||
except Exception:
|
||||
retrieved_dates = []
|
||||
if not retrieved_dates:
|
||||
# fallback: fake / minimal store -> newest snapshot's own retrieved_at
|
||||
try:
|
||||
snap = store.snapshot_at(
|
||||
dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat()
|
||||
)
|
||||
d = _date_from_ts(snap.get("_retrieved_at") or snap.get("retrieved_at"))
|
||||
if d is not None:
|
||||
retrieved_dates.append(d)
|
||||
except Exception:
|
||||
pass
|
||||
if not retrieved_dates:
|
||||
return DataCoverage(
|
||||
source="siamchart", available=True, detail=f"{len(ids)} snapshots stored"
|
||||
), None
|
||||
earliest = min(retrieved_dates)
|
||||
if cutoff is not None:
|
||||
known_by_cutoff = [d for d in retrieved_dates if d <= cutoff]
|
||||
if not known_by_cutoff:
|
||||
return DataCoverage(
|
||||
source="siamchart", available=False, earliest=earliest,
|
||||
detail=f"no snapshot retrieved by {cutoff.isoformat()}",
|
||||
), earliest
|
||||
earliest = min(known_by_cutoff)
|
||||
return DataCoverage(
|
||||
source="siamchart", available=True, earliest=earliest,
|
||||
detail=f"{len(ids)} snapshots stored",
|
||||
), earliest
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Durable JSON store for event-driven backtest runs (Task 6).
|
||||
|
||||
The previous backtest run history lived only in process-local memory
|
||||
(``app.extensions.setdefault("backtest_runs", [])``) and was lost on restart.
|
||||
This store persists every event-driven run (with its input coverage, event
|
||||
timeline, and scorer provenance) to an atomic JSON file at ``data/backtest/runs.json``
|
||||
so history survives restarts and can be audited.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
|
||||
def _utcnow_iso() -> str:
|
||||
return dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
class BacktestStoreError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
class BacktestStore:
|
||||
"""Append-only, thread-safe, atomic JSON store of backtest runs."""
|
||||
|
||||
def __init__(self, path: Optional[Path | str] = None) -> None:
|
||||
self.path = Path(path) if path else None
|
||||
self._lock = threading.Lock()
|
||||
self._runs: list[dict[str, Any]] = []
|
||||
if self.path and self.path.is_file():
|
||||
self._load()
|
||||
|
||||
# -- persistence ------------------------------------------------------
|
||||
def _load(self) -> None:
|
||||
p = self.path
|
||||
if p is None:
|
||||
return
|
||||
try:
|
||||
payload = json.loads(p.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError) as exc:
|
||||
raise BacktestStoreError(f"cannot load backtest store: {exc}") from exc
|
||||
if isinstance(payload, list):
|
||||
self._runs = payload
|
||||
elif isinstance(payload, dict) and isinstance(payload.get("runs"), list):
|
||||
self._runs = payload["runs"]
|
||||
else:
|
||||
self._runs = []
|
||||
|
||||
def _save(self) -> None:
|
||||
if not self.path:
|
||||
return
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = self.path.with_suffix(".tmp")
|
||||
tmp.write_text(
|
||||
json.dumps({"runs": self._runs}, ensure_ascii=False, default=str),
|
||||
encoding="utf-8",
|
||||
)
|
||||
tmp.replace(self.path)
|
||||
|
||||
# -- API --------------------------------------------------------------
|
||||
def add(self, record: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Persist a completed run record; returns it with an id/timestamp."""
|
||||
with self._lock:
|
||||
rec = dict(record)
|
||||
rec.setdefault("id", str(uuid.uuid4())[:12])
|
||||
rec.setdefault("ran_at", _utcnow_iso())
|
||||
self._runs.append(rec)
|
||||
self._save()
|
||||
return rec
|
||||
|
||||
def all(self) -> list[dict[str, Any]]:
|
||||
import copy
|
||||
with self._lock:
|
||||
return copy.deepcopy(self._runs)
|
||||
|
||||
def get(self, run_id: str) -> Optional[dict[str, Any]]:
|
||||
import copy
|
||||
with self._lock:
|
||||
for r in self._runs:
|
||||
if r.get("id") == run_id:
|
||||
return copy.deepcopy(r)
|
||||
return None
|
||||
+66
-17
@@ -32,13 +32,25 @@ def _fetch_with_cache(
|
||||
fetcher: Callable[[], dict],
|
||||
label: str,
|
||||
) -> dict:
|
||||
"""Fetch a source, degrading gracefully instead of crashing the board.
|
||||
|
||||
Flexible-scoring rule (user decision): if a source cannot be fetched AND
|
||||
there is no previously-good cached value, return an empty dict so the
|
||||
theme scorer simply drops that source's factors — the board still renders
|
||||
from the sources that are available. If a previous good value exists the
|
||||
daily cache returns it as stale (so the theme keeps using the last known
|
||||
numbers). We never let one upstream failure take down the whole board.
|
||||
"""
|
||||
import logging
|
||||
log = logging.getLogger("set50.dashboard")
|
||||
try:
|
||||
val = cache.fetch_or_stale(key, fetcher)
|
||||
if isinstance(val, dict) and "data" in val:
|
||||
return val["data"]
|
||||
return val or {}
|
||||
except Exception as exc:
|
||||
raise DashboardError(f"no real data for {label}: {exc}") from exc
|
||||
log.warning("dropping source %r (no cached value): %s", label, exc)
|
||||
return {}
|
||||
|
||||
|
||||
def _zscore(value: float, mean: float, stdev: float) -> float:
|
||||
@@ -75,7 +87,8 @@ class RealDashboard:
|
||||
|
||||
def build(self) -> dict:
|
||||
# 1) live theme data (real, no fallback)
|
||||
from . import auto_credit, auto_npl, bank_npl, energy_thai, bot_tourism
|
||||
from . import (auto_credit, auto_npl, bank_npl, energy_irpc, energy_thai,
|
||||
bot_tourism, macro_thai, te_thailand, thai_trade)
|
||||
|
||||
tourism = None
|
||||
try:
|
||||
@@ -92,13 +105,21 @@ class RealDashboard:
|
||||
self.cache, "bank_npl", lambda: bank_npl.fetch_bank_npl().to_dict(), "bank_npl")
|
||||
en_d = _fetch_with_cache(
|
||||
self.cache, "energy_thai", lambda: energy_thai.fetch_energy_thai().to_dict(), "energy_thai")
|
||||
irpc_d = _fetch_with_cache(
|
||||
self.cache, "energy_irpc", lambda: energy_irpc.fetch_energy_irpc().to_dict(), "energy_irpc")
|
||||
macro_d = _fetch_with_cache(
|
||||
self.cache, "macro_thai", lambda: macro_thai.fetch_macro_thai().to_dict(), "macro_thai")
|
||||
trade_d = _fetch_with_cache(
|
||||
self.cache, "thai_trade", lambda: thai_trade.fetch_thai_trade().to_dict(), "thai_trade")
|
||||
te_d = _fetch_with_cache(
|
||||
self.cache, "te_thailand", lambda: te_thailand.fetch_te_thailand().to_dict(), "te_thailand")
|
||||
|
||||
# 2) per-theme surprise — registry-driven (THE single source of truth)
|
||||
fetched = {
|
||||
"macro_thai": macro_d, "auto_credit": auto_d,
|
||||
"auto_npl": npl_d, "energy_thai": en_d, "bank_npl": bnpl_d,
|
||||
"auto_npl": npl_d, "energy_thai": en_d, "energy_irpc": irpc_d,
|
||||
"bank_npl": bnpl_d,
|
||||
"thai_trade": trade_d, "te_thailand": te_d,
|
||||
}
|
||||
tourism_surprise = self._tourism_surprise()
|
||||
surprises = themes_mod.compute_theme_surprises(
|
||||
@@ -110,31 +131,44 @@ class RealDashboard:
|
||||
self._mk_theme("tourism", surprises.get("tourism"), tourism),
|
||||
self._mk_theme("auto_credit", surprises.get("auto_credit"),
|
||||
_auto_read(auto_d, npl_d, self.cache)),
|
||||
self._mk_theme("refining_energy", surprises.get("refining_energy"), en_d),
|
||||
self._mk_theme("refining_energy", surprises.get("refining_energy"),
|
||||
{**en_d, "irpc_net_margin_pct": (irpc_d or {}).get("net_margin_pct"),
|
||||
"source": "TOP + IRPC investor"}),
|
||||
]
|
||||
# macro-proxy reads for the expanded SET50 themes (deterministic)
|
||||
proxy_reads = {
|
||||
"banks": {"source": "BOT macro (invest) + NPL ภาคการเงิน",
|
||||
"banks": {"source": "BOT macro + NPL + TE (rate/credit)",
|
||||
"frequency": "monthly",
|
||||
"invest_yoy": macro_d.get("private_investment_yoy"),
|
||||
"inflation_yoy": macro_d.get("headline_inflation_yoy"),
|
||||
"bank_npl_pct": (bnpl_d or {}).get("pct_of_npls")},
|
||||
"retail": {"source": "BOT macro (consumption)", "frequency": "monthly",
|
||||
"consumption_yoy": macro_d.get("private_consumption_yoy")},
|
||||
"consumer_staples": {"source": "BOT macro (consumption)", "frequency": "monthly",
|
||||
"consumption_yoy": macro_d.get("private_consumption_yoy")},
|
||||
"bank_npl_pct": (bnpl_d or {}).get("pct_of_npls"),
|
||||
"interest_rate_pct": (te_d or {}).get("interest_rate_pct"),
|
||||
"loan_growth": (te_d or {}).get("loans_to_fin_corp")},
|
||||
"retail": {"source": "BOT macro + TE (retail/confidence)", "frequency": "monthly",
|
||||
"consumption_yoy": macro_d.get("private_consumption_yoy"),
|
||||
"retail_sales_yoy": (te_d or {}).get("retail_sales_yoy"),
|
||||
"consumer_confidence": (te_d or {}).get("consumer_confidence")},
|
||||
"consumer_staples": {"source": "BOT macro + TE (retail/confidence)", "frequency": "monthly",
|
||||
"consumption_yoy": macro_d.get("private_consumption_yoy"),
|
||||
"retail_sales_yoy": (te_d or {}).get("retail_sales_yoy"),
|
||||
"consumer_confidence": (te_d or {}).get("consumer_confidence")},
|
||||
"telecom_it": {"source": "BOT macro (consumption)", "frequency": "monthly",
|
||||
"consumption_yoy": macro_d.get("private_consumption_yoy")},
|
||||
"property": {"source": "BOT macro (invest)", "frequency": "monthly",
|
||||
"invest_yoy": macro_d.get("private_investment_yoy")},
|
||||
"property": {"source": "BOT macro + TE (property)", "frequency": "monthly",
|
||||
"invest_yoy": macro_d.get("private_investment_yoy"),
|
||||
"property_prices_yoy": (te_d or {}).get("property_prices_yoy"),
|
||||
"business_confidence": (te_d or {}).get("business_confidence")},
|
||||
"utilities": {"source": "BOT macro (mfg)", "frequency": "monthly",
|
||||
"mfg_yoy": macro_d.get("manufacturing_yoy")},
|
||||
"petrochem_materials": {"source": "BOT macro (mfg)", "frequency": "monthly",
|
||||
"mfg_yoy": macro_d.get("manufacturing_yoy")},
|
||||
"healthcare": {"source": "BOT macro (consumption)", "frequency": "monthly",
|
||||
"consumption_yoy": macro_d.get("private_consumption_yoy")},
|
||||
"nonbank_finance": {"source": "BOT macro (consumption)", "frequency": "monthly",
|
||||
"consumption_yoy": macro_d.get("private_consumption_yoy")},
|
||||
"nonbank_finance": {"source": "BOT macro + TE (credit/confidence)", "frequency": "monthly",
|
||||
"consumption_yoy": macro_d.get("private_consumption_yoy"),
|
||||
"consumer_credit": (te_d or {}).get("consumer_credit_thbmn"),
|
||||
"household_debt_gdp": (te_d or {}).get("household_debt_gdp_pct"),
|
||||
"consumer_confidence": (te_d or {}).get("consumer_confidence")},
|
||||
"exploration": {"source": "TOP energy (refining)", "frequency": "quarterly",
|
||||
"energy_proxy": surprises.get("refining_energy")},
|
||||
}
|
||||
@@ -145,13 +179,23 @@ class RealDashboard:
|
||||
board = self._build_board(themes, macro_d)
|
||||
|
||||
# 5) source provenance table
|
||||
sources = self._build_sources(auto_d, npl_d, en_d, macro_d, tourism, bnpl_d)
|
||||
sources = self._build_sources(auto_d, npl_d, en_d, macro_d, tourism, bnpl_d, trade_d, te_d, irpc_d)
|
||||
|
||||
return {
|
||||
"themes": themes,
|
||||
"macro": macro_d,
|
||||
"board": board,
|
||||
"sources": sources,
|
||||
# raw per-module fetched data (fetch_module -> source dict) so the
|
||||
# symbol-detail endpoint can compute a per-source factor audit.
|
||||
"fetch_data": fetched,
|
||||
# per-theme factor-level contribution (source -> raw -> normalized ->
|
||||
# weight -> contribution) so the owner can audit exactly how each
|
||||
# theme score was built and tune weights.
|
||||
"factor_sources": {
|
||||
tid: themes_mod.factor_source_breakdown(fetched, tid)
|
||||
for tid in themes_mod.THEMES
|
||||
},
|
||||
# unambiguous split so "7 vs 5" style confusion is impossible:
|
||||
# distinct provider rows vs raw FACTORS-registry factor keys.
|
||||
"source_summary": {
|
||||
@@ -283,7 +327,7 @@ class RealDashboard:
|
||||
board.sort(key=lambda r: r["combined"], reverse=True)
|
||||
return board
|
||||
|
||||
def _build_sources(self, auto_d, npl_d, en_d, macro_d, tourism, bnpl_d=None) -> list:
|
||||
def _build_sources(self, auto_d, npl_d, en_d, macro_d, tourism, bnpl_d=None, trade_d=None, te_d=None, irpc_d=None) -> list:
|
||||
"""Sources derived from the FACTORS registry — adding a factor to
|
||||
factors.py auto-appends its source row here (no hardcoded list)."""
|
||||
import datetime as _dt
|
||||
@@ -292,7 +336,9 @@ class RealDashboard:
|
||||
|
||||
fetched = {
|
||||
"auto_credit": auto_d, "auto_npl": npl_d,
|
||||
"energy_thai": en_d, "macro_thai": macro_d, "bank_npl": bnpl_d,
|
||||
"energy_thai": en_d, "energy_irpc": irpc_d,
|
||||
"macro_thai": macro_d, "bank_npl": bnpl_d,
|
||||
"thai_trade": trade_d, "te_thailand": te_d,
|
||||
}
|
||||
# group FACTORS by fetch module -> one row per distinct source
|
||||
source_by_module: dict = {}
|
||||
@@ -321,8 +367,11 @@ class RealDashboard:
|
||||
"auto_npl": "BOT FI_NP_003_S2",
|
||||
"bank_npl": "BOT FI_NP_003_S2",
|
||||
"energy_thai": "Thai Oil investor",
|
||||
"energy_irpc": "IRPC investor",
|
||||
"macro_thai": "BOT Thai Economy",
|
||||
"bot_tourism": "BOT Tourism",
|
||||
"thai_trade": "TradingEconomics",
|
||||
"te_thailand": "TradingEconomics",
|
||||
}
|
||||
freq = meta["freq"]
|
||||
as_of = data.get("as_of") or data.get("period") or _period(data, meta["factors"])
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
"""IRPC refining-margin factor — IRPC PCL quarterly performance highlights.
|
||||
|
||||
Source: https://investor.irpc.co.th/en/financial-results/performance-highlights
|
||||
(IRPC, Thailand's second-largest refiner). Server-rendered HTML table with
|
||||
columns `[2024, 2025, 3M26]` (annual + latest quarter) and rows incl.:
|
||||
|
||||
Net Profit Margin (1.65%) (1.28%) 10.27%
|
||||
EBITDA Margin 1.42% 2.22% 19.19%
|
||||
|
||||
This extends the energy/refining theme beyond TOP (`energy_thai.py`) with a
|
||||
second real Thai refiner. The latest-period Net Profit Margin is the signal:
|
||||
IRPC swung from -1.65% (2024) to +10.27% (3M26) → a strong refining-margin
|
||||
recovery. Single-page snapshot, no history join required.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
_USER_AGENT = (
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
|
||||
)
|
||||
_URL = "https://investor.irpc.co.th/en/financial-results/performance-highlights"
|
||||
|
||||
|
||||
class EnergyIrpcError(Exception):
|
||||
"""Raised when the IRPC performance-highlights page cannot be fetched/parsed."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EnergyIrpcSnapshot:
|
||||
net_margin_pct: Optional[float] = None # latest period net profit margin %
|
||||
ebitda_margin_pct: Optional[float] = None # latest period EBITDA margin %
|
||||
roe_pct: Optional[float] = None
|
||||
period: str = ""
|
||||
columns: list = field(default_factory=list) # e.g. ["2024","2025","3M26"]
|
||||
source: str = "irpc"
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"source": self.source,
|
||||
"net_margin_pct": self.net_margin_pct,
|
||||
"ebitda_margin_pct": self.ebitda_margin_pct,
|
||||
"roe_pct": self.roe_pct,
|
||||
"period": self.period,
|
||||
"columns": self.columns,
|
||||
}
|
||||
|
||||
|
||||
def _fetch(url: str = _URL, timeout: float = 30.0) -> str:
|
||||
req = Request(url, headers={"User-Agent": _USER_AGENT, "Accept": "text/html"})
|
||||
try:
|
||||
with urlopen(req, timeout=timeout) as resp:
|
||||
raw = resp.read()
|
||||
except Exception as exc:
|
||||
raise EnergyIrpcError(f"failed to fetch {url}: {exc}") from exc
|
||||
try:
|
||||
return raw.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
return raw.decode("latin-1", "ignore")
|
||||
|
||||
|
||||
def _cells(row_html: str) -> list[str]:
|
||||
return [
|
||||
html.unescape(re.sub(r"<[^>]+>", "", td)).strip()
|
||||
for td in re.findall(r"<t[dh][^>]*>(.*?)</t[dh]>", row_html, re.S)
|
||||
if td.strip()
|
||||
]
|
||||
|
||||
|
||||
def _to_pct(text: str) -> Optional[float]:
|
||||
"""Parse a percent string: '10.27%' -> 10.27, '(1.65%)' -> -1.65."""
|
||||
text = text.replace(",", "").strip()
|
||||
neg = text.startswith("(") and text.endswith(")")
|
||||
digits = text.strip("()% ")
|
||||
try:
|
||||
val = float(digits)
|
||||
except ValueError:
|
||||
return None
|
||||
return -val if neg else val
|
||||
|
||||
|
||||
def parse_energy_irpc_html(html_text: str) -> EnergyIrpcSnapshot:
|
||||
"""Parse the IRPC performance-highlights table."""
|
||||
columns: list[str] = []
|
||||
rows: dict[str, list] = {}
|
||||
for table in re.findall(r"<table[^>]*>(.*?)</table>", html_text, re.S):
|
||||
for tr in re.findall(r"<tr[^>]*>(.*?)</tr>", table, re.S):
|
||||
cells = _cells(tr)
|
||||
if not cells:
|
||||
continue
|
||||
# header row: "Financial Highlights" + period labels
|
||||
if cells[0].lower().startswith("financial highlight"):
|
||||
columns = cells[1:]
|
||||
continue
|
||||
label = cells[0].strip().lower()
|
||||
rows[label] = cells[1:]
|
||||
|
||||
if not columns:
|
||||
raise EnergyIrpcError("no IRPC financial periods found on page")
|
||||
|
||||
def _pick(label):
|
||||
values = rows.get(label)
|
||||
if not values:
|
||||
return None
|
||||
# latest period is the last column
|
||||
return _to_pct(values[-1]) if values else None
|
||||
|
||||
# Only `net_margin` is registered as a FACTORS factor; ebitda/roe are surfaced
|
||||
# here for the dashboard read/display only (future-proof, not scored).
|
||||
net_margin = _pick("net profit margin")
|
||||
ebitda = _pick("ebitda margin")
|
||||
roe = _pick("return on equity")
|
||||
|
||||
if net_margin is None and ebitda is None:
|
||||
raise EnergyIrpcError("no usable IRPC margin series found on page")
|
||||
|
||||
return EnergyIrpcSnapshot(
|
||||
net_margin_pct=net_margin,
|
||||
ebitda_margin_pct=ebitda,
|
||||
roe_pct=roe,
|
||||
period=columns[-1] if columns else "",
|
||||
columns=[c for c in columns],
|
||||
)
|
||||
|
||||
|
||||
def fetch_energy_irpc(timeout: float = 30.0) -> EnergyIrpcSnapshot:
|
||||
return parse_energy_irpc_html(_fetch(timeout=timeout))
|
||||
@@ -6,6 +6,7 @@ import math
|
||||
from datetime import date, datetime, timezone
|
||||
from statistics import fmean
|
||||
from typing import Any, Mapping, Sequence
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
|
||||
class EventStudyError(ValueError):
|
||||
@@ -34,6 +35,18 @@ def _canonical_timestamp(value: str) -> str:
|
||||
return parsed.astimezone(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def _parse_known_at(value: Any, symbol: str) -> datetime:
|
||||
if not isinstance(value, str):
|
||||
raise EventStudyError(f"known_at is required for {symbol}")
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
except ValueError as exc:
|
||||
raise EventStudyError(f"invalid known_at for {symbol}") from exc
|
||||
if parsed.tzinfo is None:
|
||||
raise EventStudyError(f"known_at must include a timezone for {symbol}")
|
||||
return parsed.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def assess_backtest_readiness(vintages: Sequence[Mapping[str, Any]], min_events: int = 12) -> dict[str, Any]:
|
||||
if isinstance(min_events, bool) or min_events < 1:
|
||||
raise EventStudyError("min_events must be positive")
|
||||
@@ -63,13 +76,16 @@ def assess_backtest_readiness(vintages: Sequence[Mapping[str, Any]], min_events:
|
||||
}
|
||||
|
||||
|
||||
def _price_map(symbol: str, rows: Sequence[Mapping[str, Any]]) -> dict[date, float]:
|
||||
def _price_map(symbol: str, rows: Sequence[Mapping[str, Any]], *, require_known_at: bool = False) -> dict[date, tuple[float, datetime | None]]:
|
||||
if not rows:
|
||||
raise EventStudyError(f"missing prices for {symbol}")
|
||||
values: dict[date, float] = {}
|
||||
values: dict[date, tuple[float, datetime | None]] = {}
|
||||
for row in rows:
|
||||
try:
|
||||
trading_day = _parse_date(str(row["date"]))
|
||||
session_date_value = row.get("session_date")
|
||||
if session_date_value is None:
|
||||
session_date_value = row["date"]
|
||||
trading_day = _parse_date(str(session_date_value))
|
||||
close = float(row["close"])
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
raise EventStudyError(f"invalid price row for {symbol}") from exc
|
||||
@@ -77,11 +93,22 @@ def _price_map(symbol: str, rows: Sequence[Mapping[str, Any]]) -> dict[date, flo
|
||||
raise EventStudyError(f"invalid close for {symbol}")
|
||||
if trading_day in values:
|
||||
raise EventStudyError(f"duplicate price date for {symbol}")
|
||||
values[trading_day] = close
|
||||
known_at = _parse_known_at(row.get("known_at"), symbol) if require_known_at else None
|
||||
if known_at is not None:
|
||||
timezone_name = row.get("market_timezone")
|
||||
if not isinstance(timezone_name, str) or not timezone_name.strip():
|
||||
raise EventStudyError(f"market_timezone is required for {symbol}")
|
||||
try:
|
||||
market_date = known_at.astimezone(ZoneInfo(timezone_name)).date()
|
||||
except Exception as exc:
|
||||
raise EventStudyError(f"invalid market_timezone for {symbol}") from exc
|
||||
if market_date > trading_day:
|
||||
raise EventStudyError(f"known_at is after session date for {symbol}")
|
||||
values[trading_day] = (close, known_at)
|
||||
return dict(sorted(values.items()))
|
||||
|
||||
|
||||
def _window_return(series: dict[date, float], event_date: date, window: int, symbol: str, execution_lag_sessions: int) -> float:
|
||||
def _window_return(series: dict[date, tuple[float, datetime | None]], event_date: date, window: int, symbol: str, execution_lag_sessions: int) -> float:
|
||||
dates = list(series)
|
||||
anchor_candidates = [index for index, trading_day in enumerate(dates) if trading_day >= event_date]
|
||||
if not anchor_candidates:
|
||||
@@ -96,7 +123,7 @@ def _window_return(series: dict[date, float], event_date: date, window: int, sym
|
||||
end = anchor + window
|
||||
if end >= len(dates):
|
||||
raise EventStudyError(f"insufficient price history for {symbol} window {window}")
|
||||
return series[dates[end]] / series[dates[anchor]] - 1.0
|
||||
return series[dates[end]][0] / series[dates[anchor]][0] - 1.0
|
||||
|
||||
|
||||
def run_event_study(
|
||||
@@ -108,6 +135,7 @@ def run_event_study(
|
||||
cost_bps: float = 0.0,
|
||||
min_events: int = 12,
|
||||
execution_lag_sessions: int = 1,
|
||||
require_price_known_at: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Calculate weighted post-publication returns from point-in-time events."""
|
||||
|
||||
@@ -128,8 +156,13 @@ def run_event_study(
|
||||
if not math.isfinite(cost_bps) or cost_bps < 0:
|
||||
raise EventStudyError("cost_bps must be finite and non-negative")
|
||||
|
||||
normalized_prices = {str(symbol).upper(): _price_map(str(symbol).upper(), rows) for symbol, rows in prices.items()}
|
||||
normalized_benchmark = _price_map("benchmark", benchmark_prices) if benchmark_prices is not None else None
|
||||
if not isinstance(require_price_known_at, bool):
|
||||
raise EventStudyError("require_price_known_at must be boolean")
|
||||
normalized_prices = {
|
||||
str(symbol).upper(): _price_map(str(symbol).upper(), rows, require_known_at=require_price_known_at)
|
||||
for symbol, rows in prices.items()
|
||||
}
|
||||
normalized_benchmark = _price_map("benchmark", benchmark_prices, require_known_at=require_price_known_at) if benchmark_prices is not None else None
|
||||
seen_event_ids: set[str] = set()
|
||||
event_rows: list[dict[str, Any]] = []
|
||||
for event in events:
|
||||
@@ -189,4 +222,5 @@ def run_event_study(
|
||||
"event_count": len(event_rows),
|
||||
"windows": window_results,
|
||||
"min_events": min_events,
|
||||
"price_known_at_required": require_price_known_at,
|
||||
}
|
||||
@@ -24,7 +24,10 @@ _FETCH_MODULE: dict[str, str] = {
|
||||
"auto_npl": "auto_npl",
|
||||
"bank_npl": "bank_npl",
|
||||
"energy_thai": "energy_thai",
|
||||
"energy_irpc": "energy_irpc",
|
||||
"macro_thai": "macro_thai",
|
||||
"thai_trade": "thai_trade",
|
||||
"te_thailand": "te_thailand",
|
||||
}
|
||||
|
||||
# Factor -> value key. Sign: +1 higher-is-bullish, -1 lower-is-bullish.
|
||||
@@ -101,6 +104,17 @@ FACTORS: dict[str, dict[str, Any]] = {
|
||||
"weight": 1.0,
|
||||
"center": 5.0, "span": 10.0, # net margin % (derived from quarterly)
|
||||
},
|
||||
# ---- second Thai refiner: IRPC net margin (extends energy beyond TOP) ----
|
||||
"energy_irpc_net_margin": {
|
||||
"name_th": "กำไรสุทธิ IRPC",
|
||||
"source": "IRPC",
|
||||
"frequency": "quarterly",
|
||||
"fetch": "energy_irpc",
|
||||
"value_key": "net_margin_pct",
|
||||
"sign": 1,
|
||||
"weight": 0.6,
|
||||
"center": 3.0, "span": 8.0, # net margin %, ~0-3% neutral, refiners volatile
|
||||
},
|
||||
# ---- macro backdrop (proxy for expanded SET50 themes) ----
|
||||
"macro_consumption": {
|
||||
"name_th": "การบริโภคภาคเอกชน (YoY)",
|
||||
@@ -142,6 +156,144 @@ FACTORS: dict[str, dict[str, Any]] = {
|
||||
"weight": 0.5,
|
||||
"center": 2.0, "span": 10.0, # ~2% target; higher is worse (sign -1)
|
||||
},
|
||||
# ---- BOT Thai Economy fields that were already fetched but never used ----
|
||||
# Wired into the registry so every scraped value actually feeds analysis
|
||||
# (the user's rule: a fetched data point must be used, not just displayed).
|
||||
"macro_core_inflation": {
|
||||
"name_th": "เงินเฟ้อพื้นฐาน (Core)",
|
||||
"source": "BOT",
|
||||
"frequency": "monthly",
|
||||
"fetch": "macro_thai",
|
||||
"value_key": "core_inflation_yoy",
|
||||
"sign": -1,
|
||||
"weight": 0.4,
|
||||
"center": 1.0, "span": 6.0, # core ~1% target; higher is worse
|
||||
},
|
||||
"macro_unemployment": {
|
||||
"name_th": "อัตราการว่างงาน",
|
||||
"source": "BOT",
|
||||
"frequency": "monthly",
|
||||
"fetch": "macro_thai",
|
||||
"value_key": "unemployment_pct",
|
||||
"sign": -1,
|
||||
"weight": 0.5,
|
||||
"center": 1.0, "span": 3.0, # ~1% Thailand; higher unemployment is worse
|
||||
},
|
||||
# ---- Thailand external sector (TradingEconomics, current through 2026) ----
|
||||
"external_current_account": {
|
||||
"name_th": "ดุลบัญชีเดินสะพัด (USD ล้าน)",
|
||||
"source": "TradingEconomics",
|
||||
"frequency": "monthly",
|
||||
"fetch": "thai_trade",
|
||||
"value_key": "current_account_usdm",
|
||||
"sign": 1,
|
||||
"weight": 1.0,
|
||||
"center": 0.0, "span": 3000.0, # USD mn; surplus positive, deficit negative
|
||||
},
|
||||
"external_exports": {
|
||||
"name_th": "มูลค่าส่งออก (USD ล้าน)",
|
||||
"source": "TradingEconomics",
|
||||
"frequency": "monthly",
|
||||
"fetch": "thai_trade",
|
||||
"value_key": "exports_usdm",
|
||||
"sign": 1,
|
||||
"weight": 1.0,
|
||||
"center": 30000.0, "span": 8000.0, # ~$34k USD mn/month
|
||||
},
|
||||
"external_imports": {
|
||||
"name_th": "มูลค่านำเข้า (USD ล้าน)",
|
||||
"source": "TradingEconomics",
|
||||
"frequency": "monthly",
|
||||
"fetch": "thai_trade",
|
||||
"value_key": "imports_usdm",
|
||||
"sign": 1,
|
||||
"weight": 1.0,
|
||||
"center": 34000.0, "span": 8000.0, # ~$38k USD mn/month (domestic demand proxy)
|
||||
},
|
||||
# ---- Thailand rates / credit / retail / confidence (TradingEconomics) ----
|
||||
# Single-page snapshot factors deepening the macro-proxy themes. Sign +1 =
|
||||
# higher value is bullish/helpful; sign -1 = the opposite. Theme weights are
|
||||
# always positive magnitude (direction lives in `sign`, per the sign fix).
|
||||
"te_interest_rate": {
|
||||
"name_th": "อัตราดอกเบี้ย (rate)",
|
||||
"source": "TradingEconomics",
|
||||
"frequency": "monthly",
|
||||
"fetch": "te_thailand",
|
||||
"value_key": "interest_rate_pct",
|
||||
"sign": 1,
|
||||
"weight": 0.5,
|
||||
"center": 1.5, "span": 1.5, # ~1.0-2.0%; higher rate widens bank margin
|
||||
},
|
||||
"te_loan_growth": {
|
||||
"name_th": "สินเชื่อภาคธุรกิจ",
|
||||
"source": "TradingEconomics",
|
||||
"frequency": "monthly",
|
||||
"fetch": "te_thailand",
|
||||
"value_key": "loans_to_fin_corp",
|
||||
"sign": 1,
|
||||
"weight": 0.5,
|
||||
"center": 10000000.0, "span": 1500000.0, # THB mn (~10.5M); credit demand proxy
|
||||
},
|
||||
"te_consumer_credit": {
|
||||
"name_th": "สินเชื่อผู้บริโภค",
|
||||
"source": "TradingEconomics",
|
||||
"frequency": "monthly",
|
||||
"fetch": "te_thailand",
|
||||
"value_key": "consumer_credit_thbmn",
|
||||
"sign": 1,
|
||||
"weight": 0.5,
|
||||
"center": 5000000.0, "span": 800000.0, # THB mn consumer credit book
|
||||
},
|
||||
"te_household_debt_gdp": {
|
||||
"name_th": "หนี้ครัวเรือนต่อ GDP",
|
||||
"source": "TradingEconomics",
|
||||
"frequency": "quarterly",
|
||||
"fetch": "te_thailand",
|
||||
"value_key": "household_debt_gdp_pct",
|
||||
"sign": -1,
|
||||
"weight": 0.5,
|
||||
"center": 85.0, "span": 8.0, # ~87.5% of GDP; higher = leverage risk
|
||||
},
|
||||
"te_retail_sales_yoy": {
|
||||
"name_th": "ยอดขายปลีก (YoY)",
|
||||
"source": "TradingEconomics",
|
||||
"frequency": "monthly",
|
||||
"fetch": "te_thailand",
|
||||
"value_key": "retail_sales_yoy",
|
||||
"sign": 1,
|
||||
"weight": 0.8,
|
||||
"center": 0.0, "span": 10.0, # % YoY, ~0 neutral
|
||||
},
|
||||
"te_consumer_confidence": {
|
||||
"name_th": "ความเชื่อมั่นผู้บริโภค",
|
||||
"source": "TradingEconomics",
|
||||
"frequency": "monthly",
|
||||
"fetch": "te_thailand",
|
||||
"value_key": "consumer_confidence",
|
||||
"sign": 1,
|
||||
"weight": 0.5,
|
||||
"center": 50.0, "span": 12.0, # points (~51.8); above 50 = optimistic
|
||||
},
|
||||
"te_property_prices": {
|
||||
"name_th": "ราคาอสังหาริมทรัพย์ (YoY)",
|
||||
"source": "TradingEconomics",
|
||||
"frequency": "monthly",
|
||||
"fetch": "te_thailand",
|
||||
"value_key": "property_prices_yoy",
|
||||
"sign": 1,
|
||||
"weight": 0.8,
|
||||
"center": 0.0, "span": 6.0, # residential price % YoY, ~0-2% neutral
|
||||
},
|
||||
"te_business_confidence": {
|
||||
"name_th": "ความเชื่อมั่นภาคธุรกิจ",
|
||||
"source": "TradingEconomics",
|
||||
"frequency": "monthly",
|
||||
"fetch": "te_thailand",
|
||||
"value_key": "business_confidence",
|
||||
"sign": 1,
|
||||
"weight": 0.4,
|
||||
"center": 50.0, "span": 10.0, # points (~46.7); above 50 = optimistic
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,188 +0,0 @@
|
||||
"""Forward-test paper-portfolio lifecycle with frozen signals (real, not cosmetic).
|
||||
|
||||
The earlier "forward" mode was cosmetic: it ran the same single-pass
|
||||
backtest as "backtest", differing only in the `mode` string. This module
|
||||
implements a genuine forward lifecycle:
|
||||
|
||||
1. CREATE (freeze): capture the per-symbol combined scores / dividend
|
||||
flags **at a specific as_of** and persist them. The
|
||||
signal set is immutable from this point — later data
|
||||
cannot change what the run decided.
|
||||
2. EXECUTE (paper): use prices known *after* the freeze date to fill
|
||||
the 50/20/30 dividend buckets (the engine does NOT
|
||||
reach back to pick trades, it fills what the frozen
|
||||
signal said).
|
||||
3. MARK (mark-to-market): recompute portfolio equity against later
|
||||
prices, recording an equity series.
|
||||
|
||||
Each step is persisted to a durable store (JSON, atomic write) so runs
|
||||
survive restarts — replacing the in-memory backtest_runs list.
|
||||
|
||||
Honesty: a frozen forward run is paper and labelled as such. It uses the
|
||||
score source supplied at CREATE time; if that source is the current board it
|
||||
is non-PIT and the run is tagged `non_pit=true`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import datetime as dt
|
||||
import math
|
||||
import threading
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
from uuid import uuid4
|
||||
|
||||
FORWARD_SCHEMA_VERSION = 1
|
||||
|
||||
# lifecycle statuses in order
|
||||
_ORDER = ["frozen", "executed", "marked", "matured"]
|
||||
|
||||
|
||||
class ForwardError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
class ForwardTestStore:
|
||||
"""Durable, thread-safe JSON store of forward-test runs."""
|
||||
|
||||
def __init__(self, path: Path | str | None = None) -> None:
|
||||
self.path = Path(path).resolve() if path else None
|
||||
self._runs: dict[str, dict] = {}
|
||||
self._lock = threading.Lock()
|
||||
if self.path and self.path.is_file():
|
||||
self._load()
|
||||
|
||||
# -- persistence ------------------------------------------------------
|
||||
def _load(self) -> None:
|
||||
try:
|
||||
payload = json.loads(self.path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
raise ForwardError(f"forward store unreadable: {exc}") from exc
|
||||
if not isinstance(payload, dict) or payload.get("schema_version") != FORWARD_SCHEMA_VERSION:
|
||||
raise ForwardError("unsupported forward store schema")
|
||||
self._runs = deepcopy(payload.get("runs", {}))
|
||||
|
||||
def _persist(self) -> None:
|
||||
if not self.path:
|
||||
return
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
payload = {"schema_version": FORWARD_SCHEMA_VERSION, "runs": self._runs}
|
||||
tmp = self.path.with_name(f".{self.path.name}.tmp")
|
||||
tmp.write_text(json.dumps(payload, ensure_ascii=False, sort_keys=True) + "\n", encoding="utf-8")
|
||||
tmp.replace(self.path)
|
||||
|
||||
# -- lifecycle --------------------------------------------------------
|
||||
def create(self, capital: float, frozen: dict[str, dict], as_of: str,
|
||||
non_pit: bool, note: str = "") -> dict:
|
||||
"""CREATE: persist an immutable frozen-signal run."""
|
||||
with self._lock:
|
||||
if capital <= 0:
|
||||
raise ForwardError("capital must be > 0")
|
||||
run_id = f"fwd_{uuid4().hex[:12]}"
|
||||
run = {
|
||||
"id": run_id,
|
||||
"created_at": _now(),
|
||||
"capital": capital,
|
||||
"status": "frozen",
|
||||
"as_of": as_of,
|
||||
"non_pit": bool(non_pit),
|
||||
"note": note,
|
||||
"frozen_signals": deepcopy(frozen),
|
||||
"execution_prices": {},
|
||||
"holdings": {},
|
||||
"invested": 0.0,
|
||||
"equity_history": [{"date": as_of, "equity": capital}],
|
||||
}
|
||||
self._runs[run_id] = run
|
||||
self._persist()
|
||||
return deepcopy(run)
|
||||
|
||||
def execute(self, run_id: str, execution_prices: dict[str, float]) -> dict:
|
||||
"""EXECUTE: fill the frozen signals at prices provided (post-freeze).
|
||||
|
||||
Uses the canonical 50/20/30 dividend allocation over the frozen
|
||||
combined scores (mirrors simulation.allocate_capital). Frozen signals
|
||||
are NOT re-readable/changeable here — only execution prices vary.
|
||||
"""
|
||||
with self._lock:
|
||||
run = self._runs.get(run_id)
|
||||
if run is None:
|
||||
raise ForwardError(f"unknown forward run: {run_id}")
|
||||
if run["status"] != "frozen":
|
||||
raise ForwardError("run already executed")
|
||||
from . import simulation as sim
|
||||
candidates = []
|
||||
for sym, meta in (run.get("frozen_signals") or {}).items():
|
||||
price = execution_prices.get(sym)
|
||||
if price is None or price <= 0:
|
||||
continue
|
||||
candidates.append(sim.Candidate(
|
||||
symbol=sym, price=price,
|
||||
combined_score=float(meta.get("combined", 0.0)),
|
||||
is_dividend=bool(meta.get("is_dividend")),
|
||||
dividend_yield=float(meta.get("dividend_yield") or 0.0),
|
||||
))
|
||||
alloc = sim.allocate_capital(run["capital"], candidates)
|
||||
holdings = {o.symbol: o.qty for o in alloc.orders}
|
||||
invested = alloc.invested
|
||||
run["status"] = "executed"
|
||||
run["execution_prices"] = {s: float(execution_prices.get(s, 0)) for s in holdings}
|
||||
run["holdings"] = holdings
|
||||
run["invested"] = invested
|
||||
run["equity_history"].append({"date": _now(), "equity": invested})
|
||||
self._persist()
|
||||
return deepcopy(run)
|
||||
|
||||
def mark(self, run_id: str, prices: dict[str, float]) -> dict:
|
||||
"""MARK: recompute equity at provided (latest) prices and append."""
|
||||
with self._lock:
|
||||
run = self._runs.get(run_id)
|
||||
if run is None:
|
||||
raise ForwardError(f"unknown forward run: {run_id}")
|
||||
if run["status"] not in ("executed", "marked"):
|
||||
raise ForwardError("run not executed yet")
|
||||
equity = run["capital"]
|
||||
for sym, qty in (run.get("holdings") or {}).items():
|
||||
px = prices.get(sym)
|
||||
if px is None:
|
||||
continue
|
||||
equity += qty * (px - run["execution_prices"].get(sym, 0))
|
||||
run["status"] = "marked"
|
||||
run["equity_history"].append({"date": _now(), "equity": round(equity, 2)})
|
||||
self._persist()
|
||||
return deepcopy(run)
|
||||
|
||||
def mature(self, run_id: str, final_prices: dict[str, float]) -> dict:
|
||||
"""MATURE: close the run at final prices, freeze the outcome."""
|
||||
with self._lock:
|
||||
run = self._runs.get(run_id)
|
||||
if run is None:
|
||||
raise ForwardError(f"unknown forward run: {run_id}")
|
||||
if run["status"] not in ("executed", "marked"):
|
||||
raise ForwardError("run cannot mature before execution")
|
||||
equity = run["capital"]
|
||||
for sym, qty in (run.get("holdings") or {}).items():
|
||||
px = final_prices.get(sym)
|
||||
if px is None:
|
||||
continue
|
||||
equity += qty * (px - run["execution_prices"].get(sym, 0))
|
||||
run["status"] = "matured"
|
||||
run["final_equity"] = round(equity, 2)
|
||||
run["net_return"] = round((equity - run["capital"]) / run["capital"], 4) if run["capital"] else 0.0
|
||||
run["equity_history"].append({"date": _now(), "equity": round(equity, 2)})
|
||||
self._persist()
|
||||
return deepcopy(run)
|
||||
|
||||
# -- reads ------------------------------------------------------------
|
||||
def get(self, run_id: str) -> Optional[dict]:
|
||||
run = self._runs.get(run_id)
|
||||
return deepcopy(run) if run else None
|
||||
|
||||
def list(self) -> list[dict]:
|
||||
return [deepcopy(run) for run in sorted(self._runs.values(), key=lambda r: r.get("created_at", ""))]
|
||||
+38
-16
@@ -123,19 +123,29 @@ class PitScoreProvider:
|
||||
|
||||
# -- theme PIT score -------------------------------------------------
|
||||
def theme_surprise_report(self, theme_key: str, as_of: str) -> dict[str, Any]:
|
||||
"""Weighted-average theme surprise from PIT factor values only.
|
||||
"""Weighted-average theme surprise from the factors that ARE released by
|
||||
``as_of`` — flexible, not all-or-nothing.
|
||||
|
||||
Returns {theme, surprise, blocked, partial_pit}. ``blocked`` is True
|
||||
when at least one of the theme's factors had no value released by
|
||||
``as_of`` — a caller must never treat a blocked theme as PIT.
|
||||
``theme_surprise_report`` intentionally matches the live dashboard's
|
||||
``compute_theme_surprises`` semantics: any factor with no PIT value by
|
||||
``as_of`` is simply omitted from the weighted average, so a theme scores
|
||||
from whatever subset of its factors was genuinely knowable that day and
|
||||
is never blocked by a single missing source. ``blocked`` is only True
|
||||
when NO factor in the theme had a released value by ``as_of`` (nothing
|
||||
to compute). ``used``/``total`` report how many factors contributed, so
|
||||
callers can judge how thin the estimate is.
|
||||
|
||||
PIT integrity is preserved: we only ever use values released <= ``as_of``
|
||||
(``factor_at``), never future knowledge.
|
||||
"""
|
||||
factors = self.theme_factor_map.get(theme_key, [])
|
||||
if not factors:
|
||||
return {"theme": theme_key, "surprise": None, "blocked": True, "partial_pit": True}
|
||||
return {"theme": theme_key, "surprise": None, "blocked": True,
|
||||
"partial_pit": True, "used": 0, "total": 0}
|
||||
from . import factors as factors_mod
|
||||
weighted = 0.0
|
||||
w_sum = 0.0
|
||||
blocked = False
|
||||
used = 0
|
||||
for spec in factors:
|
||||
fkey = spec.get("key")
|
||||
if not isinstance(fkey, str) or not fkey:
|
||||
@@ -145,8 +155,7 @@ class PitScoreProvider:
|
||||
continue
|
||||
value = self.factor_at(fkey, as_of)
|
||||
if value is None:
|
||||
blocked = True
|
||||
continue
|
||||
continue # not released yet -> flexibly skip (no blanket block)
|
||||
norm = factors_mod.normalize(
|
||||
value, sign=fact.get("sign", 1),
|
||||
center=fact.get("center", 0.0), span=fact.get("span", 10.0),
|
||||
@@ -155,17 +164,21 @@ class PitScoreProvider:
|
||||
continue
|
||||
weighted += spec.get("weight", 1.0) * norm
|
||||
w_sum += abs(spec.get("weight", 1.0))
|
||||
surprise: Optional[float]
|
||||
used += 1
|
||||
total = len([f for f in factors if isinstance(f.get("key"), str) and f.get("key")])
|
||||
if w_sum == 0:
|
||||
surprise = None
|
||||
blocked = True
|
||||
blocked = True # nothing had a released value -> cannot score
|
||||
else:
|
||||
surprise = round(min(1.0, max(-1.0, weighted / w_sum)), 3)
|
||||
blocked = False
|
||||
return {
|
||||
"theme": theme_key,
|
||||
"surprise": surprise,
|
||||
"blocked": blocked,
|
||||
"partial_pit": blocked,
|
||||
"partial_pit": used < total,
|
||||
"used": used,
|
||||
"total": total,
|
||||
}
|
||||
|
||||
# -- per-symbol combined board as of a date ----------------------------
|
||||
@@ -189,6 +202,7 @@ class PitScoreProvider:
|
||||
|
||||
theme_scores: dict[str, dict[str, float]] = {}
|
||||
blocked_themes: list[str] = []
|
||||
partial_themes: list[str] = []
|
||||
fv = self.siamchart_factor_view(as_of)
|
||||
# reverse-map symbol -> fundamental for quality_within_theme's factor view
|
||||
fv_for_quality = {
|
||||
@@ -203,6 +217,8 @@ class PitScoreProvider:
|
||||
blocked_themes.append(tid)
|
||||
theme_scores[tid] = {}
|
||||
continue
|
||||
if rep["partial_pit"]:
|
||||
partial_themes.append(tid)
|
||||
q = {}
|
||||
for sym in themes_mod.THEME_SYMBOLS.get(tid, set()):
|
||||
if sym not in fv:
|
||||
@@ -212,7 +228,7 @@ class PitScoreProvider:
|
||||
theme_scores[tid] = q
|
||||
|
||||
combined = themes_mod.combine_score(list(theme_scores.values()), siamchart_score)
|
||||
is_full_pit = not blocked_themes
|
||||
is_full_pit = not blocked_themes and not partial_themes
|
||||
# fundamental is PIT only when a siamchart vintage store is wired;
|
||||
# otherwise the current snapshot makes the overall result partial.
|
||||
fundamental_pit = self.siamchart_store is not None
|
||||
@@ -227,11 +243,17 @@ class PitScoreProvider:
|
||||
"dividend_yield": fm.get("dividend_yield") or 0.0,
|
||||
"pit_meta": {
|
||||
"pit": is_full_pit and fundamental_pit,
|
||||
"partial_pit": not fundamental_pit,
|
||||
"partial_pit": (not fundamental_pit) or bool(partial_themes),
|
||||
"blocked_theme": blocked_themes,
|
||||
"note": ("theme surprises PIT + siamchart fundamental PIT (store)"
|
||||
if fundamental_pit else
|
||||
"theme surprises PIT; siamchart fundamental partial (current snapshot)"),
|
||||
"partial_themes": partial_themes,
|
||||
"note": (
|
||||
"theme surprises PIT + siamchart fundamental PIT (store)"
|
||||
if (fundamental_pit and not partial_themes) else
|
||||
("theme surprises PIT; some themes partial (missing factors); "
|
||||
"siamchart fundamental PIT (store)"
|
||||
if fundamental_pit else
|
||||
"theme surprises PIT; siamchart fundamental partial (current snapshot)")
|
||||
),
|
||||
},
|
||||
}
|
||||
# fall back to the current board for any symbol the PIT path could not
|
||||
|
||||
@@ -0,0 +1,337 @@
|
||||
"""Portfolio accounting ledger for the event-driven backtest (Task 3).
|
||||
|
||||
This is the single auditable owner of cash, positions, cost basis, dividend
|
||||
receivables, transaction costs, and realized/unrealized P&L. It does not decide
|
||||
*what* to hold (that is the rebalancer, Task 4) — it executes and accounts for
|
||||
orders and dividend cash flows.
|
||||
|
||||
Decisions (confirmed with the user):
|
||||
* transaction fee is all-in 0.3% of notional on every buy and every sell;
|
||||
no VAT/tax is added on top;
|
||||
* realized P&L is reported GROSS (before fees); all fees (buy + sell) are
|
||||
tracked together in ``fees`` and subtracted once in reconciliation, so the
|
||||
net trading gain = realized_pnl - fees attributable to sells;
|
||||
* dividend cash becomes available exactly 30 calendar days after ex-date
|
||||
(``ex_date_plus_30d`` assumption, not an observed payment date);
|
||||
* unpaid dividends are receivables and CANNOT fund purchases.
|
||||
|
||||
Accounting invariant (must reconcile after every event):
|
||||
ending_equity - initial_capital
|
||||
= realized_trading_pnl + unrealized_trading_pnl
|
||||
+ dividend_cash_received + accrued_dividend_receivable
|
||||
- transaction_costs
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import math
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Iterable, Optional
|
||||
|
||||
from .backtest_events import (
|
||||
DIVIDEND_PAYMENT_LAG_DAYS,
|
||||
DividendEntitlementEvent,
|
||||
DividendPaymentEvent,
|
||||
)
|
||||
|
||||
# all-in transaction fee: 0.3% of notional on each side
|
||||
FEE_RATE = 0.003
|
||||
# share-lot unit: trades happen in multiples of 100
|
||||
LOT_SIZE = 100
|
||||
|
||||
|
||||
class PortfolioLedgerError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _round_money(x: float) -> float:
|
||||
return round(float(x), 2)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Position:
|
||||
symbol: str
|
||||
qty: int = 0
|
||||
average_cost: float = 0.0
|
||||
|
||||
def market_value(self, price: float) -> float:
|
||||
return self.qty * price
|
||||
|
||||
|
||||
@dataclass
|
||||
class Trade:
|
||||
date: str
|
||||
signal_date: str
|
||||
symbol: str
|
||||
side: str # "buy" | "sell"
|
||||
qty: int
|
||||
price: float
|
||||
notional: float
|
||||
fees: float
|
||||
cost_basis_released: float = 0.0 # avg cost * qty released (sells only)
|
||||
realized_pnl: float = 0.0 # sells only
|
||||
cash_after: float = 0.0
|
||||
reason: str = ""
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"date": self.date, "signal_date": self.signal_date,
|
||||
"symbol": self.symbol, "side": self.side, "qty": self.qty,
|
||||
"price": _round_money(self.price),
|
||||
"notional": _round_money(self.notional),
|
||||
"fees": _round_money(self.fees),
|
||||
"cost_basis_released": _round_money(self.cost_basis_released),
|
||||
"realized_pnl": _round_money(self.realized_pnl),
|
||||
"cash_after": _round_money(self.cash_after),
|
||||
"reason": self.reason,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class DividendLedgerEntry:
|
||||
symbol: str
|
||||
ex_date: str
|
||||
assumed_payment_date: str
|
||||
qty_entitled: int
|
||||
per_share: float
|
||||
amount: float
|
||||
status: str = "receivable" # receivable -> paid
|
||||
timing_method: str = "ex_date_plus_30d"
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"symbol": self.symbol, "ex_date": self.ex_date,
|
||||
"assumed_payment_date": self.assumed_payment_date,
|
||||
"qty_entitled": self.qty_entitled,
|
||||
"per_share": self.per_share, "amount": _round_money(self.amount),
|
||||
"status": self.status, "timing_method": self.timing_method,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class PortfolioState:
|
||||
initial_capital: float
|
||||
cash: float = 0.0
|
||||
positions: dict[str, Position] = field(default_factory=dict)
|
||||
receivables: list[DividendLedgerEntry] = field(default_factory=list)
|
||||
trades: list[Trade] = field(default_factory=list)
|
||||
realized_pnl: float = 0.0
|
||||
dividend_cash_received: float = 0.0
|
||||
fees: float = 0.0
|
||||
# running log of dividend events for reporting
|
||||
dividends: list[dict] = field(default_factory=list)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
self.cash = float(self.initial_capital)
|
||||
|
||||
|
||||
class PortfolioLedger:
|
||||
"""Auditable cash/position/dividend accounting engine."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
initial_capital: float,
|
||||
fee_rate: float = FEE_RATE,
|
||||
lot_size: int = LOT_SIZE,
|
||||
) -> None:
|
||||
if initial_capital < 0:
|
||||
raise PortfolioLedgerError("initial capital cannot be negative")
|
||||
if fee_rate < 0 or fee_rate >= 1:
|
||||
raise PortfolioLedgerError("fee rate must be in [0, 1)")
|
||||
self.state = PortfolioState(initial_capital=float(initial_capital))
|
||||
self.fee_rate = float(fee_rate)
|
||||
self.lot_size = int(lot_size)
|
||||
|
||||
# -- positions ---------------------------------------------------------
|
||||
def qty(self, symbol: str) -> int:
|
||||
return self.state.positions.get(symbol, Position(symbol)).qty
|
||||
|
||||
def position(self, symbol: str) -> Optional[Position]:
|
||||
return self.state.positions.get(symbol)
|
||||
|
||||
def positions(self) -> list[Position]:
|
||||
return [p for p in self.state.positions.values() if p.qty > 0]
|
||||
|
||||
# -- buys/sells --------------------------------------------------------
|
||||
def _validate_lot(self, qty: int) -> None:
|
||||
if qty <= 0:
|
||||
raise PortfolioLedgerError("order qty must be positive")
|
||||
if qty % self.lot_size != 0:
|
||||
raise PortfolioLedgerError(
|
||||
f"order qty must be a multiple of {self.lot_size} (got {qty})"
|
||||
)
|
||||
|
||||
def buy(self, symbol: str, qty: int, price: float, *,
|
||||
date: str, signal_date: str, reason: str = "") -> Trade:
|
||||
self._validate_lot(qty)
|
||||
if price <= 0:
|
||||
raise PortfolioLedgerError("buy price must be positive")
|
||||
notional = qty * price
|
||||
fee = _round_money(notional * self.fee_rate)
|
||||
total = notional + fee
|
||||
if total > self.state.cash + 1e-6:
|
||||
raise PortfolioLedgerError(
|
||||
f"insufficient cash for buy: need {total:.2f}, have "
|
||||
f"{self.state.cash:.2f}"
|
||||
)
|
||||
self.state.cash -= total
|
||||
pos = self.state.positions.setdefault(symbol, Position(symbol=symbol))
|
||||
if pos.qty == 0:
|
||||
pos.average_cost = price
|
||||
else:
|
||||
total_cost = pos.qty * pos.average_cost + notional
|
||||
pos.average_cost = total_cost / (pos.qty + qty)
|
||||
pos.qty += qty
|
||||
self.state.fees += fee
|
||||
trade = Trade(
|
||||
date=date, signal_date=signal_date, symbol=symbol, side="buy",
|
||||
qty=qty, price=price, notional=notional, fees=fee,
|
||||
cash_after=_round_money(self.state.cash), reason=reason,
|
||||
)
|
||||
self.state.trades.append(trade)
|
||||
return trade
|
||||
|
||||
def sell(self, symbol: str, qty: int, price: float, *,
|
||||
date: str, signal_date: str, reason: str = "") -> Trade:
|
||||
self._validate_lot(qty)
|
||||
if price <= 0:
|
||||
raise PortfolioLedgerError("sell price must be positive")
|
||||
pos = self.state.positions.get(symbol)
|
||||
if pos is None or pos.qty < qty:
|
||||
raise PortfolioLedgerError(
|
||||
f"insufficient position to sell {qty} of {symbol}"
|
||||
)
|
||||
notional = qty * price
|
||||
fee = _round_money(notional * self.fee_rate)
|
||||
proceeds = notional - fee
|
||||
cost_basis_released = qty * pos.average_cost
|
||||
# realized P&L is GROSS (before sell fee). The sell fee is tracked in
|
||||
# ``state.fees`` and subtracted once in reconciliation, so the reported
|
||||
# net gain = realized_pnl - fees. This keeps the accounting identity
|
||||
# balanced (fees are a separate line, not counted twice).
|
||||
realized = notional - cost_basis_released
|
||||
self.state.cash += proceeds
|
||||
pos.qty -= qty
|
||||
# when fully exited, drop the position entirely
|
||||
if pos.qty == 0:
|
||||
del self.state.positions[symbol]
|
||||
self.state.fees += fee
|
||||
self.state.realized_pnl += realized
|
||||
trade = Trade(
|
||||
date=date, signal_date=signal_date, symbol=symbol, side="sell",
|
||||
qty=qty, price=price, notional=notional, fees=fee,
|
||||
cost_basis_released=cost_basis_released, realized_pnl=realized,
|
||||
cash_after=_round_money(self.state.cash), reason=reason,
|
||||
)
|
||||
self.state.trades.append(trade)
|
||||
return trade
|
||||
|
||||
# -- dividends ---------------------------------------------------------
|
||||
def record_dividend_entitlement(
|
||||
self, symbol: str, ex_date: str, per_share: float
|
||||
) -> None:
|
||||
"""Capture entitlement on ex-date using shares held *before* ex-date.
|
||||
|
||||
Only dated (non-estimate) dividends produce receivables. The amount is
|
||||
``qty_held * per_share`` and cash becomes available on
|
||||
``ex_date + DIVIDEND_PAYMENT_LAG_DAYS``.
|
||||
"""
|
||||
qty = self.qty(symbol)
|
||||
if qty <= 0:
|
||||
return # no shares held -> no entitlement
|
||||
if per_share <= 0:
|
||||
return
|
||||
ex = dt.date.fromisoformat(ex_date)
|
||||
pay = ex + dt.timedelta(days=DIVIDEND_PAYMENT_LAG_DAYS)
|
||||
amount = qty * per_share
|
||||
self.state.receivables.append(DividendLedgerEntry(
|
||||
symbol=symbol, ex_date=ex_date,
|
||||
assumed_payment_date=pay.isoformat(),
|
||||
qty_entitled=qty, per_share=per_share, amount=amount,
|
||||
))
|
||||
self.state.dividends.append({
|
||||
"symbol": symbol, "ex_date": ex_date,
|
||||
"payment_date": pay.isoformat(), "qty": qty,
|
||||
"per_share": per_share, "amount": _round_money(amount),
|
||||
"status": "receivable",
|
||||
})
|
||||
|
||||
def pay_due_dividends(self, on_date: str) -> list[DividendLedgerEntry]:
|
||||
"""Credit any receivable whose assumed payment date is <= on_date.
|
||||
|
||||
Paid dividends become spendable cash (available to later buys) and are
|
||||
removed from receivables.
|
||||
"""
|
||||
paid: list[DividendLedgerEntry] = []
|
||||
cutoff = dt.date.fromisoformat(on_date)
|
||||
still_receivable: list[DividendLedgerEntry] = []
|
||||
for r in self.state.receivables:
|
||||
pay_date = dt.date.fromisoformat(r.assumed_payment_date)
|
||||
if pay_date <= cutoff:
|
||||
self.state.cash += r.amount
|
||||
self.state.dividend_cash_received += r.amount
|
||||
r.status = "paid"
|
||||
paid.append(r)
|
||||
# update the dividends log entry status
|
||||
for d in self.state.dividends:
|
||||
if (d["symbol"] == r.symbol and d["ex_date"] == r.ex_date
|
||||
and d["status"] == "receivable"):
|
||||
d["status"] = "paid"
|
||||
else:
|
||||
still_receivable.append(r)
|
||||
self.state.receivables = still_receivable
|
||||
return paid
|
||||
|
||||
# -- valuation / reconciliation ---------------------------------------
|
||||
def total_receivable(self) -> float:
|
||||
return sum(r.amount for r in self.state.receivables)
|
||||
|
||||
def market_value(self, prices: dict[str, float]) -> float:
|
||||
total = 0.0
|
||||
for sym, pos in self.state.positions.items():
|
||||
px = prices.get(sym)
|
||||
if px is not None:
|
||||
total += pos.qty * px
|
||||
return total
|
||||
|
||||
def unrealized_pnl(self, prices: dict[str, float]) -> float:
|
||||
total = 0.0
|
||||
for sym, pos in self.state.positions.items():
|
||||
px = prices.get(sym)
|
||||
if px is not None:
|
||||
total += pos.qty * (px - pos.average_cost)
|
||||
return total
|
||||
|
||||
def equity(self, prices: dict[str, float]) -> float:
|
||||
"""Total equity: cash + market value of current holdings."""
|
||||
return self.state.cash + self.market_value(prices)
|
||||
|
||||
def reconcile(self, prices: dict[str, float]) -> dict:
|
||||
"""Return the full accounting breakdown for [end] reporting.
|
||||
|
||||
Invariant: equity_before_receivable - initial_capital ==
|
||||
realized + unrealized + dividend_cash - fees.
|
||||
(Accrued receivable is reported separately and is NOT part of spendable
|
||||
equity until paid.)
|
||||
"""
|
||||
realized = self.state.realized_pnl
|
||||
unrealized = self.unrealized_pnl(prices)
|
||||
div_cash = self.state.dividend_cash_received
|
||||
fees = self.state.fees
|
||||
equity = self.equity(prices)
|
||||
lhs = equity - self.state.initial_capital
|
||||
rhs = realized + unrealized + div_cash - fees
|
||||
return {
|
||||
"equity": equity,
|
||||
"cash": self.state.cash,
|
||||
"market_value": self.market_value(prices),
|
||||
"realized_trading_pnl": realized,
|
||||
"unrealized_trading_pnl": unrealized,
|
||||
"dividend_cash_received": div_cash,
|
||||
"dividend_receivable": self.total_receivable(),
|
||||
"transaction_costs": fees,
|
||||
"notional_return": lhs,
|
||||
"reconciled_rhs": rhs,
|
||||
"balanced": abs(lhs - rhs) < 0.01,
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
"""Lot- and cash-constrained portfolio rebalancer (Task 4).
|
||||
|
||||
Task 3's ``PortfolioLedger`` executes and accounts single orders. This module
|
||||
turns a frozen recommendation (the 50/20/30 target) into *executable* orders
|
||||
subject to:
|
||||
|
||||
* every trade is a multiple of the 100-share lot;
|
||||
* sells execute first and credit cash (realized P&L + proceeds) before buys;
|
||||
* buys never exceed available cash after fees;
|
||||
* an unaffordable target lot is skipped and the cash retained (never an odd
|
||||
lot, never negative cash);
|
||||
* if the target equals the current holdings, no trade occurs at all.
|
||||
|
||||
It reuses the canonical ``allocate_capital`` for the target shape (the same
|
||||
50/20/30 logic the live dashboard uses) so the backtest and the live board stay
|
||||
consistent.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Iterable, Optional
|
||||
|
||||
from .portfolio_ledger import PortfolioLedger
|
||||
from .simulation import allocate_capital, Candidate
|
||||
|
||||
|
||||
@dataclass
|
||||
class RebalanceResult:
|
||||
date: str
|
||||
signal_date: str
|
||||
trades: list = field(default_factory=list)
|
||||
target_changed: bool = False
|
||||
notes: list[str] = field(default_factory=list)
|
||||
|
||||
def trade_count(self) -> int:
|
||||
return len(self.trades)
|
||||
|
||||
|
||||
class RebalanceError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _qty_affordable(cash: float, price: float, lot: int, fee_rate: float) -> int:
|
||||
"""Max 100-lot qty affordable with cash, including the 0.3% buy fee."""
|
||||
if price <= 0 or cash <= 0:
|
||||
return 0
|
||||
# find largest q (multiple of lot) with q*price*(1+fee) <= cash
|
||||
best = 0
|
||||
q = lot
|
||||
while True:
|
||||
cost = q * price * (1 + fee_rate)
|
||||
if cost > cash + 1e-6:
|
||||
break
|
||||
best = q
|
||||
q += lot
|
||||
return best
|
||||
|
||||
|
||||
def _latest_close(series: dict, sym: str, date: dt.date) -> Optional[float]:
|
||||
bars = (series.get(sym) or {}).get("bars", [])
|
||||
chosen = None
|
||||
for b in bars:
|
||||
d = str(b.get("date") or "")[:10]
|
||||
try:
|
||||
bd = dt.date.fromisoformat(d)
|
||||
except ValueError:
|
||||
continue
|
||||
if bd <= date:
|
||||
chosen = b.get("adjusted_close")
|
||||
return float(chosen) if chosen is not None else None
|
||||
|
||||
|
||||
def _current_qty(ledger: PortfolioLedger, symbol: str) -> int:
|
||||
pos = ledger.position(symbol)
|
||||
return pos.qty if pos else 0
|
||||
|
||||
|
||||
class PortfolioRebalancer:
|
||||
"""Convert a frozen target into executable 100-lot orders via ledger."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ledger: PortfolioLedger,
|
||||
price_series: dict[str, Any],
|
||||
candidates: list[Candidate],
|
||||
*,
|
||||
fee_rate: float = 0.003,
|
||||
lot_size: int = 100,
|
||||
) -> None:
|
||||
self.ledger = ledger
|
||||
self.price_series = price_series
|
||||
self.candidates = candidates
|
||||
self.fee_rate = fee_rate
|
||||
self.lot_size = lot_size
|
||||
|
||||
def _target(self, date: dt.date) -> dict[str, int]:
|
||||
"""Compute the 50/20/30 target over current equity + price as-of date.
|
||||
|
||||
Equity is grossed up by cumulative fees so transaction costs do not
|
||||
silently drift the target (and cause churn) across otherwise-unchanged
|
||||
signals. Without this, every fee paid would shrink the bucket amounts
|
||||
and force a spurious 1-lot trade on the next rebalance.
|
||||
"""
|
||||
prices: dict[str, float] = {}
|
||||
for c in self.candidates:
|
||||
px = _latest_close(self.price_series, c.symbol, date)
|
||||
if px is not None:
|
||||
prices[c.symbol] = px
|
||||
equity = self.ledger.equity(prices) + self.ledger.state.fees
|
||||
alloc = allocate_capital(equity, self.candidates)
|
||||
return {o.symbol: o.qty for o in alloc.orders}
|
||||
|
||||
def rebalance(self, *, date: dt.date, signal_date: dt.date) -> RebalanceResult:
|
||||
result = RebalanceResult(
|
||||
date=date.isoformat(), signal_date=signal_date.isoformat()
|
||||
)
|
||||
target = self._target(date)
|
||||
current = {
|
||||
sym: _current_qty(self.ledger, sym)
|
||||
for sym in list(self.ledger.state.positions.keys())
|
||||
}
|
||||
|
||||
# unchanged target -> no trade (avoid churn)
|
||||
if all(current.get(sym, 0) == tgt for sym, tgt in target.items()) and all(
|
||||
target.get(sym, 0) == qty for sym, qty in current.items()
|
||||
):
|
||||
result.target_changed = False
|
||||
return result
|
||||
result.target_changed = True
|
||||
|
||||
date_str = date.isoformat()
|
||||
sig_str = signal_date.isoformat()
|
||||
|
||||
# --- sells first: exit / trim names not in (or over) target ---
|
||||
for sym in list(self.ledger.state.positions.keys()):
|
||||
cur = _current_qty(self.ledger, sym)
|
||||
tgt = target.get(sym, 0)
|
||||
if cur > tgt:
|
||||
sell_qty = cur - tgt
|
||||
# reduce to a 100-lot multiple
|
||||
sell_qty = (sell_qty // self.lot_size) * self.lot_size
|
||||
if sell_qty <= 0:
|
||||
continue
|
||||
px = _latest_close(self.price_series, sym, date)
|
||||
if px is None or px <= 0:
|
||||
continue
|
||||
trade = self.ledger.sell(
|
||||
sym, sell_qty, px, date=date_str, signal_date=sig_str,
|
||||
reason="exit/trim to target",
|
||||
)
|
||||
result.trades.append(trade)
|
||||
|
||||
# --- buys: deficit up to available cash after sells ---
|
||||
for sym, tgt in target.items():
|
||||
cur = _current_qty(self.ledger, sym)
|
||||
deficit = tgt - cur
|
||||
if deficit <= 0:
|
||||
continue
|
||||
px = _latest_close(self.price_series, sym, date)
|
||||
if px is None or px <= 0:
|
||||
continue
|
||||
# buy in lots, limited by that symbol's target deficit AND cash
|
||||
max_by_target = (deficit // self.lot_size) * self.lot_size
|
||||
affordable = _qty_affordable(
|
||||
self.ledger.state.cash, px, self.lot_size, self.fee_rate
|
||||
)
|
||||
buy_qty = min(max_by_target, affordable)
|
||||
if buy_qty < self.lot_size:
|
||||
continue # can't afford even one lot; keep cash
|
||||
try:
|
||||
trade = self.ledger.buy(
|
||||
sym, buy_qty, px, date=date_str, signal_date=sig_str,
|
||||
reason="enter/upsize to target",
|
||||
)
|
||||
except Exception as exc:
|
||||
result.notes.append(f"{sym}: {exc}")
|
||||
continue
|
||||
result.trades.append(trade)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def build_candidates(
|
||||
score_by_symbol: dict[str, Any], price_series: dict, date: dt.date
|
||||
) -> list[Candidate]:
|
||||
"""Build Candidate list from a frozen score map + prices as-of date."""
|
||||
out: list[Candidate] = []
|
||||
for sym, meta in score_by_symbol.items():
|
||||
px = _latest_close(price_series, sym, date)
|
||||
if px is None or px <= 0:
|
||||
continue
|
||||
out.append(Candidate(
|
||||
symbol=sym,
|
||||
price=px,
|
||||
combined_score=float(meta.get("combined", 0.0)),
|
||||
is_dividend=bool(meta.get("is_dividend", False)),
|
||||
dividend_yield=float(meta.get("dividend_yield") or 0.0),
|
||||
))
|
||||
return out
|
||||
+261
-37
@@ -1,8 +1,8 @@
|
||||
"""Frozen, replayable Tourism research runs.
|
||||
|
||||
A run either produces a deterministic event-study result from point-in-time
|
||||
inputs or persists a blocked report explaining the exact missing gate. It never
|
||||
falls back to revised vendor history.
|
||||
Validated runs require point-in-time inputs. Explicit exploratory runs may use
|
||||
revised vendor history, but their result is permanently labelled descriptive
|
||||
only and does not satisfy the validated backtest gate.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,12 +17,15 @@ from pathlib import Path
|
||||
from typing import Any, Mapping, Sequence
|
||||
|
||||
from .event_study import EventStudyError, _canonical_timestamp, assess_backtest_readiness, run_event_study
|
||||
from .prices import PriceSnapshotStore, PriceSourceError
|
||||
from .prices import PIT_ARCHIVE_CONTRACT, PriceSnapshotStore, PriceSourceError
|
||||
from .tourism import compute_tourism_signal
|
||||
from .vintages import VintageStore, VintageStoreError
|
||||
|
||||
RUN_SCHEMA_VERSION = 1
|
||||
REPORT_HASH_ALGORITHM = "sha256-json-canonical-v1"
|
||||
_RUN_ID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}")
|
||||
RESEARCH_MODES = {"validated", "exploratory"}
|
||||
_OBSERVATION_RUNTIME_FIELDS = frozenset({"first_seen_at", "last_seen_at", "observation_count"})
|
||||
|
||||
|
||||
class ResearchRunError(ValueError):
|
||||
@@ -34,6 +37,20 @@ def _canonical_hash(payload: Mapping[str, Any]) -> str:
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def _report_hash(report: Mapping[str, Any]) -> str:
|
||||
payload = copy.deepcopy(dict(report))
|
||||
payload.pop("report_hash", None)
|
||||
payload.pop("report_hash_algorithm", None)
|
||||
return _canonical_hash(payload)
|
||||
|
||||
|
||||
def _manifest_entry_hash(entry: Mapping[str, Any]) -> str:
|
||||
payload = copy.deepcopy(dict(entry))
|
||||
payload.pop("manifest_entry_hash", None)
|
||||
payload.pop("manifest_entry_hash_algorithm", None)
|
||||
return _canonical_hash(payload)
|
||||
|
||||
|
||||
def _atomic_write(path: Path, payload: Mapping[str, Any]) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_name(f".{path.name}.tmp")
|
||||
@@ -54,9 +71,13 @@ class ResearchRunStore:
|
||||
return {"schema_version": RUN_SCHEMA_VERSION, "runs": {}}
|
||||
try:
|
||||
manifest = json.loads(self.manifest_path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
||||
raise ResearchRunError("research run manifest is unreadable") from exc
|
||||
if manifest.get("schema_version") != RUN_SCHEMA_VERSION or not isinstance(manifest.get("runs"), dict):
|
||||
if (
|
||||
not isinstance(manifest, dict)
|
||||
or manifest.get("schema_version") != RUN_SCHEMA_VERSION
|
||||
or not isinstance(manifest.get("runs"), dict)
|
||||
):
|
||||
raise ResearchRunError("unsupported research run manifest schema")
|
||||
return manifest
|
||||
|
||||
@@ -74,79 +95,235 @@ class ResearchRunStore:
|
||||
raise FileNotFoundError(run_id)
|
||||
try:
|
||||
report = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
||||
raise ResearchRunError("research report is unreadable") from exc
|
||||
if not isinstance(report, dict):
|
||||
raise ResearchRunError("research report is invalid")
|
||||
if report.get("run_id") != run_id or report.get("schema_version") != RUN_SCHEMA_VERSION:
|
||||
raise ResearchRunError("research report identity mismatch")
|
||||
declared_hash = report.get("report_hash")
|
||||
if (
|
||||
report.get("report_hash_algorithm") != REPORT_HASH_ALGORITHM
|
||||
or not isinstance(declared_hash, str)
|
||||
or _report_hash(report) != declared_hash
|
||||
):
|
||||
raise ResearchRunError("research report integrity hash mismatch")
|
||||
manifest_entry = self.load_manifest().get("runs", {}).get(run_id)
|
||||
declared_manifest_hash = manifest_entry.get("manifest_entry_hash") if isinstance(manifest_entry, dict) else None
|
||||
if (
|
||||
not isinstance(manifest_entry, dict)
|
||||
or manifest_entry.get("run_id") != run_id
|
||||
or manifest_entry.get("report_file") != path.name
|
||||
or any(manifest_entry.get(field) != report.get(field) for field in ("status", "reason", "generated_at"))
|
||||
or manifest_entry.get("report_hash_algorithm") != REPORT_HASH_ALGORITHM
|
||||
or manifest_entry.get("report_hash") != declared_hash
|
||||
or manifest_entry.get("manifest_entry_hash_algorithm") != REPORT_HASH_ALGORITHM
|
||||
or not isinstance(declared_manifest_hash, str)
|
||||
or _manifest_entry_hash(manifest_entry) != declared_manifest_hash
|
||||
):
|
||||
raise ResearchRunError("research report manifest integrity mismatch")
|
||||
return report
|
||||
|
||||
def migrate_legacy(self) -> int:
|
||||
"""Add integrity metadata to explicitly migrated pre-hash reports."""
|
||||
manifest = self.load_manifest()
|
||||
migrated = 0
|
||||
for raw_run_id, raw_entry in manifest["runs"].items():
|
||||
run_id = str(raw_run_id)
|
||||
if not _RUN_ID_RE.fullmatch(run_id) or not isinstance(raw_entry, dict):
|
||||
raise ResearchRunError("invalid research run manifest entry")
|
||||
path = self._report_path(run_id)
|
||||
if raw_entry.get("run_id") != run_id or raw_entry.get("report_file") != path.name:
|
||||
raise ResearchRunError("research run manifest entry identity mismatch")
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(run_id)
|
||||
try:
|
||||
report = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
||||
raise ResearchRunError("research report is unreadable") from exc
|
||||
if not isinstance(report, dict) or report.get("run_id") != run_id or report.get("schema_version") != RUN_SCHEMA_VERSION:
|
||||
raise ResearchRunError("research report identity mismatch")
|
||||
has_report_integrity = "report_hash" in report or "report_hash_algorithm" in report
|
||||
has_manifest_integrity = "manifest_entry_hash" in raw_entry or "manifest_entry_hash_algorithm" in raw_entry
|
||||
if has_manifest_integrity and not has_report_integrity:
|
||||
raise ResearchRunError("research run integrity metadata is incomplete")
|
||||
declared_report_hash = report.get("report_hash")
|
||||
report_integrity_valid = (
|
||||
report.get("report_hash_algorithm") == REPORT_HASH_ALGORITHM
|
||||
and isinstance(declared_report_hash, str)
|
||||
and _report_hash(report) == declared_report_hash
|
||||
)
|
||||
if has_report_integrity and not report_integrity_valid:
|
||||
raise ResearchRunError("research run integrity metadata is invalid")
|
||||
if not has_report_integrity or not has_manifest_integrity:
|
||||
if any(raw_entry.get(field) != report.get(field) for field in ("status", "reason", "generated_at")):
|
||||
raise ResearchRunError("research report manifest metadata mismatch")
|
||||
if not has_report_integrity:
|
||||
stored = copy.deepcopy(report)
|
||||
stored["report_hash_algorithm"] = REPORT_HASH_ALGORITHM
|
||||
stored["report_hash"] = _report_hash(stored)
|
||||
declared_report_hash = stored["report_hash"]
|
||||
_atomic_write(path, stored)
|
||||
if not has_manifest_integrity:
|
||||
migrated_entry = copy.deepcopy(raw_entry)
|
||||
migrated_entry["report_hash_algorithm"] = REPORT_HASH_ALGORITHM
|
||||
migrated_entry["report_hash"] = declared_report_hash
|
||||
migrated_entry["manifest_entry_hash_algorithm"] = REPORT_HASH_ALGORITHM
|
||||
migrated_entry["manifest_entry_hash"] = _manifest_entry_hash(migrated_entry)
|
||||
manifest["runs"][run_id] = migrated_entry
|
||||
migrated += 1
|
||||
continue
|
||||
declared_manifest_hash = raw_entry.get("manifest_entry_hash")
|
||||
if (
|
||||
not report_integrity_valid
|
||||
or raw_entry.get("report_hash_algorithm") != REPORT_HASH_ALGORITHM
|
||||
or raw_entry.get("report_hash") != declared_report_hash
|
||||
or raw_entry.get("manifest_entry_hash_algorithm") != REPORT_HASH_ALGORITHM
|
||||
or not isinstance(declared_manifest_hash, str)
|
||||
or _manifest_entry_hash(raw_entry) != declared_manifest_hash
|
||||
or any(raw_entry.get(field) != report.get(field) for field in ("status", "reason", "generated_at"))
|
||||
):
|
||||
raise ResearchRunError("research run integrity metadata is invalid")
|
||||
if migrated:
|
||||
_atomic_write(self.manifest_path, manifest)
|
||||
return migrated
|
||||
|
||||
def _validated_manifest_entries(self) -> list[dict[str, Any]]:
|
||||
manifest = self.load_manifest()
|
||||
entries: list[dict[str, Any]] = []
|
||||
for run_id, raw_entry in manifest["runs"].items():
|
||||
if not _RUN_ID_RE.fullmatch(str(run_id)) or not isinstance(raw_entry, dict) or raw_entry.get("run_id") != run_id:
|
||||
raise ResearchRunError("invalid research run manifest entry")
|
||||
try:
|
||||
self.load(run_id)
|
||||
except FileNotFoundError as exc:
|
||||
raise ResearchRunError("research run manifest entry report is missing") from exc
|
||||
entries.append(raw_entry)
|
||||
return entries
|
||||
|
||||
def persist(self, report: dict[str, Any]) -> dict[str, Any]:
|
||||
run_id = str(report.get("run_id", ""))
|
||||
path = self._report_path(run_id)
|
||||
manifest = self.load_manifest()
|
||||
existing = manifest["runs"].get(run_id)
|
||||
if existing:
|
||||
stored = self.load(run_id)
|
||||
if stored != report:
|
||||
raise ResearchRunError("research run id already contains a different report")
|
||||
return stored
|
||||
stored = copy.deepcopy(report)
|
||||
stored["report_hash_algorithm"] = REPORT_HASH_ALGORITHM
|
||||
stored["report_hash"] = _report_hash(stored)
|
||||
manifest = self.load_manifest()
|
||||
self._validated_manifest_entries()
|
||||
if run_id in manifest["runs"]:
|
||||
if not isinstance(manifest["runs"][run_id], dict):
|
||||
raise ResearchRunError("invalid research run manifest entry")
|
||||
existing_report = self.load(run_id)
|
||||
if existing_report != stored:
|
||||
raise ResearchRunError("research run id already contains a different report")
|
||||
return existing_report
|
||||
_atomic_write(path, stored)
|
||||
manifest["runs"][run_id] = {
|
||||
manifest_entry = {
|
||||
"run_id": run_id,
|
||||
"status": stored.get("status"),
|
||||
"reason": stored.get("reason"),
|
||||
"generated_at": stored.get("generated_at"),
|
||||
"report_file": path.name,
|
||||
"report_hash_algorithm": REPORT_HASH_ALGORITHM,
|
||||
"report_hash": stored["report_hash"],
|
||||
}
|
||||
manifest_entry["manifest_entry_hash_algorithm"] = REPORT_HASH_ALGORITHM
|
||||
manifest_entry["manifest_entry_hash"] = _manifest_entry_hash(manifest_entry)
|
||||
manifest["runs"][run_id] = manifest_entry
|
||||
_atomic_write(self.manifest_path, manifest)
|
||||
return stored
|
||||
|
||||
def latest(self) -> dict[str, Any]:
|
||||
entries = list(self.load_manifest().get("runs", {}).values())
|
||||
entries = self._validated_manifest_entries()
|
||||
if not entries:
|
||||
raise FileNotFoundError("no research runs")
|
||||
latest = max(entries, key=lambda item: (str(item.get("generated_at", "")), str(item.get("run_id", ""))))
|
||||
return self.load(str(latest["run_id"]))
|
||||
|
||||
def list_runs(self) -> list[dict[str, Any]]:
|
||||
entries = list(self.load_manifest().get("runs", {}).values())
|
||||
entries = self._validated_manifest_entries()
|
||||
return sorted(entries, key=lambda item: (str(item.get("generated_at", "")), str(item.get("run_id", ""))), reverse=True)
|
||||
|
||||
|
||||
def _validate_config(windows: Sequence[int], cost_bps: float, min_events: int, execution_lag_sessions: int) -> tuple[list[int], float, int, int]:
|
||||
if not windows or any(isinstance(window, bool) or int(window) != window or int(window) <= 0 for window in windows):
|
||||
raise ResearchRunError("windows must contain positive integers")
|
||||
def _parse_config_integer(value: Any, field: str, minimum: int) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
raise ResearchRunError(f"{field} must be an integer")
|
||||
try:
|
||||
parsed = int(value)
|
||||
numeric = float(value)
|
||||
except (OverflowError, TypeError, ValueError) as exc:
|
||||
raise ResearchRunError(f"{field} must be an integer") from exc
|
||||
if not math.isfinite(numeric) or parsed != value or parsed < minimum:
|
||||
qualifier = "positive" if minimum > 0 else "non-negative"
|
||||
raise ResearchRunError(f"{field} must be a {qualifier} integer")
|
||||
return parsed
|
||||
|
||||
|
||||
def _validate_config(windows: Sequence[int], cost_bps: float, min_events: int, execution_lag_sessions: int) -> tuple[list[int], float, int, int]:
|
||||
if not isinstance(windows, (list, tuple)) or not windows:
|
||||
raise ResearchRunError("windows must contain positive integers")
|
||||
parsed_windows = [_parse_config_integer(window, "windows", 1) for window in windows]
|
||||
try:
|
||||
if isinstance(cost_bps, bool):
|
||||
raise TypeError
|
||||
parsed_cost = float(cost_bps)
|
||||
except (TypeError, ValueError) as exc:
|
||||
except (OverflowError, TypeError, ValueError) as exc:
|
||||
raise ResearchRunError("cost_bps must be finite and non-negative") from exc
|
||||
if not math.isfinite(parsed_cost) or parsed_cost < 0:
|
||||
raise ResearchRunError("cost_bps must be finite and non-negative")
|
||||
if isinstance(min_events, bool) or int(min_events) != min_events or int(min_events) < 1:
|
||||
raise ResearchRunError("min_events must be positive")
|
||||
if isinstance(execution_lag_sessions, bool) or int(execution_lag_sessions) != execution_lag_sessions or int(execution_lag_sessions) < 0:
|
||||
raise ResearchRunError("execution_lag_sessions must be a non-negative integer")
|
||||
return [int(window) for window in windows], parsed_cost, int(min_events), int(execution_lag_sessions)
|
||||
parsed_min_events = _parse_config_integer(min_events, "min_events", 1)
|
||||
parsed_execution_lag = _parse_config_integer(execution_lag_sessions, "execution_lag_sessions", 0)
|
||||
return parsed_windows, parsed_cost, parsed_min_events, parsed_execution_lag
|
||||
|
||||
|
||||
def _price_gate(price_entry: Mapping[str, Any] | None) -> dict[str, Any]:
|
||||
def _validate_mode(mode: str) -> str:
|
||||
if not isinstance(mode, str) or mode not in RESEARCH_MODES:
|
||||
raise ResearchRunError(f"mode must be one of: {', '.join(sorted(RESEARCH_MODES))}")
|
||||
return mode
|
||||
|
||||
|
||||
def _price_gate(price_entry: Mapping[str, Any] | None, mode: str = "validated") -> dict[str, Any]:
|
||||
mode = _validate_mode(mode)
|
||||
if not price_entry:
|
||||
return {"status": "blocked", "reason": "price_snapshot_missing", "snapshot_count": 0}
|
||||
if price_entry.get("point_in_time") is not True:
|
||||
return {
|
||||
"status": "blocked",
|
||||
"status": "descriptive_only" if mode == "exploratory" else "blocked",
|
||||
"reason": "price_series_not_point_in_time",
|
||||
"snapshot_id": price_entry.get("snapshot_id"),
|
||||
"quality": price_entry.get("quality"),
|
||||
"point_in_time": False,
|
||||
"validated": False,
|
||||
}
|
||||
if price_entry.get("quality") != "point_in_time_archive" or price_entry.get("archive_contract") != PIT_ARCHIVE_CONTRACT:
|
||||
return {
|
||||
"status": "descriptive_only" if mode == "exploratory" else "blocked",
|
||||
"reason": "price_archive_contract_missing",
|
||||
"snapshot_id": price_entry.get("snapshot_id"),
|
||||
"quality": price_entry.get("quality"),
|
||||
"archive_contract": price_entry.get("archive_contract"),
|
||||
"point_in_time": True,
|
||||
"validated": False,
|
||||
}
|
||||
if mode == "exploratory":
|
||||
return {
|
||||
"status": "descriptive_only",
|
||||
"reason": "exploratory_mode_non_validated",
|
||||
"snapshot_id": price_entry.get("snapshot_id"),
|
||||
"quality": price_entry.get("quality"),
|
||||
"archive_contract": price_entry.get("archive_contract"),
|
||||
"provider_release_id": price_entry.get("provider_release_id"),
|
||||
"point_in_time": True,
|
||||
"validated": False,
|
||||
}
|
||||
return {
|
||||
"status": "ready",
|
||||
"reason": None,
|
||||
"snapshot_id": price_entry.get("snapshot_id"),
|
||||
"quality": price_entry.get("quality"),
|
||||
"archive_contract": price_entry.get("archive_contract"),
|
||||
"provider_release_id": price_entry.get("provider_release_id"),
|
||||
"point_in_time": True,
|
||||
"validated": True,
|
||||
}
|
||||
|
||||
|
||||
@@ -164,11 +341,25 @@ def _select_independent_vintages(entries: Sequence[Mapping[str, Any]]) -> list[d
|
||||
entry = dict(raw_entry)
|
||||
key = _revision_key(entry)
|
||||
current = selected.get(key)
|
||||
candidate_rank = (str(entry.get("first_seen_at", "")), str(entry.get("last_seen_at", "")), str(entry.get("vintage_id", "")))
|
||||
current_rank = (str(current.get("first_seen_at", "")), str(current.get("last_seen_at", "")), str(current.get("vintage_id", ""))) if current else ("", "", "")
|
||||
candidate_rank = (
|
||||
_canonical_timestamp(str(entry.get("first_seen_at") or "")),
|
||||
_canonical_timestamp(str(entry.get("last_seen_at") or "")),
|
||||
str(entry.get("vintage_id", "")),
|
||||
)
|
||||
current_rank = (
|
||||
_canonical_timestamp(str(current.get("first_seen_at") or "")),
|
||||
_canonical_timestamp(str(current.get("last_seen_at") or "")),
|
||||
str(current.get("vintage_id", "")),
|
||||
) if current else ("", "", "")
|
||||
if current is None or candidate_rank > current_rank:
|
||||
selected[key] = entry
|
||||
return sorted(selected.values(), key=lambda item: (str(item.get("published_at", "")), str(item.get("vintage_id", ""))))
|
||||
return sorted(
|
||||
selected.values(),
|
||||
key=lambda item: (
|
||||
_canonical_timestamp(str(item.get("published_at") or "")),
|
||||
str(item.get("vintage_id", "")),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _series_rows(series: Mapping[str, Any], price_field: str, symbol: str) -> list[dict[str, Any]]:
|
||||
@@ -179,7 +370,15 @@ def _series_rows(series: Mapping[str, Any], price_field: str, symbol: str) -> li
|
||||
for bar in bars:
|
||||
if not isinstance(bar, dict) or price_field not in bar:
|
||||
raise ResearchRunError(f"price field {price_field} missing for {symbol}")
|
||||
rows.append({"date": bar.get("date"), "close": bar.get(price_field)})
|
||||
session_date = bar.get("session_date", bar.get("date"))
|
||||
row = {"date": session_date, "close": bar.get(price_field)}
|
||||
if "session_date" in bar:
|
||||
row["session_date"] = session_date
|
||||
if "known_at" in bar:
|
||||
row["known_at"] = bar.get("known_at")
|
||||
if "timezone" in series:
|
||||
row["market_timezone"] = series.get("timezone")
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
@@ -192,13 +391,15 @@ def run_tourism_research(
|
||||
windows: Sequence[int] = (1, 3, 5, 20),
|
||||
cost_bps: float = 20.0,
|
||||
execution_lag_sessions: int = 1,
|
||||
mode: str = "validated",
|
||||
) -> dict[str, Any]:
|
||||
mode = _validate_mode(mode)
|
||||
windows, cost_bps, min_events, execution_lag_sessions = _validate_config(windows, cost_bps, min_events, execution_lag_sessions)
|
||||
try:
|
||||
vintages = _select_independent_vintages(vintage_store.list_vintages())
|
||||
price_entry = price_store.latest_snapshot_entry()
|
||||
except (VintageStoreError, PriceSourceError) as exc:
|
||||
raise ResearchRunError(str(exc)) from exc
|
||||
raise ResearchRunError(f"research input integrity validation failed: {exc}") from exc
|
||||
vintage_gate = assess_backtest_readiness(vintages, min_events=min_events)
|
||||
validated_vintage_snapshots: dict[str, dict[str, Any]] = {}
|
||||
try:
|
||||
@@ -219,9 +420,11 @@ def run_tourism_research(
|
||||
**price_entry,
|
||||
"point_in_time": price_source.get("point_in_time"),
|
||||
"quality": price_source.get("quality"),
|
||||
"archive_contract": price_source.get("archive_contract"),
|
||||
"provider_release_id": price_source.get("provider_release_id"),
|
||||
"normalized_snapshot_hash": price_source.get("normalized_snapshot_hash"),
|
||||
}
|
||||
price_gate = _price_gate(price_gate_entry)
|
||||
price_gate = _price_gate(price_gate_entry, mode)
|
||||
input_vintages = [
|
||||
{
|
||||
"vintage_id": entry.get("vintage_id"),
|
||||
@@ -229,17 +432,28 @@ def run_tourism_research(
|
||||
"as_of": entry.get("as_of"),
|
||||
"published_at": entry.get("published_at"),
|
||||
"raw_payload_hash": entry.get("raw_payload_hash"),
|
||||
"normalized_snapshot_hash": entry.get("normalized_snapshot_hash"),
|
||||
"normalized_hash_algorithm": entry.get("normalized_hash_algorithm"),
|
||||
"parser_version": entry.get("parser_version"),
|
||||
"revision_status": entry.get("revision_status"),
|
||||
}
|
||||
for entry in vintages
|
||||
]
|
||||
input_price = copy.deepcopy(price_gate_entry) if price_gate_entry else None
|
||||
input_price = (
|
||||
{
|
||||
key: copy.deepcopy(value)
|
||||
for key, value in price_gate_entry.items()
|
||||
if key not in _OBSERVATION_RUNTIME_FIELDS
|
||||
}
|
||||
if price_gate_entry
|
||||
else None
|
||||
)
|
||||
config = {
|
||||
"min_events": min_events,
|
||||
"windows": windows,
|
||||
"cost_bps": cost_bps,
|
||||
"execution_lag_sessions": execution_lag_sessions,
|
||||
"mode": mode,
|
||||
}
|
||||
input_fingerprint = _canonical_hash({"theme": "tourism", "config": config, "vintages": input_vintages, "price_snapshot": input_price})
|
||||
run_id = f"tourism-run-{input_fingerprint[:16]}"
|
||||
@@ -255,6 +469,8 @@ def run_tourism_research(
|
||||
"status": "blocked",
|
||||
"reason": None,
|
||||
"generated_at": generated_at,
|
||||
"research_mode": mode,
|
||||
"result_scope": "blocked",
|
||||
"config": config,
|
||||
"gates": {"vintages": vintage_gate, "prices": price_gate},
|
||||
"inputs": {"vintages": input_vintages, "price_snapshot": input_price},
|
||||
@@ -262,7 +478,7 @@ def run_tourism_research(
|
||||
if vintage_gate["status"] != "ready":
|
||||
report["reason"] = vintage_gate["reason"]
|
||||
return run_store.persist(report)
|
||||
if price_gate["status"] != "ready":
|
||||
if price_gate["status"] == "blocked":
|
||||
report["reason"] = price_gate["reason"]
|
||||
return run_store.persist(report)
|
||||
if not price_entry or price_snapshot is None:
|
||||
@@ -294,13 +510,21 @@ def run_tourism_research(
|
||||
cost_bps=cost_bps,
|
||||
min_events=min_events,
|
||||
execution_lag_sessions=execution_lag_sessions,
|
||||
require_price_known_at=mode == "validated",
|
||||
)
|
||||
except (FileNotFoundError, VintageStoreError, EventStudyError, ResearchRunError, KeyError, TypeError, ValueError) as exc:
|
||||
report["reason"] = "research_inputs_invalid"
|
||||
report["error"] = str(exc)
|
||||
return run_store.persist(report)
|
||||
report["status"] = "ready"
|
||||
report["status"] = "descriptive_only" if mode == "exploratory" else "ready"
|
||||
report["reason"] = None
|
||||
report["result_scope"] = "validated_pit_event_study" if mode == "validated" else "non_pit_descriptive_only"
|
||||
if mode == "exploratory":
|
||||
report["limitations"] = ["This result is descriptive only and must not be used as validated backtest evidence."]
|
||||
if price_source.get("point_in_time") is not True:
|
||||
report["limitations"].insert(0, "Historical price data may be revised vendor history and is not point-in-time validated.")
|
||||
else:
|
||||
report["limitations"].insert(0, "Point-in-time-capable inputs are intentionally not promoted by exploratory mode.")
|
||||
report["result"] = result
|
||||
report["input_summary"] = {
|
||||
"event_count": len(events),
|
||||
|
||||
+402
-12
@@ -28,27 +28,54 @@ log = logging.getLogger("set50.scheduler")
|
||||
# collectors returning a .to_dict()/dict, keyed by cache key
|
||||
# (imported lazily to avoid import cycles at module load)
|
||||
# `fetch_module` = the FACTORS.fetch module name this job feeds (for history).
|
||||
# `frequency` = natural refresh cadence of the source. A job is only run
|
||||
# once its cooldown window has elapsed — the strategy rebalances
|
||||
# a few times a year, so polling slow sources hourly wastes
|
||||
# resources. Values: daily | weekly | monthly | quarterly.
|
||||
_REFRESH_JOBS: List[dict] = [
|
||||
{"key": "bot_tourism", "label": "ท่องเที่ยว (BOT)", "module": "bot_tourism", "fn": "BotTourismSource().fetch", "fetch_module": "macro_thai"},
|
||||
{"key": "auto_credit/tourism", "label": "ยอดขายรถ (TradingEconomics)", "module": "auto_credit", "fn": "fetch_auto_credit", "fetch_module": "auto_credit"},
|
||||
{"key": "auto_npl", "label": "NPL รถยนต์ (BOT)", "module": "auto_npl", "fn": "fetch_auto_npl", "fetch_module": "auto_npl"},
|
||||
{"key": "energy_thai", "label": "โรงกลั่น TOP", "module": "energy_thai", "fn": "fetch_energy_thai", "fetch_module": "energy_thai"},
|
||||
{"key": "macro_thai", "label": "ภาพรวมประเทศไทย (BOT)", "module": "macro_thai", "fn": "fetch_macro_thai", "fetch_module": "macro_thai"},
|
||||
{"key": "bank_npl", "label": "NPL ภาคการเงิน (BOT)", "module": "bank_npl", "fn": "fetch_bank_npl", "fetch_module": "bank_npl"},
|
||||
{"key": "bot_tourism", "label": "ท่องเที่ยว (BOT)", "module": "bot_tourism", "fn": "BotTourismSource().fetch", "fetch_module": "macro_thai", "frequency": "monthly"},
|
||||
{"key": "auto_credit/tourism", "label": "ยอดขายรถ (TradingEconomics)", "module": "auto_credit", "fn": "fetch_auto_credit", "fetch_module": "auto_credit", "frequency": "monthly"},
|
||||
{"key": "auto_npl", "label": "NPL รถยนต์ (BOT)", "module": "auto_npl", "fn": "fetch_auto_npl", "fetch_module": "auto_npl", "frequency": "quarterly"},
|
||||
{"key": "energy_thai", "label": "โรงกลั่น TOP", "module": "energy_thai", "fn": "fetch_energy_thai", "fetch_module": "energy_thai", "frequency": "quarterly"},
|
||||
{"key": "energy_irpc", "label": "โรงกลั่น IRPC", "module": "energy_irpc", "fn": "fetch_energy_irpc", "fetch_module": "energy_irpc", "frequency": "quarterly"},
|
||||
{"key": "macro_thai", "label": "ภาพรวมประเทศไทย (BOT)", "module": "macro_thai", "fn": "fetch_macro_thai", "fetch_module": "macro_thai", "frequency": "monthly"},
|
||||
{"key": "bank_npl", "label": "NPL ภาคการเงิน (BOT)", "module": "bank_npl", "fn": "fetch_bank_npl", "fetch_module": "bank_npl", "frequency": "quarterly"},
|
||||
{"key": "thai_trade", "label": "ดุลการค้า/ส่งออก (TradingEconomics)", "module": "thai_trade", "fn": "fetch_thai_trade", "fetch_module": "thai_trade", "frequency": "monthly"},
|
||||
{"key": "te_thailand", "label": "อัตราดอกเบี้ย/สินเชื่อ/ค้าปลีก/เชื่อมั่น (TE)", "module": "te_thailand", "fn": "fetch_te_thailand", "fetch_module": "te_thailand", "frequency": "monthly"},
|
||||
]
|
||||
|
||||
# Frequencies -> minimum seconds between successful refreshes of a job.
|
||||
# These implement the "adjust cadence to the source" requirement.
|
||||
_FREQ_SECONDS: dict[str, int] = {
|
||||
"daily": 24 * 3600,
|
||||
"weekly": 7 * 24 * 3600,
|
||||
"monthly": 30 * 24 * 3600,
|
||||
"quarterly": 91 * 24 * 3600,
|
||||
}
|
||||
|
||||
# Data that legitimately changes every day (or faster) is refreshed separately
|
||||
# at a daily cadence rather than on the slow factor loop.
|
||||
_DAILY_JOBS: List[dict] = [
|
||||
{"key": "siamchart_vintages", "label": "Siamchart SET50 snapshot (vintage)", "fn": "_collect_siamchart_daily", "frequency": "daily"},
|
||||
{"key": "price_snapshot", "label": "ราคาหุ้น SET50 (Yahoo)", "fn": "_refresh_price_snapshot", "frequency": "daily"},
|
||||
]
|
||||
|
||||
|
||||
class AppDataScheduler:
|
||||
"""Runs periodic refresh of the real data collectors inside the app."""
|
||||
|
||||
def __init__(self, cache, data_root: Path, interval_seconds: int = 3600):
|
||||
def __init__(self, cache, data_root: Path, interval_seconds: int = 3600,
|
||||
dividend_cooldown_seconds: int = 6 * 3600):
|
||||
self.cache = cache
|
||||
self.data_root = data_root
|
||||
self.interval = max(30, int(interval_seconds)) # never faster than 30s
|
||||
self.dividend_cooldown = max(300, int(dividend_cooldown_seconds)) # >=5min
|
||||
self._stop = threading.Event()
|
||||
self._thread: Optional[threading.Thread] = None
|
||||
self._snap_dir = data_root / "scheduler"
|
||||
self._snap_dir.mkdir(parents=True, exist_ok=True)
|
||||
self._div_marker = self._snap_dir / "dividends_last_refresh.json"
|
||||
self._lock = threading.Lock()
|
||||
|
||||
# -- public lifecycle ---------------------------------------------------
|
||||
def start(self) -> None:
|
||||
@@ -73,20 +100,103 @@ class AppDataScheduler:
|
||||
log.exception("set50 scheduler refresh_all failed (will retry)")
|
||||
|
||||
def refresh_all(self) -> list[dict]:
|
||||
"""Run every collector, warm the daily cache, snapshot the state, and
|
||||
append each factor's value to the historical store (P4 enabler)."""
|
||||
"""Run each collector (respecting its natural cadence), warm the cache,
|
||||
snapshot state, write vintages, and log per-source health.
|
||||
|
||||
Slow sources (monthly/quarterly factors, dividends, Siamchart) are only
|
||||
re-fetched once their cooldown has elapsed; only daily-changing data
|
||||
(prices) runs every eligible tick. This keeps resource usage aligned
|
||||
with how often the data actually changes (the strategy rebalances a few
|
||||
times a year) while still front-loading an initial refresh at boot.
|
||||
"""
|
||||
results: list[dict] = []
|
||||
fetched_by_module: dict[str, dict] = {}
|
||||
|
||||
for job in _REFRESH_JOBS:
|
||||
if not self._job_due(job):
|
||||
continue
|
||||
res = self._run_job(job)
|
||||
results.append(res)
|
||||
fetch_module = job.get("fetch_module")
|
||||
if res.get("ok") and isinstance(res.get("value"), dict) and fetch_module:
|
||||
fetched_by_module[fetch_module] = res["value"]
|
||||
if res.get("ok"):
|
||||
self._mark_job_run(job)
|
||||
fetch_module = job.get("fetch_module")
|
||||
if isinstance(res.get("value"), dict) and fetch_module:
|
||||
fetched_by_module[fetch_module] = res["value"]
|
||||
|
||||
# daily cadence data (Siamchart vintages + price snapshots)
|
||||
for djob in _DAILY_JOBS:
|
||||
if not self._job_due(djob):
|
||||
continue
|
||||
try:
|
||||
fn = getattr(self, djob["fn"])
|
||||
fn()
|
||||
self._mark_job_run(djob)
|
||||
results.append({"key": djob["key"], "label": djob["label"],
|
||||
"ok": True, "at": self._now()})
|
||||
except Exception as exc: # noqa: BLE001 — non-fatal
|
||||
results.append({"key": djob["key"], "label": djob["label"],
|
||||
"ok": False, "error": str(exc), "at": self._now()})
|
||||
|
||||
self._record_history(fetched_by_module)
|
||||
self._record_pit_factor_vintages(fetched_by_module)
|
||||
self._maybe_refresh_dated_dividends()
|
||||
self._write_marker(results)
|
||||
self._append_source_log(results)
|
||||
return results
|
||||
|
||||
# -- per-job cadence cooldown ------------------------------------------
|
||||
def _job_marker_path(self, job: dict) -> Path:
|
||||
safe = "".join(c if (c.isalnum() or c in "._-") else "_" for c in job["key"])
|
||||
return self._snap_dir / f"job_{safe}.json"
|
||||
|
||||
def _job_due(self, job: dict) -> bool:
|
||||
"""True if the job's cooldown (from its `frequency`) has elapsed."""
|
||||
import json
|
||||
import datetime as _dt
|
||||
freq = job.get("frequency")
|
||||
cooldown = _FREQ_SECONDS.get(freq if isinstance(freq, str) else "daily", _FREQ_SECONDS["daily"])
|
||||
path = self._job_marker_path(job)
|
||||
if not path.is_file():
|
||||
return True # never run -> run at boot
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
last = _dt.datetime.fromisoformat(data["at"])
|
||||
elapsed = (_dt.datetime.now().astimezone() - last).total_seconds()
|
||||
return elapsed >= cooldown
|
||||
except (OSError, ValueError, KeyError):
|
||||
return True # corrupt/missing marker -> allow retry
|
||||
|
||||
def _mark_job_run(self, job: dict) -> None:
|
||||
import json
|
||||
try:
|
||||
self._job_marker_path(job).write_text(
|
||||
json.dumps({"at": self._now()}), encoding="utf-8")
|
||||
except OSError:
|
||||
log.exception("could not write job marker for %s", job["key"])
|
||||
|
||||
def _refresh_price_snapshot(self) -> None:
|
||||
"""Refresh the SET50 Yahoo price snapshot (daily cadence).
|
||||
|
||||
Pulls live daily bars over a rolling ~3y window into the price snapshot
|
||||
store so valuation and next-trading-day execution use fresh prices. This
|
||||
is the one data type that legitimately changes every trading day, so it
|
||||
runs on the daily cadence rather than the slow factor loop. Non-fatal:
|
||||
on network failure the previous snapshot is retained.
|
||||
"""
|
||||
import datetime as _dt
|
||||
from .prices import collect_price_snapshot, PriceSourceError
|
||||
# rolling window: start ~3y back (enough history for momentum + next-day
|
||||
# execution), end = yesterday (SET session close is the latest tradable).
|
||||
today = _dt.date.today()
|
||||
start = (today - _dt.timedelta(days=3 * 366)).isoformat()
|
||||
end = (today - _dt.timedelta(days=1)).isoformat()
|
||||
prices_dir = self.data_root / "prices"
|
||||
try:
|
||||
collect_price_snapshot(prices_dir, start=start, end=end)
|
||||
except PriceSourceError as exc:
|
||||
log.warning("set50 price snapshot refresh failed (non-fatal): %s", exc)
|
||||
raise
|
||||
|
||||
def _record_history(self, fetched_by_module: dict[str, dict]) -> None:
|
||||
"""Append current factor values to the historical store (append-only).
|
||||
|
||||
@@ -101,6 +211,181 @@ class AppDataScheduler:
|
||||
except Exception: # noqa: BLE001 — never let history break the refresh loop
|
||||
log.exception("set50 factor-history record failed (non-fatal)")
|
||||
|
||||
def _record_pit_factor_vintages(self, fetched_by_module: dict[str, dict]) -> None:
|
||||
"""Write each factor's current PIT vintage into the strict PIT store.
|
||||
|
||||
The strict backtest (`backtest_readiness`) reads *this* store, so the
|
||||
scheduler must keep it populated or strict runs stay blocked forever.
|
||||
We use the honest, evidence-safe timestamps available at collection
|
||||
time: ``released_at == retrieved_at == now`` — we do NOT assume a
|
||||
reporting lag we do not know, so we only claim the value was knowable
|
||||
from the moment we actually collected it. A point is appended only when
|
||||
the factor's value differs from its last stored value, so repeated
|
||||
ticks do not spam rows. This runs on the deployed server too, so
|
||||
vintages accumulate wherever the app runs.
|
||||
"""
|
||||
from . import factors as factors_mod
|
||||
from .factor_vintages import FactorVintageStore, FactorVintageError
|
||||
try:
|
||||
store = FactorVintageStore(self.data_root)
|
||||
except Exception: # noqa: BLE001
|
||||
log.exception("set50 PIT-vintage store init failed (non-fatal)")
|
||||
return
|
||||
now = self._now() # tz-aware ISO (UTC seconds)
|
||||
for fkey, fact in factors_mod.FACTORS.items():
|
||||
if not fact.get("fetch"):
|
||||
continue
|
||||
val = factors_mod.factor_value(fact, fetched_by_module.get(fact.get("fetch")))
|
||||
if val is None:
|
||||
continue
|
||||
try:
|
||||
last = store.value_at(fkey, now)
|
||||
except FactorVintageError:
|
||||
last = None
|
||||
if last is not None and abs(last - val) < 1e-9:
|
||||
continue # unchanged since last stored -> skip
|
||||
try:
|
||||
store.record(
|
||||
fkey, val,
|
||||
observed_at=now, released_at=now,
|
||||
retrieved_at=now, source=str(fact.get("source") or ""),
|
||||
)
|
||||
except FactorVintageError as exc:
|
||||
log.warning("set50 PIT vintage skip %s: %s", fkey, exc)
|
||||
|
||||
def _record_siamchart_vintages(self) -> None:
|
||||
"""Persist the current Siamchart SET50 snapshot as a vintage chain.
|
||||
|
||||
This makes the fundamental (40%) dimension reconstructible for strict
|
||||
PIT backtests. Idempotent: ``SiamchartVintageStore.persist`` dedupes by
|
||||
``retrieved_at`` + body hash, so re-inserting an unchanged snapshot is a
|
||||
no-op. Non-fatal on network error. Reads the same latest snapshot file
|
||||
the dashboard uses (``backend/data/siamchart/set50_master.json``).
|
||||
"""
|
||||
import json
|
||||
from .siamchart_vintages import SiamchartVintageStore, SiamchartVintageError
|
||||
path = self.data_root / "siamchart" / "set50_master.json"
|
||||
try:
|
||||
if not path.is_file():
|
||||
return
|
||||
snap = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError) as exc:
|
||||
log.warning("set50 siamchart snapshot unreadable: %s", exc)
|
||||
return
|
||||
if not isinstance(snap, dict) or not snap:
|
||||
return
|
||||
try:
|
||||
store = SiamchartVintageStore(self.data_root)
|
||||
store.persist(snap)
|
||||
except SiamchartVintageError as exc:
|
||||
log.warning("set50 siamchart vintage skip: %s", exc)
|
||||
except Exception: # noqa: BLE001
|
||||
log.exception("set50 siamchart vintage persist failed (non-fatal)")
|
||||
|
||||
def _collect_siamchart_daily(self) -> None:
|
||||
"""Daily: fetch the Siamchart SET50 fundamental board, write the master
|
||||
snapshot, and persist a vintage (so dashboard + strict backtest are fed).
|
||||
|
||||
This is what actually puts stocks on the dashboard page: on a fresh
|
||||
deploy the volume starts empty (no ``set50_master.json``), so the board
|
||||
stays blank until the first successful daily collection. We fetch the
|
||||
group table (``fetch_financial``) then each symbol's stock-info page
|
||||
for ratios/income (``fetch_stock_info``), write ``set50_master.json``
|
||||
(the exact shape ``_load_siamchart_snapshot``/``siamchart_factors``
|
||||
consume), and finally record a vintage.
|
||||
|
||||
Failures are logged to the source-health panel via the caller's
|
||||
exception handling; on network error the previous master is retained.
|
||||
"""
|
||||
import datetime as _dt
|
||||
import json
|
||||
from . import siamchart
|
||||
from .siamchart_vintages import SiamchartVintageStore, SiamchartVintageError
|
||||
|
||||
rows = siamchart.fetch_financial("SET50")
|
||||
details: dict = {}
|
||||
for row in rows:
|
||||
try:
|
||||
info = siamchart.fetch_stock_info(row.symbol)
|
||||
details[row.symbol] = info.to_dict()
|
||||
except siamchart.SiamchartError as exc:
|
||||
log.warning("set50 stock-info %s failed: %s", row.symbol, exc)
|
||||
details[row.symbol] = {"error": str(exc)}
|
||||
|
||||
now_utc = _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
payload = {
|
||||
"source": "siamchart",
|
||||
"retrieved_at": now_utc,
|
||||
"mode": "group",
|
||||
"group": "SET50",
|
||||
"url": siamchart.build_url("SET50"),
|
||||
"count": len(rows),
|
||||
"rows": [row.to_dict() for row in rows],
|
||||
"details": details,
|
||||
"details_count": len(details),
|
||||
}
|
||||
out = self.data_root / "siamchart" / "set50_master.json"
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(payload, ensure_ascii=False, sort_keys=True, indent=2),
|
||||
encoding="utf-8")
|
||||
log.info("set50 siamchart board collected (%d rows, %d details)",
|
||||
len(rows), len(details))
|
||||
|
||||
# persist a vintage so the strict backtest fundamental is PIT
|
||||
try:
|
||||
store = SiamchartVintageStore(self.data_root)
|
||||
store.persist(payload)
|
||||
except SiamchartVintageError as exc:
|
||||
log.warning("set50 siamchart vintage persist failed after collect: %s", exc)
|
||||
|
||||
def _maybe_refresh_dated_dividends(self) -> None:
|
||||
"""Cooldown-gated fetch of real dated dividend history into the ledger.
|
||||
|
||||
Dividend history changes slowly (a few times a year per name), so we
|
||||
only re-fetch at most once per ``dividend_cooldown`` (default 6h), not
|
||||
every refresh tick. Non-fatal: a network failure leaves the previous
|
||||
ledger intact and just postpones the next update.
|
||||
"""
|
||||
with self._lock:
|
||||
if self._dividends_fresh():
|
||||
return
|
||||
try:
|
||||
from .dividend_ledger import DividendLedger, populate_dated_dividends
|
||||
from .siamchart import fetch_dividend_history
|
||||
from .siamchart_factors import build_factor_view
|
||||
ledger = DividendLedger(self.data_root / "dividends" / "ledger.json")
|
||||
fv = build_factor_view()
|
||||
symbols = [f["symbol"] for f in fv.get("factors", [])]
|
||||
populate_dated_dividends(ledger, symbols, fetch_dividend_history)
|
||||
ledger.save()
|
||||
self._mark_dividends_refreshed()
|
||||
log.info("set50 dated-dividend ledger refreshed (%d symbols)", len(symbols))
|
||||
except Exception: # noqa: BLE001 — non-fatal
|
||||
log.exception("set50 dated-dividend refresh failed (will retry next cooldown)")
|
||||
|
||||
def _dividends_fresh(self) -> bool:
|
||||
import json
|
||||
import datetime as _dt
|
||||
if not self._div_marker.is_file():
|
||||
return False
|
||||
try:
|
||||
payload = json.loads(self._div_marker.read_text(encoding="utf-8"))
|
||||
last = _dt.datetime.fromisoformat(payload["at"])
|
||||
return (_dt.datetime.now().astimezone() - last).total_seconds() < self.dividend_cooldown
|
||||
except (OSError, ValueError, KeyError):
|
||||
return False
|
||||
|
||||
def _mark_dividends_refreshed(self) -> None:
|
||||
import json
|
||||
import datetime as _dt
|
||||
try:
|
||||
self._div_marker.write_text(
|
||||
json.dumps({"at": _dt.datetime.now().astimezone().isoformat(timespec="seconds")}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
except OSError:
|
||||
log.exception("could not write dividend refresh marker")
|
||||
|
||||
def _run_job(self, job: dict) -> dict:
|
||||
key = job["key"]
|
||||
label = job["label"]
|
||||
@@ -153,6 +438,111 @@ class AppDataScheduler:
|
||||
except OSError:
|
||||
log.exception("could not write scheduler marker")
|
||||
|
||||
def _append_source_log(self, results: list[dict]) -> None:
|
||||
"""Append this refresh tick's per-source outcome to a durable health log
|
||||
the frontend can render (with a one-click copy), and analyze failures.
|
||||
|
||||
Stored at ``data/scheduler/source_health.json`` (ring buffer, newest
|
||||
first). Each entry categorizes the failure (network / http / parse /
|
||||
structure / auth / other) so a source that "changed its page structure"
|
||||
is distinguishable from a transient network blip.
|
||||
"""
|
||||
import json
|
||||
if not results:
|
||||
return
|
||||
path = self._snap_dir / "source_health.json"
|
||||
try:
|
||||
existing = []
|
||||
if path.is_file():
|
||||
existing = json.loads(path.read_text(encoding="utf-8"))
|
||||
if not isinstance(existing, list):
|
||||
existing = []
|
||||
except (OSError, ValueError):
|
||||
existing = []
|
||||
entries = []
|
||||
for r in results:
|
||||
category = "ok"
|
||||
if not r.get("ok"):
|
||||
category = self._analyze_error(r.get("error", ""))
|
||||
entries.append({
|
||||
"key": r.get("key"), "label": r.get("label"),
|
||||
"ok": bool(r.get("ok")), "category": category,
|
||||
"at": r.get("at") or self._now(),
|
||||
"detail": str(r.get("error") or "")[:500],
|
||||
})
|
||||
# newest-first ring buffer, cap at 500 entries
|
||||
combined = entries + existing
|
||||
combined = combined[:500]
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(combined, ensure_ascii=False), encoding="utf-8")
|
||||
except OSError:
|
||||
log.exception("could not write source-health log")
|
||||
|
||||
@staticmethod
|
||||
def _analyze_error(message: str) -> str:
|
||||
"""Classify a failure reason so the frontend can guide diagnosis.
|
||||
|
||||
Keys off the exception message/type text. Returns one of:
|
||||
network, timeout, http, parse, structure, auth, other.
|
||||
"""
|
||||
m = (message or "").lower()
|
||||
if not m:
|
||||
return "other"
|
||||
if any(t in m for t in ("timed out", "timeout", "timedout")):
|
||||
return "timeout"
|
||||
if any(t in m for t in ("no such host", "connection refused",
|
||||
"name or service not known", "network is unreachable",
|
||||
"connection reset", "getaddrinfo", "dns")):
|
||||
return "network"
|
||||
if any(t in m for t in ("http ", "status", "response code", "403", "404",
|
||||
"429", "502", "503")):
|
||||
return "http"
|
||||
if any(t in m for t in ("json decode", "parse", "unable to find",
|
||||
"regex", "no match", "value not found",
|
||||
"expecting value", "jsondecodeerror")):
|
||||
return "parse"
|
||||
if any(t in m for t in ("structure", "schema", "changed", "column",
|
||||
"field missing", "keyerror", "attributeerror")):
|
||||
return "structure"
|
||||
if any(t in m for t in ("auth", "login", "token", "credentials",
|
||||
"unauthorized", "forbidden", "401")):
|
||||
return "auth"
|
||||
return "other"
|
||||
|
||||
def _load_source_health(self, limit: int = 200) -> list[dict]:
|
||||
"""Return the most recent source-health entries (for the API/UI).
|
||||
|
||||
Only the LATEST entry per source key is returned (the owner's rule: the
|
||||
health panel should show one row per source with its last outcome, not a
|
||||
history of every refresh). Entries are ordered newest-first.
|
||||
"""
|
||||
import json
|
||||
path = self._snap_dir / "source_health.json"
|
||||
if not path.is_file():
|
||||
return []
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return []
|
||||
if not isinstance(data, list):
|
||||
return []
|
||||
# newest-first by "at" (the store writes append-only, newest last, so
|
||||
# iterate from the end); keep only the first occurrence of each key.
|
||||
seen: set = set()
|
||||
latest: list[dict] = []
|
||||
for entry in reversed(data):
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
key = entry.get("key")
|
||||
if key is None or key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
latest.append(entry)
|
||||
if len(latest) >= limit:
|
||||
break
|
||||
return latest
|
||||
|
||||
@staticmethod
|
||||
def _now() -> str:
|
||||
import datetime as _dt
|
||||
|
||||
+46
-16
@@ -1,8 +1,7 @@
|
||||
"""Capital-allocation simulation/backtest engine.
|
||||
"""Capital-allocation engine for the "จัดสรรทุน (Suggestion)" endpoint.
|
||||
|
||||
Reusable for both backtest (historical) and forward test (paper, no MT5 send) —
|
||||
the user asked these share one engine, differing only in whether an MT5 order is
|
||||
dispatched. Pure local research; never sends a real order.
|
||||
Pure local research; never sends a real order. This is a live recommendation
|
||||
on the current board (non-PIT) — forward-test mode was removed per the user.
|
||||
|
||||
Allocation rules (confirmed by the user, 2026-08-25):
|
||||
|
||||
@@ -41,6 +40,12 @@ class Candidate:
|
||||
combined_score: float
|
||||
is_dividend: bool
|
||||
dividend_yield: float
|
||||
# Owner's "ทำกำไร" definition: a price-trend (momentum) score; and theme
|
||||
# signal gate (when provided: must be > 0 to be eligible for profit buckets).
|
||||
# None = "unspecified" (e.g. backtest path) -> not gated. momentum=None means
|
||||
# no price-trend signal given -> not gated (rank as 0).
|
||||
momentum: Optional[float] = None
|
||||
theme_signal: Optional[float] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -76,13 +81,30 @@ class AllocationResult:
|
||||
# B1: price-series loader
|
||||
# ---------------------------------------------------------------------------
|
||||
def load_price_snapshot(snapshot_path: Optional[Path] = None) -> dict:
|
||||
"""Load the newest Yahoo price snapshot: {symbol: {bars: [...]}}."""
|
||||
"""Load the newest Yahoo price snapshot: {symbol: {bars: [...]}}.
|
||||
|
||||
'Newest' = the snapshot with the latest ``retrieved_at``, NOT the last
|
||||
filename lexicographically (a partial 9-symbol collection can sort after a
|
||||
full 50-symbol one, which would silently drop most of the universe).
|
||||
"""
|
||||
if snapshot_path is None:
|
||||
snap_dir = _PRICES_DIR / "snapshots"
|
||||
files = sorted(snap_dir.glob("prices-yahoo-chart-*.json"))
|
||||
files = list(snap_dir.glob("prices-yahoo-chart-*.json"))
|
||||
if not files:
|
||||
raise SimulationError("no Yahoo price snapshot found on disk")
|
||||
snapshot_path = files[-1]
|
||||
# pick the snapshot retrieved most recently by timestamp embedded in
|
||||
# its source metadata (fall back to the newest filename on any error).
|
||||
best: Optional[Path] = None
|
||||
best_ts: Optional[str] = None
|
||||
for f in files:
|
||||
try:
|
||||
blob = json.loads(f.read_text(encoding="utf-8"))
|
||||
ts = (blob.get("source") or {}).get("retrieved_at") or ""
|
||||
except Exception:
|
||||
ts = ""
|
||||
if best is None or (ts and ts > best_ts):
|
||||
best, best_ts = f, ts
|
||||
snapshot_path = best or files[-1]
|
||||
data = json.loads(snapshot_path.read_text(encoding="utf-8"))
|
||||
return data.get("series", {})
|
||||
|
||||
@@ -113,9 +135,16 @@ def allocate_capital(
|
||||
if not candidates:
|
||||
raise SimulationError("no candidates to allocate")
|
||||
|
||||
# sort all by combined_score desc (used for bucket 1 & 2 ranking)
|
||||
by_score = sorted(candidates, key=lambda c: -c.combined_score)
|
||||
# bucket 3 ranked by dividend yield desc among dividend payers
|
||||
# "ทำกำไร" = price likely to rise (POSITIVE momentum) + positive theme signal
|
||||
# + a NON-NEGATIVE combined score (owner: a stock with a negative overall
|
||||
# score must not be recommended in the profit buckets). This is the owner's
|
||||
# definition — NOT EPS-growth ranking. Buckets 1 & 2 rank by momentum within
|
||||
# this gated pool; bucket 3 ranks purely by dividend yield.
|
||||
profit_pool = [c for c in candidates
|
||||
if (c.theme_signal is None or c.theme_signal > 0.0)
|
||||
and (c.momentum is None or c.momentum > 0.0)
|
||||
and c.combined_score > 0.0]
|
||||
by_momentum = sorted(profit_pool, key=lambda c: -(c.momentum or 0.0))
|
||||
by_yield = sorted(
|
||||
(c for c in candidates if c.is_dividend and c.dividend_yield > 0),
|
||||
key=lambda c: -c.dividend_yield,
|
||||
@@ -137,11 +166,12 @@ def allocate_capital(
|
||||
sort_by: str = "combined_score"):
|
||||
nonlocal cash, used
|
||||
remaining = cash[bucket_idx]
|
||||
# bucket 3 must rank by dividend_yield (ignoring score); others by score.
|
||||
# bucket 3 must rank by dividend_yield (ignoring score); buckets 1/2
|
||||
# rank by price-trend momentum (the owner's "ทำกำไร" definition).
|
||||
if sort_by == "dividend_yield":
|
||||
key = lambda c: -c.dividend_yield
|
||||
else:
|
||||
key = lambda c: -c.combined_score
|
||||
key = lambda c: -(c.momentum or 0.0)
|
||||
for cand in sorted(eligible, key=key):
|
||||
if cand.symbol in used:
|
||||
continue
|
||||
@@ -166,10 +196,10 @@ def allocate_capital(
|
||||
result.bucket_allocation[bucket_idx + 1] - remaining
|
||||
)
|
||||
|
||||
# Bucket 1: dividend-paying, highest score
|
||||
_fill(0, [c for c in by_score if c.is_dividend], require_dividend=True)
|
||||
# Bucket 2: non-dividend, highest score
|
||||
_fill(1, [c for c in by_score if not c.is_dividend], require_dividend=False)
|
||||
# Bucket 1: dividend-paying, highest momentum (theme gate already applied)
|
||||
_fill(0, [c for c in by_momentum if c.is_dividend], require_dividend=True)
|
||||
# Bucket 2: non-dividend, highest momentum (theme gate already applied)
|
||||
_fill(1, [c for c in by_momentum if not c.is_dividend], require_dividend=False)
|
||||
# Bucket 3: highest dividend yield (ignoring score), excluding symbols bought
|
||||
_fill(2, by_yield, require_dividend=True, sort_by="dividend_yield")
|
||||
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
"""Thailand rates / credit / retail / confidence / property factors — TradingEconomics.
|
||||
|
||||
Source pages (server-rendered HTML, same infrastructure as `thai_trade` /
|
||||
`auto_credit` — the "related indicators" table exposes a stable 5-column row
|
||||
`[label, value, prev, unit, period]`):
|
||||
|
||||
- https://tradingeconomics.com/thailand/interest-rate
|
||||
Interest Rate, Loans to Non Financial Corporations, Banks Balance Sheet
|
||||
- https://tradingeconomics.com/thailand/consumer-confidence
|
||||
Consumer Confidence, Retail Sales YoY, Consumer Credit, Households Debt
|
||||
to GDP, Consumer Spending
|
||||
- https://tradingeconomics.com/thailand/housing-index
|
||||
Residential Property Prices, Housing Index, Housing Starts
|
||||
- https://tradingeconomics.com/thailand/business-confidence
|
||||
Business Confidence, Leading Economic Index, Private Investment MoM
|
||||
|
||||
This module deepens the macro-proxy themes that today rely only on the one BOT
|
||||
Thai-Economy page:
|
||||
|
||||
Factor contributes to
|
||||
---------------------------- -------------------------------------
|
||||
te_interest_rate -> banks (rate/credit cycle)
|
||||
te_loan_growth_level -> banks (credit demand)
|
||||
te_consumer_credit -> nonbank_finance (household credit book)
|
||||
te_household_debt_gdp -> nonbank_finance (household leverage risk)
|
||||
te_retail_sales_yoy -> retail, consumer_staples (spending)
|
||||
te_consumer_confidence -> retail, consumer_staples, nonbank (sentiment)
|
||||
te_property_prices -> property (residential price YoY)
|
||||
te_business_confidence -> telecom_it, property, healthcare (sentiment)
|
||||
|
||||
Every value is a single-page snapshot (current value + prev + period), so each
|
||||
factor is a *level / latest-period* driver — no history join required.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
_USER_AGENT = (
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
|
||||
)
|
||||
_URL_INTEREST = "https://tradingeconomics.com/thailand/interest-rate"
|
||||
_URL_CONFIDENCE = "https://tradingeconomics.com/thailand/consumer-confidence"
|
||||
_URL_HOUSING = "https://tradingeconomics.com/thailand/housing-index"
|
||||
_URL_BIZCONF = "https://tradingeconomics.com/thailand/business-confidence"
|
||||
|
||||
|
||||
class ThaiFactorsError(Exception):
|
||||
"""Raised when a TradingEconomics Thailand page cannot be fetched/parsed."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ThaiFactorsSnapshot:
|
||||
interest_rate_pct: Optional[float] = None # policy-rate proxy (Aug 2026: 1.00)
|
||||
loans_to_fin_corp: Optional[float] = None # THB mn (Jun 2026)
|
||||
consumer_credit_thbmn: Optional[float] = None # THB mn (Jun 2025)
|
||||
household_debt_gdp_pct: Optional[float] = None # % of GDP (Dec 2025)
|
||||
retail_sales_yoy: Optional[float] = None # % YoY (May 2026)
|
||||
consumer_confidence: Optional[float] = None # points (Jul 2026)
|
||||
consumer_spending: Optional[float] = None # THB mn (Jun 2026)
|
||||
property_prices_yoy: Optional[float] = None # residential prices % YoY (Mar 2026)
|
||||
business_confidence: Optional[float] = None # points (Jul 2026)
|
||||
periods: dict = field(default_factory=dict)
|
||||
source: str = "tradingeconomics.thai-factors"
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"source": self.source,
|
||||
"interest_rate_pct": self.interest_rate_pct,
|
||||
"loans_to_fin_corp": self.loans_to_fin_corp,
|
||||
"consumer_credit_thbmn": self.consumer_credit_thbmn,
|
||||
"household_debt_gdp_pct": self.household_debt_gdp_pct,
|
||||
"retail_sales_yoy": self.retail_sales_yoy,
|
||||
"consumer_confidence": self.consumer_confidence,
|
||||
"consumer_spending": self.consumer_spending,
|
||||
"property_prices_yoy": self.property_prices_yoy,
|
||||
"business_confidence": self.business_confidence,
|
||||
"periods": self.periods,
|
||||
}
|
||||
|
||||
|
||||
def _fetch(url: str, timeout: float = 30.0) -> str:
|
||||
req = Request(url, headers={"User-Agent": _USER_AGENT, "Accept": "text/html"})
|
||||
try:
|
||||
with urlopen(req, timeout=timeout) as resp:
|
||||
raw = resp.read()
|
||||
except Exception as exc:
|
||||
raise ThaiFactorsError(f"failed to fetch {url}: {exc}") from exc
|
||||
try:
|
||||
return raw.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
return raw.decode("latin-1", "ignore")
|
||||
|
||||
|
||||
def _cells(row_html: str) -> list[str]:
|
||||
return [
|
||||
html.unescape(re.sub(r"<[^>]+>", "", td)).strip()
|
||||
for td in re.findall(r"<td[^>]*>(.*?)</td>", row_html, re.S)
|
||||
if td.strip()
|
||||
]
|
||||
|
||||
|
||||
def _to_float(text: str) -> Optional[float]:
|
||||
text = text.replace(",", "").strip().replace("%", "")
|
||||
if not text or text in ("-", "N/A", "…"):
|
||||
return None
|
||||
try:
|
||||
return float(text)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _related_indicators(html_text: str) -> dict[str, dict]:
|
||||
"""Map normalized-label -> {value, prev, unit, period} from the related table.
|
||||
|
||||
Rows are `[label, value, prev, unit, period]` (5 cols). Keys are
|
||||
lowercased + stripped so a TradingEconomics label tweak (e.g. extra space /
|
||||
case change) does not silently drop a series. A label may appear more than
|
||||
once; first row that parses a numeric value wins.
|
||||
"""
|
||||
out: dict[str, dict] = {}
|
||||
for table in re.findall(r"<table[^>]*>(.*?)</table>", html_text, re.S):
|
||||
for row_html in re.findall(r"<tr[^>]*>(.*?)</tr>", table, re.S):
|
||||
cells = _cells(row_html)
|
||||
if len(cells) < 4:
|
||||
continue
|
||||
key = cells[0].strip().lower()
|
||||
value = _to_float(cells[1])
|
||||
if value is None:
|
||||
continue
|
||||
if key not in out or out[key].get("value") is None:
|
||||
out[key] = {
|
||||
"value": value,
|
||||
"prev": _to_float(cells[2]) if len(cells) > 2 else None,
|
||||
"unit": cells[3] if len(cells) > 3 else "",
|
||||
"period": cells[4] if len(cells) > 4 else "",
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
def parse_te_thailand_html(interest_html: str, confidence_html: str,
|
||||
housing_html: str = "", bizconf_html: str = "") -> ThaiFactorsSnapshot:
|
||||
"""Parse the TradingEconomics Thailand pages into one snapshot.
|
||||
|
||||
`housing_html` + `bizconf_html` are optional (Phase B property/business
|
||||
factors); when omitted those two factors are simply None.
|
||||
"""
|
||||
ir = _related_indicators(interest_html)
|
||||
cc = _related_indicators(confidence_html)
|
||||
hi = _related_indicators(housing_html) if housing_html else {}
|
||||
bc = _related_indicators(bizconf_html) if bizconf_html else {}
|
||||
|
||||
periods: dict = {}
|
||||
snap = ThaiFactorsSnapshot(
|
||||
interest_rate_pct=(ir.get("interest rate") or {}).get("value"),
|
||||
loans_to_fin_corp=(ir.get("loans to non financial corporations") or {}).get("value"),
|
||||
consumer_credit_thbmn=(cc.get("consumer credit") or {}).get("value"),
|
||||
household_debt_gdp_pct=(cc.get("households debt to gdp") or {}).get("value"),
|
||||
retail_sales_yoy=(cc.get("retail sales yoy") or {}).get("value"),
|
||||
consumer_confidence=(cc.get("consumer confidence") or {}).get("value"),
|
||||
# consumer_spending is surfaced here for display/debug only — it is not
|
||||
# registered as a FACTORS factor, so it does not feed a theme surprise.
|
||||
consumer_spending=(cc.get("consumer spending") or {}).get("value"),
|
||||
property_prices_yoy=(hi.get("residential property prices") or {}).get("value"),
|
||||
business_confidence=(bc.get("business confidence") or {}).get("value"),
|
||||
)
|
||||
for key, label, src in (
|
||||
("interest_rate_pct", "interest rate", ir),
|
||||
("retail_sales_yoy", "retail sales yoy", cc),
|
||||
("consumer_confidence", "consumer confidence", cc),
|
||||
("property_prices_yoy", "residential property prices", hi),
|
||||
("business_confidence", "business confidence", bc),
|
||||
):
|
||||
meta = src.get(label) or {}
|
||||
if meta and meta.get("period"):
|
||||
periods[key] = meta.get("period")
|
||||
|
||||
if snap.interest_rate_pct is None and snap.consumer_confidence is None \
|
||||
and snap.retail_sales_yoy is None:
|
||||
raise ThaiFactorsError(
|
||||
"no usable Thailand factor series found in TradingEconomics pages"
|
||||
)
|
||||
# attach parsed periods onto a copy (dataclass is frozen)
|
||||
return ThaiFactorsSnapshot(
|
||||
interest_rate_pct=snap.interest_rate_pct,
|
||||
loans_to_fin_corp=snap.loans_to_fin_corp,
|
||||
consumer_credit_thbmn=snap.consumer_credit_thbmn,
|
||||
household_debt_gdp_pct=snap.household_debt_gdp_pct,
|
||||
retail_sales_yoy=snap.retail_sales_yoy,
|
||||
consumer_confidence=snap.consumer_confidence,
|
||||
consumer_spending=snap.consumer_spending,
|
||||
property_prices_yoy=snap.property_prices_yoy,
|
||||
business_confidence=snap.business_confidence,
|
||||
periods=periods,
|
||||
)
|
||||
|
||||
|
||||
def fetch_te_thailand(timeout: float = 30.0) -> ThaiFactorsSnapshot:
|
||||
interest_html = _fetch(_URL_INTEREST, timeout=timeout)
|
||||
confidence_html = _fetch(_URL_CONFIDENCE, timeout=timeout)
|
||||
housing_html = _fetch(_URL_HOUSING, timeout=timeout)
|
||||
bizconf_html = _fetch(_URL_BIZCONF, timeout=timeout)
|
||||
return parse_te_thailand_html(interest_html, confidence_html,
|
||||
housing_html, bizconf_html)
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Thailand external-sector / trade factor — TradingEconomics Thailand.
|
||||
|
||||
Source: https://tradingeconomics.com/thailand/current-account
|
||||
(server-rendered HTML, same infobox/infrastructure as the auto_credit source —
|
||||
the "related indicators" table lists the current value, previous value, unit
|
||||
and reporting period for Thailand's external account).
|
||||
|
||||
Verified live: the current-account page's related-indicators table exposes
|
||||
(Jul 2026) Exports 34,781.10, Imports 38,399.60, Balance of Trade -3,611.00
|
||||
USD mn and (Jun 2026) Current Account -3,473.85 USD mn. Replaces the stale
|
||||
BOT report-60 path (which only carried data through 2011) with a CURRENT,
|
||||
free, scrapeable source per the plan's "do not ship a wrong/stale series" gate.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
_USER_AGENT = (
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
|
||||
)
|
||||
_URL = "https://tradingeconomics.com/thailand/current-account"
|
||||
|
||||
|
||||
class ThaiTradeError(Exception):
|
||||
"""Raised when the TradingEconomics Thailand page cannot be fetched/parsed."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ThaiTradeSnapshot:
|
||||
current_account_usdm: Optional[float] = None # USD million
|
||||
trade_balance_usdm: Optional[float] = None # USD million
|
||||
exports_usdm: Optional[float] = None # USD million
|
||||
imports_usdm: Optional[float] = None # USD million
|
||||
as_of: str = ""
|
||||
source: str = "tradingeconomics.thai-trade"
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"source": self.source,
|
||||
"as_of": self.as_of,
|
||||
"current_account_usdm": self.current_account_usdm,
|
||||
"trade_balance_usdm": self.trade_balance_usdm,
|
||||
"exports_usdm": self.exports_usdm,
|
||||
"imports_usdm": self.imports_usdm,
|
||||
}
|
||||
|
||||
|
||||
def _fetch(url: str = _URL, timeout: float = 30.0) -> str:
|
||||
req = Request(url, headers={"User-Agent": _USER_AGENT, "Accept": "text/html"})
|
||||
try:
|
||||
with urlopen(req, timeout=timeout) as resp:
|
||||
raw = resp.read()
|
||||
except Exception as exc:
|
||||
raise ThaiTradeError(f"failed to fetch {url}: {exc}") from exc
|
||||
try:
|
||||
return raw.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
return raw.decode("latin-1", "ignore")
|
||||
|
||||
|
||||
def _tables(html_text: str) -> list[str]:
|
||||
return re.findall(r"<table[^>]*>(.*?)</table>", html_text, re.S)
|
||||
|
||||
|
||||
def _cells(row_html: str) -> list[str]:
|
||||
return [
|
||||
html.unescape(re.sub(r"<[^>]+>", "", td)).strip()
|
||||
for td in re.findall(r"<td[^>]*>(.*?)</td>", row_html, re.S)
|
||||
if td.strip()
|
||||
]
|
||||
|
||||
|
||||
def _to_float(text: str) -> Optional[float]:
|
||||
text = text.replace(",", "").strip().replace("%", "")
|
||||
if not text or text in ("-", "N/A", "…"):
|
||||
return None
|
||||
try:
|
||||
return float(text)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def parse_thai_trade_html(html_text: str) -> ThaiTradeSnapshot:
|
||||
"""Parse the TradingEconomics Thailand current-account related table."""
|
||||
current = trade = exports = imports = None
|
||||
as_of = ""
|
||||
|
||||
for table in _tables(html_text):
|
||||
rows = re.findall(r"<tr[^>]*>(.*?)</tr>", table, re.S)
|
||||
for row_html in rows:
|
||||
cells = _cells(row_html)
|
||||
if not cells:
|
||||
continue
|
||||
label = cells[0].strip()
|
||||
if label == "Current Account":
|
||||
current = _to_float(cells[1])
|
||||
if len(cells) > 4:
|
||||
as_of = cells[4]
|
||||
elif label == "Balance of Trade":
|
||||
trade = _to_float(cells[1])
|
||||
elif label == "Exports" and exports is None:
|
||||
exports = _to_float(cells[1])
|
||||
elif label == "Imports" and imports is None:
|
||||
imports = _to_float(cells[1])
|
||||
|
||||
if current is None and exports is None and imports is None:
|
||||
raise ThaiTradeError("no Thai trade series found in TradingEconomics page")
|
||||
|
||||
return ThaiTradeSnapshot(
|
||||
current_account_usdm=current,
|
||||
trade_balance_usdm=trade,
|
||||
exports_usdm=exports,
|
||||
imports_usdm=imports,
|
||||
as_of=as_of,
|
||||
)
|
||||
|
||||
|
||||
def fetch_thai_trade(timeout: float = 30.0) -> ThaiTradeSnapshot:
|
||||
return parse_thai_trade_html(_fetch(timeout=timeout))
|
||||
+178
-20
@@ -101,6 +101,7 @@ THEMES: dict[str, dict] = {
|
||||
"factors": [
|
||||
{"key": "tourism_arrivals_ytd", "weight": 1.0},
|
||||
{"key": "macro_consumption", "weight": 0.4},
|
||||
{"key": "external_current_account", "weight": 0.3},
|
||||
],
|
||||
},
|
||||
"auto_credit": {
|
||||
@@ -109,13 +110,14 @@ THEMES: dict[str, dict] = {
|
||||
{"key": "auto_sales_yoy", "weight": 1.0},
|
||||
{"key": "auto_production", "weight": 0.4},
|
||||
{"key": "auto_exports", "weight": 0.3},
|
||||
{"key": "auto_npl", "weight": -0.6},
|
||||
{"key": "auto_npl", "weight": 0.6},
|
||||
],
|
||||
},
|
||||
"refining_energy": {
|
||||
"label_th": "พลังงาน/โรงกลั่น",
|
||||
"factors": [
|
||||
{"key": "energy_net_margin", "weight": 1.0},
|
||||
{"key": "energy_irpc_net_margin", "weight": 0.6},
|
||||
{"key": "macro_mfg", "weight": 0.3},
|
||||
],
|
||||
},
|
||||
@@ -123,22 +125,36 @@ THEMES: dict[str, dict] = {
|
||||
"label_th": "ธนาคาร",
|
||||
"factors": [
|
||||
{"key": "macro_investment", "weight": 1.0},
|
||||
{"key": "macro_inflation", "weight": -0.4},
|
||||
{"key": "bank_npl", "weight": -0.6},
|
||||
{"key": "macro_inflation", "weight": 0.4},
|
||||
{"key": "macro_core_inflation", "weight": 0.3},
|
||||
{"key": "bank_npl", "weight": 0.6},
|
||||
{"key": "te_interest_rate", "weight": 0.4},
|
||||
{"key": "te_loan_growth", "weight": 0.4},
|
||||
],
|
||||
},
|
||||
"retail": {
|
||||
"label_th": "ค้าปลีก",
|
||||
"factors": [
|
||||
{"key": "macro_consumption", "weight": 1.0},
|
||||
{"key": "macro_inflation", "weight": -0.3},
|
||||
{"key": "macro_inflation", "weight": 0.3},
|
||||
{"key": "macro_core_inflation", "weight": 0.2},
|
||||
{"key": "macro_unemployment", "weight": 0.3},
|
||||
{"key": "external_imports", "weight": 0.2},
|
||||
{"key": "external_current_account", "weight": 0.2},
|
||||
{"key": "te_retail_sales_yoy", "weight": 0.7},
|
||||
{"key": "te_consumer_confidence", "weight": 0.4},
|
||||
],
|
||||
},
|
||||
"consumer_staples": {
|
||||
"label_th": "อาหาร/อุปโภค",
|
||||
"factors": [
|
||||
{"key": "macro_consumption", "weight": 1.0},
|
||||
{"key": "macro_inflation", "weight": -0.2},
|
||||
{"key": "macro_inflation", "weight": 0.2},
|
||||
{"key": "macro_core_inflation", "weight": 0.15},
|
||||
{"key": "macro_unemployment", "weight": 0.3},
|
||||
{"key": "external_imports", "weight": 0.15},
|
||||
{"key": "te_retail_sales_yoy", "weight": 0.6},
|
||||
{"key": "te_consumer_confidence", "weight": 0.3},
|
||||
],
|
||||
},
|
||||
"telecom_it": {
|
||||
@@ -146,6 +162,8 @@ THEMES: dict[str, dict] = {
|
||||
"factors": [
|
||||
{"key": "macro_consumption", "weight": 0.8},
|
||||
{"key": "macro_investment", "weight": 0.4},
|
||||
{"key": "external_exports", "weight": 0.2},
|
||||
{"key": "te_business_confidence", "weight": 0.3},
|
||||
],
|
||||
},
|
||||
"property": {
|
||||
@@ -153,20 +171,27 @@ THEMES: dict[str, dict] = {
|
||||
"factors": [
|
||||
{"key": "macro_investment", "weight": 1.0},
|
||||
{"key": "macro_consumption", "weight": 0.5},
|
||||
{"key": "macro_inflation", "weight": -0.3},
|
||||
{"key": "macro_inflation", "weight": 0.3},
|
||||
{"key": "external_imports", "weight": 0.2},
|
||||
{"key": "te_property_prices", "weight": 0.9},
|
||||
{"key": "te_business_confidence", "weight": 0.3},
|
||||
],
|
||||
},
|
||||
"healthcare": {
|
||||
"label_th": "โรงพยาบาล",
|
||||
"factors": [
|
||||
{"key": "macro_consumption", "weight": 0.5},
|
||||
{"key": "macro_unemployment", "weight": 0.4},
|
||||
{"key": "te_business_confidence", "weight": 0.2},
|
||||
],
|
||||
},
|
||||
"petrochem_materials": {
|
||||
"label_th": "ปิโตรเคมี/วัสดุ",
|
||||
"factors": [
|
||||
{"key": "macro_mfg", "weight": 1.0},
|
||||
{"key": "macro_inflation", "weight": -0.3},
|
||||
{"key": "macro_inflation", "weight": 0.3},
|
||||
{"key": "external_exports", "weight": 0.4},
|
||||
{"key": "external_current_account", "weight": 0.3},
|
||||
],
|
||||
},
|
||||
"utilities": {
|
||||
@@ -174,20 +199,28 @@ THEMES: dict[str, dict] = {
|
||||
"factors": [
|
||||
{"key": "macro_mfg", "weight": 1.0},
|
||||
{"key": "energy_net_margin", "weight": 0.3},
|
||||
{"key": "energy_irpc_net_margin", "weight": 0.2},
|
||||
],
|
||||
},
|
||||
"nonbank_finance": {
|
||||
"label_th": "การเงินนอกธนาคาร",
|
||||
"factors": [
|
||||
{"key": "macro_consumption", "weight": 1.0},
|
||||
{"key": "auto_npl", "weight": -0.3},
|
||||
{"key": "auto_npl", "weight": 0.3},
|
||||
{"key": "macro_unemployment", "weight": 0.3},
|
||||
{"key": "te_consumer_credit", "weight": 0.5},
|
||||
{"key": "te_household_debt_gdp", "weight": 0.4},
|
||||
{"key": "te_consumer_confidence", "weight": 0.3},
|
||||
],
|
||||
},
|
||||
"exploration": {
|
||||
"label_th": "สำรวจ/ผลิตพลังงาน",
|
||||
"factors": [
|
||||
{"key": "energy_net_margin", "weight": 1.0},
|
||||
{"key": "macro_inflation", "weight": -0.2},
|
||||
{"key": "energy_irpc_net_margin", "weight": 0.4},
|
||||
{"key": "macro_inflation", "weight": 0.2},
|
||||
{"key": "external_exports", "weight": 0.3},
|
||||
{"key": "external_current_account", "weight": 0.2},
|
||||
],
|
||||
},
|
||||
}
|
||||
@@ -263,10 +296,92 @@ def compute_theme_surprises(fetched: dict, tourism_surprise: Optional[float] = N
|
||||
return out
|
||||
|
||||
|
||||
_SIAMCHART_GROWTH_W = 1.5 # R1 (PEAD): EPS-growth dominates value; literature (Bernard-Thomas 1990,
|
||||
# Livnat-Mendenhall 2006) shows drift follows earnings, not just yield.
|
||||
_SIAMCHART_YIELD_W = 2.0 # dividend floor for value names
|
||||
_SIAMCHART_MOMENTUM_W = 0.5 # R2: EM momentum exists but is noisy -> keep it a small trend boost.
|
||||
def factor_source_breakdown(fetched: dict, theme_id: str) -> list:
|
||||
"""Per-factor contribution detail for one theme (what the user asked for).
|
||||
|
||||
For each FACTOR a theme references, show exactly how it contributed to the
|
||||
theme surprise:
|
||||
- source: the fetch-module name (e.g. 'macro_thai', 'te_thailand')
|
||||
- name_th: the factor's Thai label
|
||||
- raw: the raw collected value
|
||||
- normalized: the sign/center/span-normalized score in [-1, 1]
|
||||
- weight: the per-theme weight (positive magnitude; direction is in sign)
|
||||
- contribution: weight * normalized
|
||||
- missing: True when the source had no value so the factor was dropped
|
||||
|
||||
This is the audit trail that lets the owner see "which source scored what,
|
||||
and how the weight was applied" and tune weights/thesis more easily.
|
||||
"""
|
||||
from . import factors as factors_mod
|
||||
|
||||
tdef = THEMES.get(theme_id, {})
|
||||
rows = []
|
||||
for ref in tdef.get("factors", []):
|
||||
fkey = ref.get("key")
|
||||
fact = factors_mod.FACTORS.get(fkey)
|
||||
if not fact:
|
||||
continue
|
||||
fetch_mod = fact.get("fetch")
|
||||
val = factors_mod.factor_value(fact, fetched.get(fetch_mod))
|
||||
w = float(ref.get("weight", 1.0))
|
||||
if val is None:
|
||||
rows.append({
|
||||
"factor": fkey, "source": fetch_mod,
|
||||
"name_th": fact.get("name_th", fkey),
|
||||
"frequency": fact.get("frequency", "monthly"),
|
||||
"sign": fact.get("sign", 1),
|
||||
"raw": None, "normalized": None, "weight": w,
|
||||
"contribution": None, "missing": True,
|
||||
})
|
||||
continue
|
||||
norm = factors_mod.normalize(val, sign=fact.get("sign", 1),
|
||||
center=fact.get("center", 0.0),
|
||||
span=fact.get("span", 10.0))
|
||||
rows.append({
|
||||
"factor": fkey, "source": fetch_mod,
|
||||
"name_th": fact.get("name_th", fkey),
|
||||
"frequency": fact.get("frequency", "monthly"),
|
||||
"sign": fact.get("sign", 1),
|
||||
"raw": round(val, 4) if val is not None else None,
|
||||
"normalized": norm,
|
||||
"weight": w,
|
||||
"contribution": round(w * (norm or 0.0), 4) if norm is not None else None,
|
||||
"missing": False,
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
# Siamchart score is a declarative weighted blend of fundamentals + momentum —
|
||||
# each term is a first-class factor WITHIN the formula (not an out-of-formula
|
||||
# adjustment). Weights are config in one place so tuning/auditing is trivial.
|
||||
# - eps_growth (R1, PEAD): earnings drift dominates; literature Bernard-Thomas
|
||||
# 1990, Livnat-Mendenhall 2006.
|
||||
# - dividend_yield: value floor.
|
||||
# - momentum: price-trend factor in the formula (R2); EM momentum is noisier
|
||||
# so it stays small relative to EPS.
|
||||
_SIAMCHART_WEIGHTS: dict[str, float] = {
|
||||
"eps_growth": 1.5,
|
||||
"dividend_yield": 2.0,
|
||||
"momentum": 0.5,
|
||||
}
|
||||
_SIAMCHART_GROWTH_W = _SIAMCHART_WEIGHTS["eps_growth"]
|
||||
_SIAMCHART_YIELD_W = _SIAMCHART_WEIGHTS["dividend_yield"]
|
||||
_SIAMCHART_MOMENTUM_W = _SIAMCHART_WEIGHTS["momentum"]
|
||||
|
||||
|
||||
def siamchart_raw_score(g: float, d: float, m: float) -> float:
|
||||
"""Raw (pre-z) Siamchart score = single source of the scoring formula.
|
||||
|
||||
Momentum is an explicit term INSIDE the formula (per the owner's rule — it is
|
||||
a factor that enters the formula, not an out-of-formula tweak). All three
|
||||
weights come from ``_SIAMCHART_WEIGHTS`` so the board, the per-symbol detail,
|
||||
and the population stats always use byte-identical arithmetic.
|
||||
"""
|
||||
return (
|
||||
_SIAMCHART_WEIGHTS["eps_growth"] * g
|
||||
+ _SIAMCHART_WEIGHTS["dividend_yield"] * d
|
||||
+ _SIAMCHART_WEIGHTS["momentum"] * m
|
||||
)
|
||||
|
||||
|
||||
def _load_momentum(lookback_days: int = 252) -> dict[str, float]:
|
||||
@@ -297,13 +412,57 @@ def _load_momentum(lookback_days: int = 252) -> dict[str, float]:
|
||||
return out
|
||||
|
||||
|
||||
def price_trend_score(series: dict, lookbacks=(63, 126, 252), weights=(0.4, 0.35, 0.25)) -> dict[str, float]:
|
||||
"""Mid-term price trend per symbol — the owner's definition of "ทำกำไร".
|
||||
|
||||
The owner wants buckets 1/2 to mean "a stock whose price is likely to rise in
|
||||
the next 3-6 months", which is a *price-trend* signal, not EPS growth. This
|
||||
blends multi-horizon momentum over ~3 / 6 / 12 months (trading days), then
|
||||
z-scores across the universe so the score is comparable. Heavier weight on
|
||||
the shorter horizons (3/6m) matches the 3-6 month tenure the owner named.
|
||||
|
||||
Returns {symbol: z(trend)}. Symbols without enough price history are omitted
|
||||
(callers treat them as ineligible/momentum-neutral).
|
||||
"""
|
||||
import statistics
|
||||
mom = {sym: [] for sym in series}
|
||||
for sym, s in series.items():
|
||||
bars = s.get("bars", [])
|
||||
if not bars:
|
||||
continue
|
||||
todays = float(bars[-1]["adjusted_close"])
|
||||
if todays <= 0:
|
||||
continue
|
||||
for lb in lookbacks:
|
||||
if len(bars) > lb:
|
||||
base = float(bars[-1 - lb]["adjusted_close"])
|
||||
if base > 0:
|
||||
mom[sym].append((todays / base) - 1.0)
|
||||
else:
|
||||
mom[sym].append(0.0)
|
||||
else:
|
||||
mom[sym].append(None)
|
||||
raw: dict[str, float] = {}
|
||||
for sym, vals in mom.items():
|
||||
contrib = [w * (v or 0.0) for v, w in zip(vals, weights) if v is not None]
|
||||
if contrib:
|
||||
raw[sym] = sum(contrib)
|
||||
if not raw:
|
||||
return {}
|
||||
vals = list(raw.values())
|
||||
mean = statistics.mean(vals)
|
||||
sd = statistics.pstdev(vals) or 1.0
|
||||
return {sym: round((v - mean) / sd, 4) for sym, v in raw.items()}
|
||||
|
||||
|
||||
def build_siamchart_score(factors: dict,
|
||||
momentum: Optional[dict[str, float]] = None) -> dict[str, float]:
|
||||
"""Derive a normalized fundamental score from the Siamchart factor view.
|
||||
|
||||
Uses EPS growth YoY (weighted above yield per PEAD literature) and dividend
|
||||
yield. Optional momentum (12-1, from price snapshot) adds a low-weight
|
||||
trend component; EM momentum is noisier, so it stays small.
|
||||
Raw score = eps_growth*w + dividend_yield*w + momentum*w (see
|
||||
``siamchart_raw_score``) — momentum is a first-class factor INSIDE the
|
||||
formula, then z-scored across the universe. Optional momentum (price trend)
|
||||
contributes per its configured weight in ``_SIAMCHART_WEIGHTS``.
|
||||
"""
|
||||
out: dict[str, float] = {}
|
||||
for f in factors.get("factors", []):
|
||||
@@ -314,8 +473,7 @@ def build_siamchart_score(factors: dict,
|
||||
d = f.get("dividend_yield") or 0.0
|
||||
g = float(g) if g is not None else 0.0
|
||||
m = (momentum or {}).get(sym, 0.0)
|
||||
# R1+R2: growth dominates (PEAD), yield floors, momentum adds trend.
|
||||
out[sym] = g * _SIAMCHART_GROWTH_W + d * _SIAMCHART_YIELD_W + _SIAMCHART_MOMENTUM_W * m
|
||||
out[sym] = siamchart_raw_score(g, d, m)
|
||||
syms = list(out.keys())
|
||||
z = _zscore([out[s] for s in syms])
|
||||
return {s: z.get(i, 0.0) for i, s in enumerate(syms)}
|
||||
@@ -446,7 +604,7 @@ def symbol_breakdown(
|
||||
d = fac.get("dividend_yield") or 0.0
|
||||
g = float(g) if g is not None else 0.0
|
||||
m = (momentum or {}).get(symbol, 0.0)
|
||||
raw_siamchart = g * _SIAMCHART_GROWTH_W + d * _SIAMCHART_YIELD_W + _SIAMCHART_MOMENTUM_W * m
|
||||
raw_siamchart = siamchart_raw_score(g, d, m)
|
||||
|
||||
# z-score against the full universe (same as build_siamchart_score); capture
|
||||
# the population stats so the view can show HOW -2.8 became -0.588.
|
||||
@@ -461,7 +619,7 @@ def symbol_breakdown(
|
||||
dd = f.get("dividend_yield") or 0.0
|
||||
gg = float(gg) if gg is not None else 0.0
|
||||
mm = (momentum or {}).get(f.get("symbol"), 0.0)
|
||||
raw_values.append(gg * _SIAMCHART_GROWTH_W + dd * _SIAMCHART_YIELD_W + _SIAMCHART_MOMENTUM_W * mm)
|
||||
raw_values.append(siamchart_raw_score(gg, dd, mm))
|
||||
pop_mean = statistics.mean(raw_values) if raw_values else 0.0
|
||||
pop_stdev = statistics.pstdev(raw_values) if raw_values else 0.0
|
||||
|
||||
|
||||
+10
-3
@@ -42,10 +42,12 @@ def _data_quality(snapshot: dict[str, Any], observations: list[dict[str, Any]])
|
||||
def compute_tourism_signal(snapshot: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Compute a replayable Tourism Pulse signal from a frozen snapshot."""
|
||||
|
||||
observations = list(snapshot.get("observations", []))
|
||||
if not observations:
|
||||
observations = snapshot.get("observations", [])
|
||||
if not isinstance(observations, list) or not observations:
|
||||
raise ValueError("tourism snapshot must contain observations")
|
||||
for observation in observations:
|
||||
if not isinstance(observation, dict):
|
||||
raise ValueError("tourism observation must be an object")
|
||||
_validate_observation(observation)
|
||||
|
||||
standardized = []
|
||||
@@ -58,7 +60,12 @@ def compute_tourism_signal(snapshot: dict[str, Any]) -> dict[str, Any]:
|
||||
theme_surprise = round(fmean(standardized), 8)
|
||||
|
||||
signal_rows = []
|
||||
for exposure in snapshot.get("exposures", []):
|
||||
exposures = snapshot.get("exposures", [])
|
||||
if not isinstance(exposures, list):
|
||||
raise ValueError("tourism snapshot exposures must be a list")
|
||||
for exposure in exposures:
|
||||
if not isinstance(exposure, dict):
|
||||
raise ValueError("tourism exposure must be an object")
|
||||
symbol = str(exposure.get("symbol", "")).strip().upper()
|
||||
coefficient = float(exposure.get("coefficient", 0))
|
||||
confidence = float(exposure.get("confidence", 1.0))
|
||||
|
||||
@@ -90,7 +90,7 @@ class VintageStore:
|
||||
return {"schema_version": MANIFEST_SCHEMA_VERSION, "vintages": {}}
|
||||
try:
|
||||
payload = json.loads(self.manifest_path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
||||
raise VintageStoreError("vintage manifest is unreadable") from exc
|
||||
if not isinstance(payload, dict) or payload.get("schema_version") != MANIFEST_SCHEMA_VERSION:
|
||||
raise VintageStoreError("unsupported vintage manifest schema")
|
||||
@@ -174,8 +174,10 @@ class VintageStore:
|
||||
raise FileNotFoundError(vintage_id)
|
||||
try:
|
||||
snapshot = json.loads(snapshot_path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
||||
raise VintageStoreError("vintage snapshot is unreadable") from exc
|
||||
if not isinstance(snapshot, dict):
|
||||
raise VintageStoreError("vintage snapshot is invalid")
|
||||
source = snapshot.get("source")
|
||||
if not isinstance(source, dict) or source.get("vintage_id") != vintage_id:
|
||||
raise VintageStoreError("vintage snapshot identity mismatch")
|
||||
@@ -186,7 +188,11 @@ class VintageStore:
|
||||
raw_path = (self.raw_dir / raw_filename).resolve()
|
||||
if raw_path.parent != self.raw_dir.resolve() or not raw_path.is_file():
|
||||
raise VintageStoreError("vintage raw payload is missing")
|
||||
if hashlib.sha256(raw_path.read_bytes()).hexdigest() != source.get("raw_payload_hash"):
|
||||
try:
|
||||
raw_payload_hash = hashlib.sha256(raw_path.read_bytes()).hexdigest()
|
||||
except OSError as exc:
|
||||
raise VintageStoreError("vintage raw payload is unreadable") from exc
|
||||
if raw_payload_hash != source.get("raw_payload_hash"):
|
||||
raise VintageStoreError("vintage raw payload hash mismatch")
|
||||
manifest_entry = self.load_manifest().get("vintages", {}).get(vintage_id)
|
||||
if not isinstance(manifest_entry, dict):
|
||||
|
||||
+3
-2
@@ -6,12 +6,13 @@ import os
|
||||
|
||||
from app import create_app
|
||||
|
||||
app = create_app()
|
||||
HOST = os.getenv("HOST", os.getenv("PAPER_BIND_HOST", "127.0.0.1"))
|
||||
app = create_app({"PAPER_BIND_HOST": HOST})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(
|
||||
host=os.getenv("HOST", "127.0.0.1"),
|
||||
host=HOST,
|
||||
port=int(os.getenv("PORT", "5000")),
|
||||
debug=False,
|
||||
)
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Migrate legacy research reports into the fail-closed hashed format."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from app.research import ResearchRunStore
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument(
|
||||
"--root",
|
||||
type=Path,
|
||||
default=Path(__file__).resolve().parents[1] / "data" / "research",
|
||||
help="research store root containing manifest.json and reports/",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
migrated = ResearchRunStore(args.root).migrate_legacy()
|
||||
print(json.dumps({"migrated_reports": migrated}, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Live end-to-end probe of the event-driven PIT backtest engine (Task 8).
|
||||
|
||||
Uses fully PIT-complete fake inputs to prove the engine produces a reconciled,
|
||||
accounting-consistent result — this is the "happy path" complement to the
|
||||
fail-closed readiness gate already verified separately.
|
||||
"""
|
||||
import datetime as dt
|
||||
from app.backtest_engine import run_event_backtest
|
||||
from app.backtest_readiness import _factor_keys_required
|
||||
|
||||
|
||||
def series(syms, days=120, jump=None, after_price=20.0):
|
||||
s = dt.date(2026, 1, 1)
|
||||
out = {}
|
||||
for sym in syms:
|
||||
bars = []
|
||||
for i in range(days):
|
||||
d = (s + dt.timedelta(days=i))
|
||||
px = (after_price if jump and d >= jump else 10.0)
|
||||
bars.append({"date": d.isoformat(), "adjusted_close": px})
|
||||
out[sym] = {"bars": bars}
|
||||
return out
|
||||
|
||||
|
||||
class FStore:
|
||||
def __init__(self, rels):
|
||||
self.r = rels
|
||||
|
||||
def series(self, k):
|
||||
return [{"released_at": t, "observed_at": t, "value": 1.0}
|
||||
for t in self.r.get(k, [])]
|
||||
|
||||
|
||||
class FLedger:
|
||||
def symbols(self):
|
||||
return ["A"]
|
||||
|
||||
def entries(self, s):
|
||||
return [{"symbol": "A", "ex_date": "2026-02-15",
|
||||
"per_share": 1.0, "estimate": False}]
|
||||
|
||||
|
||||
rels = {k: ["2026-01-02T09:00:00+07:00"] for k in _factor_keys_required()}
|
||||
|
||||
|
||||
class SC:
|
||||
def list_ids(self):
|
||||
return ["1"]
|
||||
|
||||
def _load_manifest(self):
|
||||
return {"snapshots": {"1": {"retrieved_at": "2026-01-02T09:00:00+07:00"}}}
|
||||
|
||||
|
||||
def pit_scorer(symbols, as_of=None):
|
||||
out = {}
|
||||
for i, sym in enumerate(symbols):
|
||||
out[sym] = {
|
||||
"combined": 1.0 / (i + 1), "is_dividend": True,
|
||||
"dividend_yield": 3.0,
|
||||
"pit_meta": {"pit": True, "partial_pit": False, "note": "test"},
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
ser = series(["A", "B", "C"], 120, jump=dt.date(2026, 2, 1))
|
||||
res = run_event_backtest(
|
||||
start="2026-01-05", end="2026-04-30", capital=100000,
|
||||
factor_store=FStore(rels), siamchart_store=SC(),
|
||||
dividend_ledger=FLedger(), price_series=ser,
|
||||
score_fn=pit_scorer, symbols=["A", "B", "C"],
|
||||
)
|
||||
d = res.to_dict()
|
||||
print("rebalances:", d["rebalances"])
|
||||
print("leakage_guard:", d["leakage_guard"])
|
||||
print("accounting_reconciled:", d["accounting_reconciled"])
|
||||
print("final_equity:", round(d["final_equity"], 2))
|
||||
print("realized:", d["realized_trading_pnl"], "unrealized:", d["unrealized_trading_pnl"])
|
||||
print("dividend_cash:", d["dividend_cash_received"], "dividend_recv:", d["dividend_receivable"])
|
||||
print("fees:", d["transaction_costs"], "net_return:", round(d["net_return"], 4))
|
||||
print("holdings:", [(h["symbol"], h["qty"]) for h in d["holdings"]])
|
||||
|
||||
assert d["accounting_reconciled"], "FAIL: not reconciled"
|
||||
lhs = d["final_equity"] - 100000
|
||||
rhs = (d["realized_trading_pnl"] + d["unrealized_trading_pnl"]
|
||||
+ d["dividend_cash_received"] - d["transaction_costs"])
|
||||
print(f" identity lhs={round(lhs,2)} rhs={round(rhs,2)}")
|
||||
assert abs(lhs - rhs) < 1.0, "identity mismatch"
|
||||
assert d["leakage_guard"] is True, "leakage_guard should be True with pit_meta"
|
||||
print("PASS")
|
||||
@@ -88,7 +88,7 @@ class ApiTests(unittest.TestCase):
|
||||
db = self.client.get("/api/v1/dashboard").get_json()
|
||||
self.assertEqual({t["id"] for t in th["themes"]}, {t["id"] for t in db["themes"]})
|
||||
|
||||
def test_simulation_allocates_capital(self):
|
||||
def test_suggestion_allocates_capital(self):
|
||||
from unittest.mock import patch
|
||||
class _FakeAuto:
|
||||
def to_dict(self):
|
||||
@@ -100,10 +100,11 @@ class ApiTests(unittest.TestCase):
|
||||
"Q2/2026": {"net_profit": 8000.0, "ebitda": 9000.0, "sales": 120000.0}}}
|
||||
with patch("app.auto_credit.fetch_auto_credit", return_value=_FakeAuto()), \
|
||||
patch("app.energy_thai.fetch_energy_thai", return_value=_FakeEnergy()):
|
||||
resp = self.client.post("/api/v1/simulation", json={"capital": 500000, "mode": "backtest"})
|
||||
resp = self.client.post("/api/v1/suggestion", json={"capital": 500000})
|
||||
self.assertEqual(resp.status_code, 200)
|
||||
payload = resp.get_json()
|
||||
self.assertEqual(payload["capital"], 500000)
|
||||
self.assertEqual(payload["mode"], "suggestion")
|
||||
self.assertIn("orders", payload)
|
||||
self.assertIn("unallocated_cash", payload)
|
||||
# invested + unallocated == capital
|
||||
@@ -112,12 +113,12 @@ class ApiTests(unittest.TestCase):
|
||||
for order in payload["orders"]:
|
||||
self.assertEqual(order["qty"] % 100, 0)
|
||||
|
||||
def test_simulation_rejects_invalid_capital(self):
|
||||
resp = self.client.post("/api/v1/simulation", json={"capital": 0})
|
||||
def test_suggestion_rejects_invalid_capital(self):
|
||||
resp = self.client.post("/api/v1/suggestion", json={"capital": 0})
|
||||
self.assertEqual(resp.status_code, 400)
|
||||
resp2 = self.client.post("/api/v1/simulation", json={"capital": -5})
|
||||
resp2 = self.client.post("/api/v1/suggestion", json={"capital": -5})
|
||||
self.assertEqual(resp2.status_code, 400)
|
||||
resp3 = self.client.post("/api/v1/simulation", json={"capital": "abc"})
|
||||
resp3 = self.client.post("/api/v1/suggestion", json={"capital": "abc"})
|
||||
self.assertEqual(resp3.status_code, 400)
|
||||
|
||||
def test_health_reports_research_mode(self):
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
"""Integration tests for the event-driven backtest engine (Task 5)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import unittest
|
||||
|
||||
from app.backtest_engine import (
|
||||
run_event_backtest,
|
||||
)
|
||||
from app.backtest_events import DIVIDEND_PAYMENT_LAG_DAYS
|
||||
|
||||
|
||||
def make_series(symbols, start, days, price_map=None):
|
||||
"""Price series; price_map maps date->{sym:price} overrides, else flat."""
|
||||
s = dt.date.fromisoformat(start)
|
||||
out = {}
|
||||
for sym in symbols:
|
||||
bars = []
|
||||
for i in range(days):
|
||||
d = (s + dt.timedelta(days=i)).isoformat()
|
||||
base = (price_map or {}).get(d, {}).get(sym, 10.0)
|
||||
bars.append({"date": d, "adjusted_close": float(base)})
|
||||
out[sym] = {"bars": bars}
|
||||
return out
|
||||
|
||||
|
||||
def price_jump_series(symbols, start, days, jump_date, new_price=20.0):
|
||||
"""Price series that jumps on/after jump_date for all symbols."""
|
||||
s = dt.date.fromisoformat(start)
|
||||
jd = dt.date.fromisoformat(jump_date)
|
||||
out = {}
|
||||
for sym in symbols:
|
||||
bars = []
|
||||
for i in range(days):
|
||||
d = (s + dt.timedelta(days=i))
|
||||
px = new_price if d >= jd else 10.0
|
||||
bars.append({"date": d.isoformat(), "adjusted_close": px})
|
||||
out[sym] = {"bars": bars}
|
||||
return out
|
||||
|
||||
|
||||
class FakeFactorStore:
|
||||
"""factor_key -> release timestamps; used to trigger releases on a date."""
|
||||
|
||||
def __init__(self, releases=None):
|
||||
self._rels = releases or {}
|
||||
|
||||
def series(self, key):
|
||||
return [
|
||||
{"released_at": ts, "observed_at": ts, "value": 1.0}
|
||||
for ts in self._rels.get(key, [])
|
||||
]
|
||||
|
||||
|
||||
class FakeLedger:
|
||||
def __init__(self, entries):
|
||||
self._by = {}
|
||||
for e in entries:
|
||||
self._by.setdefault(e["symbol"], []).append(e)
|
||||
|
||||
def symbols(self):
|
||||
return list(self._by.keys())
|
||||
|
||||
def entries(self, sym):
|
||||
return self._by.get(sym, [])
|
||||
|
||||
|
||||
def noop_scorer(symbols, as_of=None):
|
||||
# non-PIT scorer: all dividend, equal score -> allocation picks top by list
|
||||
out = {}
|
||||
for i, sym in enumerate(symbols):
|
||||
out[sym] = {
|
||||
"combined": 1.0 / (i + 1),
|
||||
"is_dividend": True,
|
||||
"dividend_yield": 3.0,
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
class NoLookAheadTest(unittest.TestCase):
|
||||
def test_signal_release_three_months_in_triggers_one_rebalance(self):
|
||||
series = make_series(["A", "B"], "2026-01-01", 200)
|
||||
# a factor release 3 months later (daily series, days ~90)
|
||||
rel = "2026-04-01T09:00:00+07:00"
|
||||
fstore = FakeFactorStore({"energy_net_margin": [rel]})
|
||||
res = run_event_backtest(
|
||||
start="2026-01-01", end="2026-06-30",
|
||||
capital=100_000,
|
||||
factor_store=fstore,
|
||||
price_series=series,
|
||||
score_fn=noop_scorer,
|
||||
symbols=["A", "B"],
|
||||
)
|
||||
# event-driven: releases were 1 (the release day) + initial; the initial
|
||||
# signal always triggers the first buy; the release triggers one more
|
||||
# rebalance (>=1 because portfolio changes when scores re-rank).
|
||||
self.assertGreaterEqual(res.rebalances, 1)
|
||||
self.assertTrue(res.account_reconciled)
|
||||
|
||||
|
||||
class LifecycleTest(unittest.TestCase):
|
||||
def test_full_lifecycle_reconciles_with_trade_pnl(self):
|
||||
# price jumps mid-run so a sell realizes real P&L
|
||||
series = price_jump_series(["A", "B"], "2026-01-01", 90, "2026-03-01", 20.0)
|
||||
# dividend on A before the jump
|
||||
ledger = FakeLedger([{
|
||||
"symbol": "A", "ex_date": "2026-02-15",
|
||||
"per_share": 1.0, "estimate": False,
|
||||
}])
|
||||
res = run_event_backtest(
|
||||
start="2026-01-01", end="2026-03-30",
|
||||
capital=100_000,
|
||||
dividend_ledger=ledger,
|
||||
price_series=series,
|
||||
score_fn=noop_scorer,
|
||||
symbols=["A", "B"],
|
||||
)
|
||||
self.assertTrue(res.account_reconciled)
|
||||
# final equity must be consistent with reported components
|
||||
self.assertAlmostEqual(
|
||||
res.final_equity,
|
||||
res.capital + res.realized_trading_pnl + res.unrealized_trading_pnl
|
||||
+ res.dividend_cash_received - res.transaction_costs,
|
||||
places=1,
|
||||
)
|
||||
|
||||
def test_dividend_cash_becomes_available_after_ex_date_plus_30(self):
|
||||
series = make_series(["A"], "2026-01-01", 200)
|
||||
ex = "2026-01-15"
|
||||
ledger = FakeLedger([{
|
||||
"symbol": "A", "ex_date": ex, "per_share": 2.0, "estimate": False,
|
||||
}])
|
||||
res = run_event_backtest(
|
||||
start="2026-01-01", end="2026-04-01",
|
||||
capital=200_000, dividend_ledger=ledger,
|
||||
price_series=series, score_fn=noop_scorer, symbols=["A"],
|
||||
)
|
||||
# by end (after ex+30) the dividend has been paid into cash
|
||||
self.assertGreater(res.dividend_cash_received, 0)
|
||||
self.assertEqual(res.dividend_receivable, 0.0)
|
||||
|
||||
|
||||
class ResultContractTest(unittest.TestCase):
|
||||
def test_to_dict_has_expected_shape(self):
|
||||
series = make_series(["A"], "2026-01-01", 120)
|
||||
res = run_event_backtest(
|
||||
start="2026-01-01", end="2026-04-30",
|
||||
capital=100_000, price_series=series,
|
||||
score_fn=noop_scorer, symbols=["A"],
|
||||
)
|
||||
d = res.to_dict()
|
||||
for key in [
|
||||
"final_equity", "net_return", "realized_trading_pnl",
|
||||
"unrealized_trading_pnl", "price_pnl", "dividend_cash_received",
|
||||
"transaction_costs", "holdings", "trades", "leakage_guard",
|
||||
"accounting_reconciled", "fee_rate", "dividend_timing",
|
||||
]:
|
||||
self.assertIn(key, d)
|
||||
self.assertEqual(d["fee_rate"], 0.003)
|
||||
self.assertEqual(d["dividend_timing"], "ex_date_plus_30d")
|
||||
|
||||
def test_refuses_to_fallback_to_live_board_without_scorer(self):
|
||||
# strict event-driven mode must not freeze the live (non-PIT) board at a
|
||||
# historical release — that is look-ahead. It must fail closed.
|
||||
series = make_series(["A"], "2026-01-01", 120)
|
||||
with self.assertRaises(ValueError):
|
||||
run_event_backtest(
|
||||
start="2026-01-01", end="2026-04-30",
|
||||
capital=100_000, price_series=series,
|
||||
symbols=["A"], # no score_fn -> must raise
|
||||
)
|
||||
|
||||
def test_no_entitlement_for_shares_bought_on_ex_date(self):
|
||||
# Regression for the cycle-2 review breach (invariant #4): when an
|
||||
# execution day coincides with a dividend ex-date, shares acquired
|
||||
# ON the ex-date must not be entitled to that dividend. The engine must
|
||||
# capture entitlement from the pre-trade position.
|
||||
# Daily price series; A held from day 1. ex-date on a day when an
|
||||
# initial signal's next trading day also lands (coincident) — the buy on
|
||||
# that ex-date must NOT count toward entitlement.
|
||||
ledger = FakeLedger([{
|
||||
"symbol": "A", "ex_date": "2026-01-02",
|
||||
"per_share": 1.0, "estimate": False,
|
||||
}])
|
||||
# start next trading day after 2026-01-01 is 2026-01-02 (daily series),
|
||||
# which is the exact ex-date -> coincident execution + ex-date.
|
||||
series = make_series(["A", "B"], "2026-01-01", 30)
|
||||
res = run_event_backtest(
|
||||
start="2026-01-01", end="2026-03-31",
|
||||
capital=200_000, dividend_ledger=ledger,
|
||||
price_series=series, score_fn=noop_scorer, symbols=["A", "B"],
|
||||
)
|
||||
# dividend was entitled for A, but only for shares held BEFORE the
|
||||
# ex-date. Since A was FIRST bought on the ex-date (initial signal's
|
||||
# next trading day), entitlement must be 0 (no receivable created).
|
||||
assert res.ledger is not None
|
||||
# no receivable for A on the ex-date (shares only acquired that day)
|
||||
a_receivables = [
|
||||
r for r in res.ledger.state.receivables
|
||||
if r.symbol == "A" and r.ex_date == "2026-01-02"
|
||||
]
|
||||
self.assertEqual(a_receivables, [], "shares bought on ex-date must not be entitled")
|
||||
# no dividend log entry either
|
||||
for d in (res.ledger.state.dividends or []):
|
||||
if d["symbol"] == "A" and d["ex_date"] == "2026-01-02":
|
||||
self.fail("dividend logged for shares bought on ex-date")
|
||||
# reconcile still holds
|
||||
self.assertTrue(res.account_reconciled)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,223 @@
|
||||
"""Tests for the unified event-driven backtest calendar (Task 2)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import unittest
|
||||
|
||||
from app.backtest_events import (
|
||||
DIVIDEND_PAYMENT_LAG_DAYS,
|
||||
DividendEntitlementEvent,
|
||||
DividendPaymentEvent,
|
||||
EndValuationEvent,
|
||||
ExecutionEvent,
|
||||
SignalReleaseEvent,
|
||||
build_event_calendar,
|
||||
)
|
||||
|
||||
|
||||
class FakeFactorStore:
|
||||
"""factor_key -> rows with released_at (chronological)."""
|
||||
|
||||
def __init__(self, releases: dict[str, list[str]]):
|
||||
self._releases = releases
|
||||
|
||||
def series(self, key: str) -> list[dict]:
|
||||
return [
|
||||
{"released_at": ts, "observed_at": ts, "value": 1.0}
|
||||
for ts in self._releases.get(key, [])
|
||||
]
|
||||
|
||||
|
||||
class FakeSiamchartStore:
|
||||
def __init__(self, retrieved: list[str]):
|
||||
self._retrieved = sorted(retrieved)
|
||||
|
||||
def list_ids(self) -> list[str]:
|
||||
return [str(i) for i in range(len(self._retrieved))]
|
||||
|
||||
def _load_manifest(self) -> dict:
|
||||
return {
|
||||
"snapshots": {
|
||||
str(i): {"retrieved_at": ts} for i, ts in enumerate(self._retrieved)
|
||||
}
|
||||
}
|
||||
|
||||
def snapshot_at(self, as_of: str) -> dict:
|
||||
chosen = [t for t in self._retrieved if t <= as_of]
|
||||
if not chosen:
|
||||
return {}
|
||||
return {"retrieved_at": chosen[-1], "_retrieved_at": chosen[-1]}
|
||||
|
||||
|
||||
class FakeLedger:
|
||||
def __init__(self, entries):
|
||||
# entries: list of {symbol, ex_date, per_share, estimate}
|
||||
self._by = {}
|
||||
for e in entries:
|
||||
self._by.setdefault(e["symbol"], []).append(e)
|
||||
|
||||
def symbols(self) -> list[str]:
|
||||
return list(self._by.keys())
|
||||
|
||||
def entries(self, sym: str) -> list[dict]:
|
||||
return self._by.get(sym, [])
|
||||
|
||||
|
||||
class SignalReleaseTest(unittest.TestCase):
|
||||
def test_factor_release_produces_signal_event(self):
|
||||
store = FakeFactorStore({
|
||||
"energy_net_margin": ["2026-03-15T09:00:00+07:00"],
|
||||
})
|
||||
events = build_event_calendar(
|
||||
factor_store=store, start="2026-03-01", end="2026-04-01"
|
||||
)
|
||||
sigs = [e for e in events if isinstance(e, SignalReleaseEvent)]
|
||||
self.assertEqual(len(sigs), 1)
|
||||
self.assertEqual(sigs[0].released_at[:10], "2026-03-15")
|
||||
self.assertIn("factor:energy_net_margin", sigs[0].sources)
|
||||
|
||||
def test_same_day_factor_releases_coalesce_into_one_signal(self):
|
||||
store = FakeFactorStore({
|
||||
"energy_net_margin": ["2026-03-15T09:00:00+07:00"],
|
||||
"macro_consumption": ["2026-03-15T14:00:00+07:00"],
|
||||
})
|
||||
events = build_event_calendar(
|
||||
factor_store=store, start="2026-03-01", end="2026-04-01"
|
||||
)
|
||||
sigs = [e for e in events if isinstance(e, SignalReleaseEvent)]
|
||||
self.assertEqual(len(sigs), 1) # coalesced
|
||||
self.assertEqual(len(sigs[0].sources), 2)
|
||||
|
||||
def test_release_outside_window_is_excluded(self):
|
||||
store = FakeFactorStore({
|
||||
"energy_net_margin": ["2026-03-15T09:00:00+07:00"],
|
||||
})
|
||||
events = build_event_calendar(
|
||||
factor_store=store, start="2026-04-01", end="2026-05-01"
|
||||
)
|
||||
sigs = [e for e in events if isinstance(e, SignalReleaseEvent)]
|
||||
self.assertEqual(len(sigs), 0)
|
||||
|
||||
|
||||
class SiamchartSignalTest(unittest.TestCase):
|
||||
def test_snapshot_retrieval_produces_signal(self):
|
||||
store = FakeSiamchartStore(["2026-03-20T09:00:00+07:00"])
|
||||
events = build_event_calendar(
|
||||
siamchart_store=store, start="2026-03-01", end="2026-04-01"
|
||||
)
|
||||
sigs = [e for e in events if isinstance(e, SignalReleaseEvent)]
|
||||
sc = [s for s in sigs if "siamchart" in s.sources]
|
||||
self.assertEqual(len(sc), 1)
|
||||
self.assertEqual(sc[0].released_at[:10], "2026-03-20")
|
||||
|
||||
|
||||
class DividendEventTest(unittest.TestCase):
|
||||
def test_entitlement_and_payment_events(self):
|
||||
ledger = FakeLedger([{
|
||||
"symbol": "A", "ex_date": "2026-03-10",
|
||||
"per_share": 1.5, "estimate": False,
|
||||
}])
|
||||
events = build_event_calendar(
|
||||
dividend_ledger=ledger, start="2026-03-01", end="2026-05-01"
|
||||
)
|
||||
ents = [e for e in events if isinstance(e, DividendEntitlementEvent)]
|
||||
pays = [e for e in events if isinstance(e, DividendPaymentEvent)]
|
||||
self.assertEqual(len(ents), 1)
|
||||
self.assertEqual(ents[0].ex_date, "2026-03-10")
|
||||
self.assertEqual(ents[0].per_share, 1.5)
|
||||
self.assertEqual(len(pays), 1)
|
||||
expected_pay = dt.date(2026, 3, 10) + dt.timedelta(days=DIVIDEND_PAYMENT_LAG_DAYS)
|
||||
self.assertEqual(pays[0].payment_date, expected_pay.isoformat())
|
||||
self.assertEqual(pays[0].timing_method, "ex_date_plus_30d")
|
||||
|
||||
def test_estimate_entry_produces_no_dated_events(self):
|
||||
ledger = FakeLedger([{
|
||||
"symbol": "A", "ex_date": "2026-03-10",
|
||||
"per_share": 1.5, "estimate": True,
|
||||
}])
|
||||
events = build_event_calendar(
|
||||
dividend_ledger=ledger, start="2026-03-01", end="2026-05-01"
|
||||
)
|
||||
ents = [e for e in events if isinstance(e, DividendEntitlementEvent)]
|
||||
pays = [e for e in events if isinstance(e, DividendPaymentEvent)]
|
||||
self.assertEqual(len(ents), 0)
|
||||
self.assertEqual(len(pays), 0)
|
||||
|
||||
|
||||
class CalendarShapeTest(unittest.TestCase):
|
||||
def test_end_valuation_event_always_present(self):
|
||||
events = build_event_calendar(start="2026-03-01", end="2026-04-01")
|
||||
ends = [e for e in events if isinstance(e, EndValuationEvent)]
|
||||
self.assertEqual(len(ends), 1)
|
||||
self.assertEqual(ends[0].end_date, "2026-04-01")
|
||||
|
||||
def test_events_sorted_chronologically(self):
|
||||
factor_store = FakeFactorStore({
|
||||
"energy_net_margin": ["2026-03-15T09:00:00+07:00"],
|
||||
})
|
||||
sc = FakeSiamchartStore(["2026-03-20T09:00:00+07:00"])
|
||||
ledger = FakeLedger([{
|
||||
"symbol": "A", "ex_date": "2026-03-25",
|
||||
"per_share": 1.0, "estimate": False,
|
||||
}])
|
||||
events = build_event_calendar(
|
||||
factor_store=factor_store, siamchart_store=sc,
|
||||
dividend_ledger=ledger, start="2026-03-01", end="2026-05-20",
|
||||
)
|
||||
dates = [e.date for e in events]
|
||||
self.assertEqual(dates, sorted(dates))
|
||||
|
||||
def test_invalid_window_raises(self):
|
||||
with self.assertRaises(Exception):
|
||||
build_event_calendar(start="2026-05-01", end="2026-03-01")
|
||||
|
||||
|
||||
class ExecutionEventTest(unittest.TestCase):
|
||||
def test_execution_event_shape(self):
|
||||
ev = ExecutionEvent(signal_date="2026-03-15", execution_date="2026-03-16")
|
||||
self.assertEqual(ev.kind, "execution")
|
||||
self.assertEqual(ev.date.isoformat(), "2026-03-16")
|
||||
|
||||
|
||||
def make_daily_series(start: str, days: int) -> dict:
|
||||
"""Random-free daily price series with one bar per calendar day."""
|
||||
bars = []
|
||||
s = dt.date.fromisoformat(start)
|
||||
for i in range(days):
|
||||
bars.append({"date": (s + dt.timedelta(days=i)).isoformat(),
|
||||
"adjusted_close": 10.0})
|
||||
return {"A": {"bars": bars}}
|
||||
|
||||
|
||||
class ExecutionMappingTest(unittest.TestCase):
|
||||
def test_next_trading_day_is_strictly_after_signal(self):
|
||||
from app.backtest_events import next_trading_day
|
||||
series = make_daily_series("2026-03-10", 10) # 03-10..03-19
|
||||
nxt = next_trading_day(series, dt.date(2026, 3, 15))
|
||||
self.assertEqual(nxt, dt.date(2026, 3, 16))
|
||||
|
||||
def test_no_trading_day_after_returns_none(self):
|
||||
from app.backtest_events import next_trading_day
|
||||
series = make_daily_series("2026-03-10", 10)
|
||||
nxt = next_trading_day(series, dt.date(2026, 3, 25))
|
||||
self.assertIsNone(nxt)
|
||||
|
||||
def test_pair_signal_executions(self):
|
||||
from app.backtest_events import pair_signal_executions
|
||||
series = make_daily_series("2026-03-10", 10)
|
||||
sigs = [SignalReleaseEvent(released_at="2026-03-15T09:00:00+07:00")]
|
||||
pairs = pair_signal_executions(sigs, series, dt.date(2026, 3, 19))
|
||||
self.assertEqual(len(pairs), 1)
|
||||
self.assertEqual(pairs[0].execution_date, "2026-03-16")
|
||||
|
||||
def test_signal_past_end_not_executed(self):
|
||||
from app.backtest_events import pair_signal_executions
|
||||
series = make_daily_series("2026-03-10", 10)
|
||||
sigs = [SignalReleaseEvent(released_at="2026-03-15T09:00:00+07:00")]
|
||||
pairs = pair_signal_executions(sigs, series, dt.date(2026, 3, 14))
|
||||
self.assertEqual(len(pairs), 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,214 @@
|
||||
"""Tests for strict PIT backtest readiness + default-date derivation (Task 1).
|
||||
|
||||
Covered scenarios follow the acceptance criteria:
|
||||
|
||||
* no factor vintages -> ready=false, factor missing listed
|
||||
* no Siamchart snapshot -> ready=false, siamchart missing listed
|
||||
* price coverage starting after PIT factors -> recommended start =
|
||||
latest of the first-ready dates (strict: all inputs must be available)
|
||||
* recommended end = yesterday in Bangkok, bounded by latest price date
|
||||
* an explicit start earlier than readiness -> ready=false
|
||||
|
||||
All stores are lightweight fakes so tests stay deterministic and offline.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import unittest
|
||||
|
||||
from app.backtest_readiness import (
|
||||
BacktestReadiness,
|
||||
evaluate_readiness,
|
||||
yesterday_bangkok,
|
||||
)
|
||||
|
||||
|
||||
class FakeFactorStore:
|
||||
"""Minimal factor store exposing series()/value_at() for readiness tests."""
|
||||
|
||||
def __init__(self, releases: dict[str, list[str]]):
|
||||
# factor_key -> list of ISO released_at timestamps (earliest first)
|
||||
self._releases = releases
|
||||
|
||||
def series(self, key: str) -> list[dict]:
|
||||
rows = []
|
||||
for ts in self._releases.get(key, []):
|
||||
rows.append({"released_at": ts, "observed_at": ts, "value": 1.0})
|
||||
return rows
|
||||
|
||||
def value_at(self, key: str, as_of: str):
|
||||
for ts in reversed(self._releases.get(key, [])):
|
||||
if ts <= as_of:
|
||||
return 1.0
|
||||
return None
|
||||
|
||||
|
||||
class FakeSiamchartStore:
|
||||
def __init__(self, retrieved: list[str]):
|
||||
self._retrieved = sorted(retrieved)
|
||||
|
||||
def list_ids(self) -> list[str]:
|
||||
return [str(i) for i in range(len(self._retrieved))]
|
||||
|
||||
def snapshot_at(self, as_of: str) -> dict:
|
||||
chosen = [t for t in self._retrieved if t <= as_of]
|
||||
if not chosen:
|
||||
return {}
|
||||
return {"retrieved_at": chosen[-1], "_retrieved_at": chosen[-1]}
|
||||
|
||||
|
||||
def make_price_series(
|
||||
symbols: list[str], start: str, end: str, step_days: int = 30
|
||||
) -> dict:
|
||||
"""A price series {sym: {bars: [...]}} covering [start, end] for every sym."""
|
||||
s = dt.date.fromisoformat(start)
|
||||
e = dt.date.fromisoformat(end)
|
||||
bars = []
|
||||
cur = s
|
||||
while cur <= e:
|
||||
bars.append({"date": cur.isoformat(), "adjusted_close": 10.0})
|
||||
cur += dt.timedelta(days=step_days)
|
||||
return {sym: {"bars": list(bars)} for sym in symbols}
|
||||
|
||||
|
||||
def today_iso() -> str:
|
||||
return yesterday_bangkok().isoformat()
|
||||
|
||||
|
||||
# A factor store that has released every registry factor by a known date.
|
||||
def full_factor_store(release_date: str) -> FakeFactorStore:
|
||||
from app.backtest_readiness import _factor_keys_required
|
||||
releases = {
|
||||
key: [f"{release_date}T09:00:00+07:00"] for key in _factor_keys_required()
|
||||
}
|
||||
return FakeFactorStore(releases)
|
||||
|
||||
|
||||
class YesterdayDefaultTest(unittest.TestCase):
|
||||
def test_yesterday_is_bangkok_tz(self):
|
||||
y = dt.date.fromisoformat(yesterday_bangkok().isoformat())
|
||||
# just assert it's a valid date one day before "now"
|
||||
self.assertIsInstance(y, dt.date)
|
||||
# and timezone is +07 (Bangkok has no DST)
|
||||
import app.backtest_readiness as r
|
||||
now = r.bangkok_now()
|
||||
off = now.utcoffset()
|
||||
assert off is not None
|
||||
self.assertEqual(off.total_seconds(), 7 * 3600)
|
||||
|
||||
|
||||
class NoFactorVintagesTest(unittest.TestCase):
|
||||
def test_blocks_when_no_factor_release(self):
|
||||
store = FakeFactorStore({}) # no factor ever released
|
||||
sc = FakeSiamchartStore(["2025-01-01T09:00:00+07:00"])
|
||||
series = make_price_series(["A"], "2020-01-01", "2026-08-01")
|
||||
res = evaluate_readiness(
|
||||
factor_store=store, siamchart_store=sc, price_series=series
|
||||
)
|
||||
self.assertFalse(res.ready)
|
||||
self.assertIn("factor", res.missing)
|
||||
|
||||
|
||||
class NoSiamchartSnapshotTest(unittest.TestCase):
|
||||
def test_blocks_when_no_snapshot(self):
|
||||
store = full_factor_store("2025-01-01")
|
||||
sc = FakeSiamchartStore([]) # no snapshot
|
||||
series = make_price_series(["A"], "2020-01-01", "2026-08-01")
|
||||
res = evaluate_readiness(
|
||||
factor_store=store, siamchart_store=sc, price_series=series
|
||||
)
|
||||
self.assertFalse(res.ready)
|
||||
self.assertIn("siamchart", res.missing)
|
||||
|
||||
|
||||
class RecommendedStartTest(unittest.TestCase):
|
||||
def test_start_is_oldest_runnable_price(self):
|
||||
# Owner rule: backtest default start = oldest history the system holds
|
||||
# (the oldest executable price), NOT the date every input co-exists.
|
||||
# factors ready 2025-01-01, siamchart ready 2025-06-01, price from 2024
|
||||
store = full_factor_store("2025-01-01")
|
||||
sc = FakeSiamchartStore(["2025-06-01T09:00:00+07:00"])
|
||||
series = make_price_series(["A"], "2024-01-01", "2026-08-01")
|
||||
res = evaluate_readiness(
|
||||
factor_store=store, siamchart_store=sc, price_series=series
|
||||
)
|
||||
self.assertTrue(res.ready)
|
||||
# oldest runnable history = oldest price (2024-01-01), even though
|
||||
# factors/siamchart start later (flexible scoring uses what's known).
|
||||
self.assertEqual(res.recommended_start, "2024-01-01")
|
||||
self.assertEqual(res.recommended_end, today_iso())
|
||||
|
||||
def test_start_limited_by_price_when_price_latest(self):
|
||||
# factors + siamchart ready 2026-05-01, but price only from 2026-06-01
|
||||
store = full_factor_store("2026-05-01")
|
||||
sc = FakeSiamchartStore(["2026-05-01T09:00:00+07:00"])
|
||||
series = make_price_series(["A"], "2026-06-01", "2026-08-01")
|
||||
res = evaluate_readiness(
|
||||
factor_store=store, siamchart_store=sc, price_series=series
|
||||
)
|
||||
self.assertTrue(res.ready)
|
||||
self.assertEqual(res.recommended_start, "2026-06-01")
|
||||
|
||||
|
||||
class ExplicitWindowTest(unittest.TestCase):
|
||||
def test_explicit_start_before_readiness_blocks(self):
|
||||
store = full_factor_store("2025-06-01")
|
||||
sc = FakeSiamchartStore(["2025-06-01T09:00:00+07:00"])
|
||||
series = make_price_series(["A"], "2024-01-01", "2026-08-01")
|
||||
# user asks for start 2024-01-01, but PIT only ready from 2025-06-01
|
||||
res = evaluate_readiness(
|
||||
factor_store=store, siamchart_store=sc, price_series=series,
|
||||
start="2024-01-01", end="2026-08-01",
|
||||
)
|
||||
# factors missing before start -> blocked
|
||||
self.assertFalse(res.ready)
|
||||
self.assertIn("factor", res.missing)
|
||||
|
||||
def test_explicit_start_before_price_history_blocks(self):
|
||||
# Regression (cycle-1 review): explicit start that predates ALL usable
|
||||
# price history must not manufacture a false strict-PIT window. Factor +
|
||||
# Siamchart are ready at the start, but price is not -> block.
|
||||
store = full_factor_store("2024-01-01")
|
||||
sc = FakeSiamchartStore(["2024-01-01T09:00:00+07:00"])
|
||||
# price only starts 2026-06-01
|
||||
series = make_price_series(["A"], "2026-06-01", "2026-08-01")
|
||||
res = evaluate_readiness(
|
||||
factor_store=store, siamchart_store=sc, price_series=series,
|
||||
start="2025-01-01", end="2026-08-01",
|
||||
)
|
||||
self.assertFalse(res.ready)
|
||||
self.assertIn("price", res.missing)
|
||||
|
||||
def test_explicit_start_after_readiness_is_ready(self):
|
||||
store = full_factor_store("2025-01-01")
|
||||
sc = FakeSiamchartStore(["2025-01-01T09:00:00+07:00"])
|
||||
series = make_price_series(["A"], "2024-01-01", "2026-08-01")
|
||||
res = evaluate_readiness(
|
||||
factor_store=store, siamchart_store=sc, price_series=series,
|
||||
start="2025-06-01", end="2026-08-01",
|
||||
)
|
||||
self.assertTrue(res.ready)
|
||||
|
||||
|
||||
class CoverageShapeTest(unittest.TestCase):
|
||||
def test_to_dict_includes_missing_and_coverage(self):
|
||||
res = evaluate_readiness(
|
||||
factor_store=FakeFactorStore({}),
|
||||
siamchart_store=FakeSiamchartStore([]),
|
||||
price_series=make_price_series(["A"], "2024-01-01", "2026-08-01"),
|
||||
)
|
||||
d = res.to_dict()
|
||||
self.assertIn("ready", d)
|
||||
self.assertIn("missing", d)
|
||||
self.assertIn("coverage", d)
|
||||
self.assertEqual(d["timezone"], "Asia/Bangkok")
|
||||
|
||||
def test_dataclass_defaults(self):
|
||||
r = BacktestReadiness(ready=False)
|
||||
self.assertEqual(r.missing, [])
|
||||
self.assertEqual(r.coverage, [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Tests for the durable backtest run store (Task 6)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from app.backtest_store import BacktestStore
|
||||
|
||||
|
||||
class StoreTest(unittest.TestCase):
|
||||
def tearDown(self):
|
||||
self._dir = getattr(self, "_dir", None)
|
||||
if self._dir:
|
||||
import shutil
|
||||
shutil.rmtree(self._dir, ignore_errors=True)
|
||||
|
||||
def _store(self):
|
||||
self._dir = tempfile.mkdtemp()
|
||||
return BacktestStore(Path(self._dir) / "runs.json")
|
||||
|
||||
def test_add_persists_and_assigns_id(self):
|
||||
s = self._store()
|
||||
rec = s.add({"start": "2026-01-01", "end": "2026-06-01", "final_equity": 123.0})
|
||||
self.assertIn("id", rec)
|
||||
self.assertIn("ran_at", rec)
|
||||
self.assertEqual(len(s.all()), 1)
|
||||
|
||||
def test_survives_restart(self):
|
||||
path = Path(tempfile.mkdtemp()) / "runs.json"
|
||||
s1 = BacktestStore(path)
|
||||
rec = s1.add({"start": "2026-01-01", "end": "2026-06-01"})
|
||||
# new instance reads from disk
|
||||
s2 = BacktestStore(path)
|
||||
self.assertEqual(len(s2.all()), 1)
|
||||
got = s2.get(rec["id"])
|
||||
assert got is not None
|
||||
self.assertEqual(got["start"], "2026-01-01")
|
||||
|
||||
def test_get_returns_none_for_unknown(self):
|
||||
s = self._store()
|
||||
self.assertIsNone(s.get("nope"))
|
||||
|
||||
def test_all_returns_copies(self):
|
||||
s = self._store()
|
||||
s.add({"x": 1})
|
||||
s.all()[0]["x"] = 999
|
||||
self.assertEqual(s.all()[0]["x"], 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -36,9 +36,10 @@ class DashboardTest(unittest.TestCase):
|
||||
@patch("app.auto_credit.fetch_auto_credit")
|
||||
@patch("app.auto_npl.fetch_auto_npl")
|
||||
@patch("app.energy_thai.fetch_energy_thai")
|
||||
@patch("app.energy_irpc.fetch_energy_irpc")
|
||||
@patch("app.macro_thai.fetch_macro_thai")
|
||||
@patch("app.bank_npl.fetch_bank_npl")
|
||||
def test_build_returns_structure(self, bnpl, macro, energy, npl, auto):
|
||||
def test_build_returns_structure(self, bnpl, macro, energy, eirpc, npl, auto):
|
||||
class _Factory:
|
||||
def __init__(self, data): self._data = data
|
||||
def to_dict(self): return self._data
|
||||
@@ -46,6 +47,7 @@ class DashboardTest(unittest.TestCase):
|
||||
"private_consumption_yoy": 4.9, "headline_inflation_yoy": 1.95, "periods": {}})
|
||||
energy.return_value = _Factory({
|
||||
"quarterly": {"Q2/2026": {"net_profit": 8000.0, "ebitda": 9000.0}}})
|
||||
eirpc.return_value = _Factory({"net_margin_pct": 10.27, "period": "3M26"})
|
||||
auto.return_value = _Factory({
|
||||
"new_car_sales_yoy": 20.07, "total_vehicle_sales": 59000})
|
||||
npl.return_value = _Factory({
|
||||
@@ -55,7 +57,7 @@ class DashboardTest(unittest.TestCase):
|
||||
cache = _FakeCache({})
|
||||
dash = RealDashboard([], cache).build()
|
||||
self.assertEqual(len(dash["themes"]), 13) # all SET50 themes
|
||||
self.assertEqual(len(dash["sources"]), 6) # auto-derived from FACTORS (bank_npl added)
|
||||
self.assertEqual(len(dash["sources"]), 9) # auto-derived from FACTORS (energy_irpc added)
|
||||
self.assertIn("macro", dash)
|
||||
self.assertIn("board", dash)
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Tests for the IRPC refining-margin collector + theme wiring."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from app import energy_irpc, themes
|
||||
from app.energy_irpc import EnergyIrpcSnapshot, parse_energy_irpc_html
|
||||
|
||||
|
||||
_PERF_HTML = """<table>
|
||||
<tr><td>Financial Highlights</td><td>2024</td><td>2025</td><td>3M26</td></tr>
|
||||
<tr><td>Current Assets</td><td>56,999</td><td>67,086</td><td>101,978</td></tr>
|
||||
<tr><td>Total Assets</td><td>184,555</td><td>187,383</td><td>217,356</td></tr>
|
||||
<tr><td>EBITDA Margin</td><td>1.42%</td><td>2.22%</td><td>19.19%</td></tr>
|
||||
<tr><td>Net Profit Margin</td><td>(1.65%)</td><td>(1.28%)</td><td>10.27%</td></tr>
|
||||
<tr><td>Return on Equity</td><td>(7.12%)</td><td>(5.26%)</td><td>7.75%</td></tr>
|
||||
</table>"""
|
||||
|
||||
|
||||
class EnergyIrpcParseTest(unittest.TestCase):
|
||||
def test_parses_margins(self):
|
||||
snap = parse_energy_irpc_html(_PERF_HTML)
|
||||
self.assertIsInstance(snap, EnergyIrpcSnapshot)
|
||||
self.assertEqual(snap.columns, ["2024", "2025", "3M26"])
|
||||
self.assertEqual(snap.net_margin_pct, 10.27)
|
||||
self.assertEqual(snap.ebitda_margin_pct, 19.19)
|
||||
self.assertEqual(snap.roe_pct, 7.75)
|
||||
# latest period is the last column
|
||||
self.assertEqual(snap.period, "3M26")
|
||||
|
||||
def test_parses_negative_parens(self):
|
||||
# "(1.65%)" -> -1.65
|
||||
snap = parse_energy_irpc_html(_PERF_HTML)
|
||||
# net_margin picks the LAST column (3M26, +10.27), not the negative one;
|
||||
# verify the paren parser separately on a table where the last col is negative
|
||||
html_neg = _PERF_HTML.replace("<td>10.27%</td>", "<td>(3.20%)</td>")
|
||||
snap2 = parse_energy_irpc_html(html_neg)
|
||||
self.assertEqual(snap2.net_margin_pct, -3.20)
|
||||
|
||||
def test_to_dict_full(self):
|
||||
d = parse_energy_irpc_html(_PERF_HTML).to_dict()
|
||||
self.assertIn("net_margin_pct", d)
|
||||
self.assertIn("period", d)
|
||||
self.assertIn("source", d)
|
||||
|
||||
def test_missing_values_raise(self):
|
||||
html_no = "<table><tr><td>Nothing</td><td>1</td></tr></table>"
|
||||
with self.assertRaises(energy_irpc.EnergyIrpcError):
|
||||
parse_energy_irpc_html(html_no)
|
||||
|
||||
def test_every_factor_value_key_resolves(self):
|
||||
from app import factors
|
||||
keys = set(EnergyIrpcSnapshot().to_dict().keys())
|
||||
for fkey, fact in factors.FACTORS.items():
|
||||
if fact.get("fetch") != "energy_irpc":
|
||||
continue
|
||||
self.assertIn(
|
||||
fact.get("value_key"), keys,
|
||||
f"factor {fkey!r} value_key not emitted by energy_irpc",
|
||||
)
|
||||
|
||||
|
||||
class EnergyIrpcThemeDirectionTest(unittest.TestCase):
|
||||
"""IRPC margin must move energy themes the intended (bullish) direction."""
|
||||
|
||||
@staticmethod
|
||||
def _fetched(**irpc):
|
||||
base = {
|
||||
"macro_thai": {
|
||||
"private_consumption_yoy": 4.9, "private_investment_yoy": 18.1,
|
||||
"headline_inflation_yoy": 1.95, "core_inflation_yoy": 1.0,
|
||||
"unemployment_pct": 1.0, "manufacturing_yoy": -3.1,
|
||||
"tourists_ytd_mn": 16.2,
|
||||
},
|
||||
"auto_credit": {"new_car_sales_yoy": 20.07, "vehicle_production": 117383.0,
|
||||
"auto_exports": 81526.0},
|
||||
"auto_npl": {"pct_of_npls": 3.0},
|
||||
"bank_npl": {"pct_of_npls": 1.0},
|
||||
"energy_thai": {"quarterly": {"Q1/2026": {"net_profit": 19481.0, "sales": 114809.0}}},
|
||||
"energy_irpc": {"net_margin_pct": irpc.get("net", 0.0)},
|
||||
"thai_trade": {"current_account_usdm": 500.0, "exports_usdm": 34000.0,
|
||||
"imports_usdm": 38000.0},
|
||||
"te_thailand": {
|
||||
"interest_rate_pct": 1.5, "loans_to_fin_corp": 10000000.0,
|
||||
"consumer_credit_thbmn": 5000000.0, "household_debt_gdp_pct": 85.0,
|
||||
"retail_sales_yoy": 0.0, "consumer_confidence": 50.0,
|
||||
"property_prices_yoy": 0.0, "business_confidence": 50.0,
|
||||
},
|
||||
}
|
||||
# refresh energy_irpc from kwargs (neutral default 0.0 used above)
|
||||
base["energy_irpc"] = {"net_margin_pct": irpc.get("net", 0.0)}
|
||||
return base
|
||||
|
||||
def test_higher_irpc_margin_raises_energy_themes(self):
|
||||
from app import themes
|
||||
low = themes.compute_theme_surprises(self._fetched(net=-3.0))
|
||||
high = themes.compute_theme_surprises(self._fetched(net=10.0))
|
||||
self.assertGreater(high["refining_energy"], low["refining_energy"])
|
||||
self.assertGreater(high["exploration"], low["exploration"])
|
||||
self.assertGreater(high["utilities"], low["utilities"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -94,6 +94,39 @@ class EventStudyTests(unittest.TestCase):
|
||||
result = run_event_study(events, prices, windows=(1,), min_events=1)
|
||||
self.assertAlmostEqual(result["windows"]["1"]["gross_return"], 101 / 100 - 1, places=8)
|
||||
|
||||
def test_event_study_requires_known_at_for_point_in_time_prices(self):
|
||||
events = [{"event_id": "pit", "published_at": "2026-01-01T08:00:00+07:00", "signals": [{"symbol": "AOT", "target_weight": 1.0}]}]
|
||||
prices = {
|
||||
"AOT": [
|
||||
{"session_date": "2026-01-01", "close": 100},
|
||||
{"session_date": "2026-01-02", "close": 105, "known_at": "2026-01-02T17:00:00+07:00"},
|
||||
]
|
||||
}
|
||||
with self.assertRaisesRegex(EventStudyError, "known_at"):
|
||||
run_event_study(events, prices, windows=(1,), min_events=1, require_price_known_at=True)
|
||||
|
||||
def test_event_study_rejects_price_known_after_session_as_lookahead(self):
|
||||
events = [{"event_id": "lookahead", "published_at": "2026-01-01T08:00:00+07:00", "signals": [{"symbol": "AOT", "target_weight": 1.0}]}]
|
||||
prices = {
|
||||
"AOT": [
|
||||
{"session_date": "2026-01-01", "close": 100, "known_at": "2026-01-01T17:00:00+07:00", "market_timezone": "Asia/Bangkok"},
|
||||
{"session_date": "2026-01-02", "close": 105, "known_at": "2026-01-03T09:00:00+07:00", "market_timezone": "Asia/Bangkok"},
|
||||
]
|
||||
}
|
||||
with self.assertRaisesRegex(EventStudyError, "known_at"):
|
||||
run_event_study(events, prices, windows=(1,), min_events=1, require_price_known_at=True)
|
||||
|
||||
def test_event_study_checks_known_at_in_market_timezone(self):
|
||||
events = [{"event_id": "timezone-lookahead", "published_at": "2026-01-01T08:00:00+07:00", "signals": [{"symbol": "AOT", "target_weight": 1.0}]}]
|
||||
prices = {
|
||||
"AOT": [
|
||||
{"session_date": "2026-01-01", "close": 100, "known_at": "2026-01-01T18:30:00Z", "market_timezone": "Asia/Bangkok"},
|
||||
{"session_date": "2026-01-02", "close": 105, "known_at": "2026-01-02T17:00:00+07:00", "market_timezone": "Asia/Bangkok"},
|
||||
]
|
||||
}
|
||||
with self.assertRaisesRegex(EventStudyError, "known_at"):
|
||||
run_event_study(events, prices, windows=(1,), min_events=1, require_price_known_at=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,86 +0,0 @@
|
||||
"""Tests for the forward-test frozen-signal paper lifecycle."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from app.forward_test import ForwardError, ForwardTestStore
|
||||
|
||||
|
||||
def _frozen():
|
||||
return {
|
||||
"A": {"combined": 1.0, "is_dividend": True, "dividend_yield": 5.0},
|
||||
"B": {"combined": 0.8, "is_dividend": False, "dividend_yield": 0.0},
|
||||
}
|
||||
|
||||
|
||||
class ForwardTestStoreTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self._tmp = tempfile.TemporaryDirectory()
|
||||
self.path = Path(self._tmp.name) / "forward.json"
|
||||
self.store = ForwardTestStore(self.path)
|
||||
|
||||
def tearDown(self):
|
||||
self._tmp.cleanup()
|
||||
|
||||
def test_create_freezes_and_persists(self):
|
||||
run = self.store.create(1_000_000, _frozen(), as_of="2026-06-01", non_pit=True)
|
||||
self.assertEqual(run["status"], "frozen")
|
||||
self.assertEqual(run["capital"], 1_000_000)
|
||||
# reloaded from disk still has the frozen signals
|
||||
reloaded = ForwardTestStore(self.path)
|
||||
got = reloaded.get(run["id"])
|
||||
self.assertEqual(got["frozen_signals"]["A"]["combined"], 1.0)
|
||||
self.assertEqual(got["status"], "frozen")
|
||||
|
||||
def test_execute_fills_frozen_signals_at_provided_prices(self):
|
||||
run = self.store.create(100_000, _frozen(), as_of="2026-06-01", non_pit=True)
|
||||
prices = {"A": 10.0, "B": 20.0}
|
||||
ex = self.store.execute(run["id"], prices)
|
||||
self.assertEqual(ex["status"], "executed")
|
||||
# A is dividend (bucket1 50%, 50k/10=5000); B non-dividend (bucket2 20%, 20k/20=1000)
|
||||
self.assertEqual(ex["holdings"].get("A"), 5000)
|
||||
self.assertEqual(ex["holdings"].get("B"), 1000)
|
||||
|
||||
def test_mark_changes_equity_with_prices(self):
|
||||
run = self.store.create(100_000, _frozen(), as_of="2026-06-01", non_pit=True)
|
||||
ex = self.store.execute(run["id"], {"A": 10.0, "B": 20.0})
|
||||
# B rises 20 -> 22 => +1000*2 = +2000
|
||||
marked = self.store.mark(run["id"], {"A": 10.0, "B": 22.0})
|
||||
last_equity = marked["equity_history"][-1]["equity"]
|
||||
self.assertEqual(last_equity, 100_000 + 2_000)
|
||||
|
||||
def test_mature_computes_net_return(self):
|
||||
run = self.store.create(100_000, _frozen(), as_of="2026-06-01", non_pit=True)
|
||||
self.store.execute(run["id"], {"A": 10.0, "B": 20.0})
|
||||
matured = self.store.mature(run["id"], {"A": 10.0, "B": 22.0})
|
||||
self.assertEqual(matured["status"], "matured")
|
||||
self.assertAlmostEqual(matured["final_equity"], 102_000.0, places=2)
|
||||
self.assertAlmostEqual(matured["net_return"], 0.02, places=4)
|
||||
|
||||
def test_frozen_signals_cannot_be_re_frozen_on_execute(self):
|
||||
run = self.store.create(100_000, _frozen(), as_of="2026-06-01", non_pit=True)
|
||||
self.store.execute(run["id"], {"A": 10.0, "B": 20.0})
|
||||
# a second execute must fail (lifecycle - signals already locked)
|
||||
with self.assertRaises(ForwardError):
|
||||
self.store.execute(run["id"], {"A": 11.0, "B": 20.0})
|
||||
|
||||
def test_execute_before_create_unknown_run(self):
|
||||
with self.assertRaises(ForwardError):
|
||||
self.store.execute("fwd_nope", {"A": 10.0})
|
||||
|
||||
def test_double_mark_allowed_and_appends(self):
|
||||
run = self.store.create(100_000, _frozen(), as_of="2026-06-01", non_pit=True)
|
||||
self.store.execute(run["id"], {"A": 10.0, "B": 20.0})
|
||||
self.store.mark(run["id"], {"A": 10.0, "B": 21.0})
|
||||
self.store.mark(run["id"], {"A": 10.0, "B": 22.0})
|
||||
marked = self.store.get(run["id"])
|
||||
self.assertEqual(marked["status"], "marked")
|
||||
# init + execute + 2 marks = 4 entries
|
||||
self.assertEqual(len(marked["equity_history"]), 4)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Tests for the portfolio accounting ledger (Task 3)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from app.backtest_events import DIVIDEND_PAYMENT_LAG_DAYS
|
||||
from app.portfolio_ledger import (
|
||||
FEE_RATE,
|
||||
LOT_SIZE,
|
||||
PortfolioLedger,
|
||||
PortfolioLedgerError,
|
||||
)
|
||||
|
||||
|
||||
SHARES = LOT_SIZE # 100
|
||||
|
||||
|
||||
class BuySellTest(unittest.TestCase):
|
||||
def test_buy_100_lots_and_average_cost(self):
|
||||
ledger = PortfolioLedger(1_000_000)
|
||||
ledger.buy("A", SHARES, 100.0, date="2026-01-05", signal_date="2026-01-01")
|
||||
pos = ledger.position("A")
|
||||
assert pos is not None
|
||||
self.assertEqual(pos.qty, SHARES)
|
||||
self.assertEqual(pos.average_cost, 100.0)
|
||||
# fee 0.3% of 100*100=10,000 -> 30
|
||||
expected_cost = 10_000 * FEE_RATE
|
||||
self.assertAlmostEqual(ledger.state.fees, expected_cost)
|
||||
self.assertAlmostEqual(
|
||||
ledger.state.cash, 1_000_000 - 10_000 - expected_cost, places=2
|
||||
)
|
||||
|
||||
def test_average_cost_after_second_buy_at_higher_price(self):
|
||||
ledger = PortfolioLedger(1_000_000)
|
||||
ledger.buy("A", SHARES, 100.0, date="2026-01-05", signal_date="2026-01-01")
|
||||
ledger.buy("A", SHARES, 200.0, date="2026-02-05", signal_date="2026-02-01")
|
||||
pos = ledger.position("A")
|
||||
assert pos is not None
|
||||
self.assertEqual(pos.qty, 2 * SHARES)
|
||||
# avg = (100*100 + 200*100) / 200 = 150
|
||||
self.assertAlmostEqual(pos.average_cost, 150.0, places=2)
|
||||
|
||||
def test_realized_pnl_uses_average_cost(self):
|
||||
ledger = PortfolioLedger(1_000_000)
|
||||
ledger.buy("A", SHARES, 100.0, date="2026-01-05", signal_date="2026-01-01")
|
||||
# sell at 110 -> avg cost 100; gross realized = 11000 - 10000 = 1000
|
||||
trade = ledger.sell("A", SHARES, 110.0, date="2026-03-05", signal_date="2026-03-01")
|
||||
self.assertAlmostEqual(trade.realized_pnl, 1_000.0, places=2)
|
||||
self.assertAlmostEqual(ledger.state.realized_pnl, 1_000.0, places=2)
|
||||
# sell fee = 0.3% * 11000 = 33 tracked separately
|
||||
self.assertAlmostEqual(trade.fees, 33.0, places=2)
|
||||
# full exit drops the position
|
||||
self.assertIsNone(ledger.position("A"))
|
||||
|
||||
def test_buy_requires_lot_multiple(self):
|
||||
ledger = PortfolioLedger(1_000_000)
|
||||
with self.assertRaises(PortfolioLedgerError):
|
||||
ledger.buy("A", 50, 100.0, date="2026-01-05", signal_date="2026-01-01")
|
||||
|
||||
def test_buy_requires_enough_cash(self):
|
||||
ledger = PortfolioLedger(10_000)
|
||||
# 100 shares * 500 = 50,000 + fee > 10,000
|
||||
with self.assertRaises(PortfolioLedgerError):
|
||||
ledger.buy("A", SHARES, 500.0, date="2026-01-05", signal_date="2026-01-01")
|
||||
|
||||
def test_sell_more_than_held_rejected(self):
|
||||
ledger = PortfolioLedger(1_000_000)
|
||||
ledger.buy("A", SHARES, 100.0, date="2026-01-05", signal_date="2026-01-01")
|
||||
with self.assertRaises(PortfolioLedgerError):
|
||||
ledger.sell("A", 2 * SHARES, 100.0, date="2026-03-05", signal_date="2026-03-01")
|
||||
|
||||
|
||||
class DividendTest(unittest.TestCase):
|
||||
def test_entitlement_uses_shares_held_before_ex_date(self):
|
||||
ledger = PortfolioLedger(1_000_000)
|
||||
ledger.buy("A", 2 * SHARES, 100.0, date="2026-01-05", signal_date="2026-01-01")
|
||||
ledger.record_dividend_entitlement("A", "2026-03-10", 1.5)
|
||||
self.assertEqual(len(ledger.state.receivables), 1)
|
||||
r = ledger.state.receivables[0]
|
||||
self.assertEqual(r.qty_entitled, 2 * SHARES)
|
||||
self.assertAlmostEqual(r.amount, 2 * SHARES * 1.5, places=2)
|
||||
# payment = ex_date + 30 calendar days
|
||||
self.assertEqual(r.assumed_payment_date, "2026-04-09")
|
||||
self.assertEqual(r.timing_method, "ex_date_plus_30d")
|
||||
# NOT yet cash
|
||||
self.assertAlmostEqual(ledger.state.dividend_cash_received, 0.0)
|
||||
|
||||
def test_no_entitlement_when_no_shares_held(self):
|
||||
ledger = PortfolioLedger(1_000_000)
|
||||
ledger.record_dividend_entitlement("A", "2026-03-10", 1.5)
|
||||
self.assertEqual(len(ledger.state.receivables), 0)
|
||||
|
||||
def test_payment_credits_cash_at_ex_date_plus_30(self):
|
||||
ledger = PortfolioLedger(1_000_000)
|
||||
ledger.buy("A", 2 * SHARES, 100.0, date="2026-01-05", signal_date="2026-01-01")
|
||||
ledger.record_dividend_entitlement("A", "2026-03-10", 1.5)
|
||||
cash_before = ledger.state.cash
|
||||
# before payment date -> no credit
|
||||
ledger.pay_due_dividends("2026-04-08")
|
||||
self.assertAlmostEqual(ledger.state.cash, cash_before, places=2)
|
||||
# on/after payment date -> credited
|
||||
ledger.pay_due_dividends("2026-04-09")
|
||||
self.assertAlmostEqual(
|
||||
ledger.state.cash, cash_before + 2 * SHARES * 1.5, places=2
|
||||
)
|
||||
self.assertAlmostEqual(
|
||||
ledger.state.dividend_cash_received, 2 * SHARES * 1.5, places=2
|
||||
)
|
||||
self.assertEqual(len(ledger.state.receivables), 0)
|
||||
|
||||
def test_receivable_is_not_spendable_before_payment(self):
|
||||
ledger = PortfolioLedger(50_000)
|
||||
ledger.buy("A", SHARES, 100.0, date="2026-01-05", signal_date="2026-01-01")
|
||||
ledger.record_dividend_entitlement("A", "2026-03-10", 1.5)
|
||||
# dividend receivable = 150, but cash is only 10,030-ish; can't buy 100*200
|
||||
with self.assertRaises(PortfolioLedgerError):
|
||||
ledger.buy("B", SHARES, 400.0, date="2026-03-15", signal_date="2026-03-10")
|
||||
# after payment, cash grows and can fund the buy
|
||||
ledger.pay_due_dividends("2026-04-09")
|
||||
ledger.buy("B", SHARES, 10.0, date="2026-04-10", signal_date="2026-04-09")
|
||||
self.assertEqual(ledger.qty("B"), SHARES)
|
||||
|
||||
|
||||
class ReconcileTest(unittest.TestCase):
|
||||
def test_equity_matches_market_value_plus_cash(self):
|
||||
ledger = PortfolioLedger(1_000_000)
|
||||
ledger.buy("A", SHARES, 100.0, date="2026-01-05", signal_date="2026-01-01")
|
||||
prices = {"A": 110.0}
|
||||
self.assertAlmostEqual(
|
||||
ledger.equity(prices),
|
||||
ledger.state.cash + 100 * 110.0,
|
||||
places=2,
|
||||
)
|
||||
|
||||
def test_reconciled_balanced_with_sell(self):
|
||||
ledger = PortfolioLedger(100_000)
|
||||
ledger.buy("A", SHARES, 50.0, date="2026-01-05", signal_date="2026-01-01")
|
||||
ledger.sell("A", SHARES, 60.0, date="2026-02-05", signal_date="2026-02-01")
|
||||
prices = {}
|
||||
r = ledger.reconcile(prices)
|
||||
self.assertTrue(r["balanced"])
|
||||
# notional return equals realized pnl - fees
|
||||
self.assertAlmostEqual(
|
||||
r["notional_return"], r["realized_trading_pnl"] - r["transaction_costs"],
|
||||
places=1,
|
||||
)
|
||||
|
||||
def test_reconciled_balanced_with_holding_and_dividend(self):
|
||||
ledger = PortfolioLedger(100_000)
|
||||
ledger.buy("A", SHARES, 50.0, date="2026-01-05", signal_date="2026-01-01")
|
||||
ledger.record_dividend_entitlement("A", "2026-03-10", 1.0)
|
||||
ledger.pay_due_dividends("2026-04-09")
|
||||
prices = {"A": 55.0}
|
||||
r = ledger.reconcile(prices)
|
||||
self.assertTrue(r["balanced"])
|
||||
# equity = cash(+div) + 100*55
|
||||
expected_equity = ledger.state.cash + 100 * 55.0
|
||||
self.assertAlmostEqual(r["equity"], expected_equity, places=2)
|
||||
|
||||
|
||||
class FeeConfigTest(unittest.TestCase):
|
||||
def test_custom_fee_rate(self):
|
||||
ledger = PortfolioLedger(1_000_000, fee_rate=0.0)
|
||||
ledger.buy("A", SHARES, 100.0, date="2026-01-05", signal_date="2026-01-01")
|
||||
self.assertEqual(ledger.state.fees, 0.0)
|
||||
|
||||
def test_invalid_fee_rate_rejected(self):
|
||||
with self.assertRaises(PortfolioLedgerError):
|
||||
PortfolioLedger(1000, fee_rate=1.0)
|
||||
with self.assertRaises(PortfolioLedgerError):
|
||||
PortfolioLedger(1000, fee_rate=-0.1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Tests for the lot- and cash-constrained rebalancer (Task 4)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import unittest
|
||||
|
||||
from app.portfolio_ledger import PortfolioLedger
|
||||
from app.portfolio_rebalancer import (
|
||||
PortfolioRebalancer,
|
||||
RebalanceResult,
|
||||
build_candidates,
|
||||
)
|
||||
from app.simulation import Candidate
|
||||
|
||||
|
||||
def make_series(symbols: list[str], start: str, days: int, price: float = 100.0) -> dict:
|
||||
"""Flat daily price series for every symbol at a fixed price."""
|
||||
s = dt.date.fromisoformat(start)
|
||||
bars = [
|
||||
{"date": (s + dt.timedelta(days=i)).isoformat(), "adjusted_close": price}
|
||||
for i in range(days)
|
||||
]
|
||||
return {sym: {"bars": list(bars)} for sym in symbols}
|
||||
|
||||
|
||||
def scorer(*, score: float = 1.0, is_div: bool = True, yield_pct: float = 3.0):
|
||||
"""Build a frozen score map {sym: meta} with the given attributes."""
|
||||
def _build(symbols: list[str]) -> dict:
|
||||
return {
|
||||
sym: {
|
||||
"combined": score, "is_dividend": is_div,
|
||||
"dividend_yield": yield_pct,
|
||||
}
|
||||
for sym in symbols
|
||||
}
|
||||
return _build
|
||||
|
||||
|
||||
DATE = dt.date(2026, 1, 5)
|
||||
|
||||
|
||||
class RebalancerTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.series = make_series(["A", "B", "C"], "2026-01-01", 30)
|
||||
|
||||
def _rebalance(self, ledger, symbols, scores):
|
||||
cands = build_candidates(scores(symbols), self.series, DATE)
|
||||
rb = PortfolioRebalancer(ledger, self.series, cands)
|
||||
return rb.rebalance(date=DATE, signal_date=dt.date(2026, 1, 1)), cands
|
||||
|
||||
def test_builds_initial_lot_positions(self):
|
||||
ledger = PortfolioLedger(1_000_000)
|
||||
score_fn = scorer(score=1.0, is_div=True, yield_pct=3.0)
|
||||
res, _ = self._rebalance(ledger, ["A", "B", "C"], score_fn)
|
||||
self.assertGreater(res.trade_count(), 0)
|
||||
for pos in ledger.positions():
|
||||
self.assertEqual(pos.qty % 100, 0) # every position a 100-lot
|
||||
# equity reconciliation holds
|
||||
r = ledger.reconcile({"A": 100.0, "B": 100.0, "C": 100.0})
|
||||
self.assertTrue(r["balanced"])
|
||||
|
||||
def test_unchanged_target_produces_no_trade(self):
|
||||
ledger = PortfolioLedger(1_000_000)
|
||||
score_fn = scorer(score=1.0, is_div=True, yield_pct=3.0)
|
||||
res1, cands = self._rebalance(ledger, ["A", "B"], score_fn)
|
||||
self.assertGreater(res1.trade_count(), 0)
|
||||
# same scores/regime -> target unchanged -> zero trades on re-rebalance
|
||||
rb = PortfolioRebalancer(ledger, self.series, cands)
|
||||
res2 = rb.rebalance(date=DATE, signal_date=dt.date(2026, 1, 1))
|
||||
self.assertEqual(res2.trade_count(), 0)
|
||||
self.assertFalse(res2.target_changed)
|
||||
|
||||
def test_sale_profit_funds_next_purchase(self):
|
||||
# There must be enough proceeds from a profitable sale to afford a new
|
||||
# 100-lot, and the buy must actually happen.
|
||||
ledger = PortfolioLedger(1_000_000)
|
||||
# Buy A only at first: A dividend payer score 1
|
||||
score_fn = scorer(score=1.0, is_div=True)
|
||||
self._rebalance(ledger, ["A", "B"], score_fn)
|
||||
# Now target shifts to B (A exits). A is sold at same price -> no profit
|
||||
# here but proceeds fund B; test the buy occurs and reconciliation holds.
|
||||
score_b = scorer(score=2.0, is_div=True) # B outranks A
|
||||
cands = build_candidates(
|
||||
{"B": {"combined": 2.0, "is_dividend": True, "dividend_yield": 3.0},
|
||||
"A": {"combined": 0.1, "is_dividend": True, "dividend_yield": 3.0}},
|
||||
self.series, DATE)
|
||||
rb = PortfolioRebalancer(ledger, self.series, cands)
|
||||
res = rb.rebalance(date=DATE, signal_date=dt.date(2026, 2, 1))
|
||||
self.assertGreater(res.trade_count(), 0)
|
||||
# B is held, in a 100-lot
|
||||
pos = ledger.position("B")
|
||||
assert pos is not None
|
||||
self.assertEqual(pos.qty % 100, 0)
|
||||
r = ledger.reconcile({"A": 100.0, "B": 100.0})
|
||||
self.assertTrue(r["balanced"])
|
||||
|
||||
def test_cash_constraint_keeps_cash_and_skips_odd_lot(self):
|
||||
# capital that lets bucket 1 (50%) afford exactly 500 shares @100; the
|
||||
# cash-and-lot constraint must still hold and never go negative.
|
||||
ledger = PortfolioLedger(100_000)
|
||||
series = make_series(["A", "B"], "2026-01-01", 30, price=100.0)
|
||||
cands = build_candidates(
|
||||
{"A": {"combined": 1.0, "is_dividend": True, "dividend_yield": 3.0},
|
||||
"B": {"combined": 0.5, "is_dividend": False, "dividend_yield": 0.0}},
|
||||
series, DATE)
|
||||
rb = PortfolioRebalancer(ledger, series, cands)
|
||||
rb.rebalance(date=DATE, signal_date=dt.date(2026, 1, 1))
|
||||
# every position is a 100-lot, cash never negative
|
||||
for pos in ledger.positions():
|
||||
self.assertEqual(pos.qty % 100, 0)
|
||||
self.assertGreaterEqual(ledger.state.cash, 0)
|
||||
self.assertTrue(ledger.reconcile({"A": 100.0, "B": 100.0})["balanced"])
|
||||
|
||||
def test_reconcile_after_paid_dividend_funds_next_buy(self):
|
||||
ledger = PortfolioLedger(1_000_000)
|
||||
score_fn = scorer(score=1.0, is_div=True)
|
||||
self._rebalance(ledger, ["A", "B"], score_fn)
|
||||
# record a dividend on A's holding, then pay it (ex+30)
|
||||
ledger.record_dividend_entitlement("A", "2026-01-10", 2.0)
|
||||
ledger.pay_due_dividends("2026-02-09")
|
||||
# dividend cash now in ledger; reconciliation stays balanced
|
||||
r = ledger.reconcile({"A": 100.0, "B": 100.0})
|
||||
self.assertTrue(r["balanced"])
|
||||
self.assertGreater(ledger.state.dividend_cash_received, 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -5,11 +5,15 @@ import tempfile
|
||||
import unittest
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.prices import (
|
||||
DEFAULT_SYMBOL_MAP,
|
||||
PIT_ARCHIVE_CONTRACT,
|
||||
PriceSnapshotStore,
|
||||
PriceSourceError,
|
||||
_normalized_snapshot_hash,
|
||||
_observation_id,
|
||||
collect_price_snapshot,
|
||||
normalize_yahoo_chart,
|
||||
trading_dates,
|
||||
@@ -19,6 +23,33 @@ FIXTURE = Path(__file__).parent / "fixtures" / "yahoo_chart_aot.json"
|
||||
PAYLOAD = json.loads(FIXTURE.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def valid_non_pit_snapshot(snapshot_id="prices-valid", retrieved_at="2026-02-01T00:00:00+00:00"):
|
||||
return {
|
||||
"schema_version": 1,
|
||||
"source": {
|
||||
"source_id": "test.prices",
|
||||
"source_url": "https://example.test/prices",
|
||||
"snapshot_id": snapshot_id,
|
||||
"retrieved_at": retrieved_at,
|
||||
"period_start": "2026-01-01",
|
||||
"period_end": "2026-01-02",
|
||||
"quality": "revised_vendor_history",
|
||||
"point_in_time": False,
|
||||
"parser_version": "test-v1",
|
||||
"adjusted_prices": False,
|
||||
},
|
||||
"series": {
|
||||
"AOT": {
|
||||
"canonical_symbol": "AOT",
|
||||
"provider_symbol": "AOT.BK",
|
||||
"raw_payload_hash": hashlib.sha256(b"aot").hexdigest(),
|
||||
"timezone": "Asia/Bangkok",
|
||||
"bars": [{"date": "2026-01-01", "close": 100.0}],
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class FakePriceProvider:
|
||||
def __init__(self, payload):
|
||||
self.payload = payload
|
||||
@@ -75,6 +106,43 @@ class PriceSnapshotTests(unittest.TestCase):
|
||||
with self.assertRaisesRegex(PriceSourceError, "result"):
|
||||
normalize_yahoo_chart(payload, canonical_symbol="AOT", provider_symbol="AOT.BK", retrieved_at="2026-08-23T06:00:00+00:00", raw_payload_hash="a" * 64)
|
||||
|
||||
def test_normalize_yahoo_chart_rejects_malformed_provider_shapes_and_numbers(self):
|
||||
cases = []
|
||||
|
||||
payload = copy.deepcopy(PAYLOAD)
|
||||
payload["chart"]["result"][0]["meta"] = []
|
||||
cases.append(("meta", payload))
|
||||
|
||||
payload = copy.deepcopy(PAYLOAD)
|
||||
payload["chart"]["result"][0]["indicators"]["quote"][0] = []
|
||||
cases.append(("quote", payload))
|
||||
|
||||
payload = copy.deepcopy(PAYLOAD)
|
||||
payload["chart"]["result"][0]["timestamp"][0] = 10**100
|
||||
cases.append(("timestamp overflow", payload))
|
||||
|
||||
for label, field, value in (
|
||||
("boolean timestamp", "timestamp", True),
|
||||
("boolean close", "close", True),
|
||||
("boolean volume", "volume", True),
|
||||
):
|
||||
payload = copy.deepcopy(PAYLOAD)
|
||||
if field == "timestamp":
|
||||
payload["chart"]["result"][0][field][0] = value
|
||||
else:
|
||||
payload["chart"]["result"][0]["indicators"]["quote"][0][field][0] = value
|
||||
cases.append((label, payload))
|
||||
|
||||
for label, payload in cases:
|
||||
with self.subTest(label=label), self.assertRaises(PriceSourceError):
|
||||
normalize_yahoo_chart(
|
||||
payload,
|
||||
canonical_symbol="AOT",
|
||||
provider_symbol="AOT.BK",
|
||||
retrieved_at="2026-08-23T06:00:00+00:00",
|
||||
raw_payload_hash="a" * 64,
|
||||
)
|
||||
|
||||
def test_collector_persists_revised_vendor_history_snapshot(self):
|
||||
provider = FakePriceProvider(PAYLOAD)
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
@@ -93,6 +161,231 @@ class PriceSnapshotTests(unittest.TestCase):
|
||||
self.assertEqual(len(manifest["snapshots"]), 1)
|
||||
self.assertEqual(len(provider.calls), 2)
|
||||
|
||||
def test_collector_records_observation_history_for_unchanged_payload(self):
|
||||
provider = FakePriceProvider(PAYLOAD)
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=provider,
|
||||
retrieved_at="2026-08-23T06:00:00+00:00",
|
||||
)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=provider,
|
||||
retrieved_at="2026-08-24T06:00:00+00:00",
|
||||
)
|
||||
|
||||
store = PriceSnapshotStore(root)
|
||||
manifest = store.load_manifest()
|
||||
observations = manifest["observations"]
|
||||
self.assertEqual(len(observations), 2)
|
||||
self.assertEqual(observations[0]["revision_status"], "initial")
|
||||
self.assertEqual(observations[1]["revision_status"], "unchanged")
|
||||
self.assertEqual(observations[1]["previous_raw_payload_hash"], observations[0]["raw_payload_hash"])
|
||||
self.assertFalse(observations[1]["diff"]["normalized_content_changed"])
|
||||
entry = store.latest_snapshot_entry()
|
||||
self.assertEqual(entry["first_seen_at"], "2026-08-23T06:00:00+00:00")
|
||||
self.assertEqual(entry["last_seen_at"], "2026-08-24T06:00:00+00:00")
|
||||
self.assertEqual(entry["observation_count"], 2)
|
||||
|
||||
def test_collector_records_revision_diff_without_overwriting_previous_snapshot(self):
|
||||
changed_payload = copy.deepcopy(PAYLOAD)
|
||||
changed_payload["chart"]["result"][0]["indicators"]["quote"][0]["close"][0] = 61.0
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(PAYLOAD),
|
||||
retrieved_at="2026-08-23T06:00:00+00:00",
|
||||
)
|
||||
revised = collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(changed_payload),
|
||||
retrieved_at="2026-08-24T06:00:00+00:00",
|
||||
)
|
||||
|
||||
store = PriceSnapshotStore(root)
|
||||
manifest = store.load_manifest()
|
||||
observations = manifest["observations"]
|
||||
self.assertEqual(len(manifest["snapshots"]), 2)
|
||||
self.assertEqual(len(observations), 2)
|
||||
self.assertEqual(observations[1]["revision_status"], "revised")
|
||||
self.assertTrue(observations[1]["diff"]["normalized_content_changed"])
|
||||
self.assertIn("series.AOT.bars[0].close", observations[1]["diff"]["changed_paths"])
|
||||
self.assertEqual(observations[1]["previous_snapshot_id"], observations[0]["snapshot_id"])
|
||||
self.assertNotEqual(revised["source"]["snapshot_id"], observations[0]["snapshot_id"])
|
||||
self.assertEqual(store.load_snapshot(observations[0]["snapshot_id"])["series"]["AOT"]["bars"][0]["close"], 61.5)
|
||||
|
||||
def test_price_store_rejects_tampered_observation_audit_entry(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(PAYLOAD),
|
||||
retrieved_at="2026-08-23T06:00:00+00:00",
|
||||
)
|
||||
store = PriceSnapshotStore(root)
|
||||
manifest = store.load_manifest()
|
||||
manifest["observations"][0]["diff"]["changed_paths"] = ["series.AOT.bars[0].close"]
|
||||
store.manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaises(PriceSourceError):
|
||||
store.list_observations()
|
||||
|
||||
def test_price_store_rejects_recomputed_observation_id_with_mismatched_predecessor(self):
|
||||
changed_payload = copy.deepcopy(PAYLOAD)
|
||||
changed_payload["chart"]["result"][0]["indicators"]["quote"][0]["close"][0] = 61.0
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(PAYLOAD),
|
||||
retrieved_at="2026-08-23T06:00:00+00:00",
|
||||
)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(changed_payload),
|
||||
retrieved_at="2026-08-24T06:00:00+00:00",
|
||||
)
|
||||
store = PriceSnapshotStore(root)
|
||||
manifest = store.load_manifest()
|
||||
tampered = manifest["observations"][1]
|
||||
tampered["previous_raw_payload_hash"] = "0" * 64
|
||||
tampered["observation_id"] = _observation_id({key: value for key, value in tampered.items() if key != "observation_id"})
|
||||
store.manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "previous.*hash|observation"):
|
||||
store.list_observations()
|
||||
|
||||
def test_price_store_rejects_recomputed_observation_id_with_tampered_diff(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(PAYLOAD),
|
||||
retrieved_at="2026-08-23T06:00:00+00:00",
|
||||
)
|
||||
store = PriceSnapshotStore(root)
|
||||
manifest = store.load_manifest()
|
||||
tampered = manifest["observations"][0]
|
||||
tampered["diff"]["changed_paths"] = ["series.AOT.bars[0].close"]
|
||||
tampered["observation_id"] = _observation_id({key: value for key, value in tampered.items() if key != "observation_id"})
|
||||
store.manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "diff|observation"):
|
||||
store.list_observations()
|
||||
|
||||
def test_price_store_rejects_malformed_observation_id_types_without_type_error(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(PAYLOAD),
|
||||
retrieved_at="2026-08-23T06:00:00+00:00",
|
||||
)
|
||||
store = PriceSnapshotStore(root)
|
||||
manifest = store.load_manifest()
|
||||
tampered = manifest["observations"][0]
|
||||
tampered["snapshot_id"] = []
|
||||
tampered["observation_id"] = _observation_id({key: value for key, value in tampered.items() if key != "observation_id"})
|
||||
store.manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "observation"):
|
||||
store.list_observations()
|
||||
|
||||
def test_price_store_rejects_observation_history_truncation(self):
|
||||
changed_payload = copy.deepcopy(PAYLOAD)
|
||||
changed_payload["chart"]["result"][0]["indicators"]["quote"][0]["close"][0] = 61.0
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(PAYLOAD),
|
||||
retrieved_at="2026-08-23T06:00:00+00:00",
|
||||
)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(changed_payload),
|
||||
retrieved_at="2026-08-24T06:00:00+00:00",
|
||||
)
|
||||
store = PriceSnapshotStore(root)
|
||||
manifest = store.load_manifest()
|
||||
manifest["observations"] = manifest["observations"][:-1]
|
||||
store.manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "observation"):
|
||||
store.list_observations()
|
||||
|
||||
def test_collector_rejects_out_of_order_observation_after_future_capture(self):
|
||||
revised_payload = copy.deepcopy(PAYLOAD)
|
||||
revised_payload["chart"]["result"][0]["indicators"]["quote"][0]["close"][0] = 61.0
|
||||
late_payload = copy.deepcopy(PAYLOAD)
|
||||
late_payload["chart"]["result"][0]["indicators"]["quote"][0]["close"][0] = 62.0
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(PAYLOAD),
|
||||
retrieved_at="2026-08-23T06:00:00+00:00",
|
||||
)
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(revised_payload),
|
||||
retrieved_at="2026-08-24T06:00:00+00:00",
|
||||
)
|
||||
before = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
|
||||
with self.assertRaisesRegex(PriceSourceError, "immutable predecessor"):
|
||||
collect_price_snapshot(
|
||||
root,
|
||||
start="2026-01-01",
|
||||
end="2026-01-06",
|
||||
symbol_map={"AOT": "AOT.BK", "SET50": "^SET.BK"},
|
||||
provider=FakePriceProvider(late_payload),
|
||||
retrieved_at="2026-08-22T06:00:00+00:00",
|
||||
)
|
||||
after = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(after, before)
|
||||
|
||||
def test_price_store_rejects_snapshot_with_mismatched_raw_hash(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
store = PriceSnapshotStore(Path(temp_dir))
|
||||
@@ -100,6 +393,469 @@ class PriceSnapshotTests(unittest.TestCase):
|
||||
with self.assertRaisesRegex(PriceSourceError, "raw payload hash"):
|
||||
store.persist(snapshot, {"AOT.BK": b"different"})
|
||||
|
||||
def test_price_store_rejects_same_raw_hash_with_changed_stable_content(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
snapshot = {
|
||||
"schema_version": 1,
|
||||
"source": {
|
||||
"source_id": "test.prices",
|
||||
"snapshot_id": "prices-same-raw",
|
||||
"retrieved_at": "2026-02-01T00:00:00+00:00",
|
||||
"period_start": "2026-01-01",
|
||||
"period_end": "2026-01-01",
|
||||
"quality": "revised_vendor_history",
|
||||
"point_in_time": False,
|
||||
},
|
||||
"series": {
|
||||
"AOT": {
|
||||
"canonical_symbol": "AOT",
|
||||
"provider_symbol": "AOT.BK",
|
||||
"raw_payload_hash": hashlib.sha256(b"aot").hexdigest(),
|
||||
"timezone": "Asia/Bangkok",
|
||||
"bars": [{"date": "2026-01-01", "close": 100.0}],
|
||||
}
|
||||
},
|
||||
}
|
||||
raw = {"AOT.BK": b"aot"}
|
||||
store.persist(snapshot, raw)
|
||||
changed = copy.deepcopy(snapshot)
|
||||
changed["series"]["AOT"]["bars"][0]["close"] = 101.0
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "immutable"):
|
||||
store.persist(changed, raw)
|
||||
|
||||
def test_price_store_rejects_same_raw_payload_with_changed_normalized_content(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
initial = valid_non_pit_snapshot("prices-same-raw-initial", "2026-02-01T00:00:00+00:00")
|
||||
store.persist(initial, {"AOT.BK": b"aot"})
|
||||
|
||||
revised = valid_non_pit_snapshot("prices-same-raw-revised", "2026-02-02T00:00:00+00:00")
|
||||
revised["series"]["AOT"]["bars"][0]["close"] = 101.0
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "normalized content"):
|
||||
store.persist(revised, {"AOT.BK": b"aot"})
|
||||
|
||||
def test_price_store_rejects_point_in_time_flag_without_archive_contract(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
store = PriceSnapshotStore(Path(temp_dir))
|
||||
snapshot = {
|
||||
"schema_version": 1,
|
||||
"source": {
|
||||
"source_id": "test.prices",
|
||||
"snapshot_id": "prices-pit-missing-contract",
|
||||
"retrieved_at": "2026-02-01T00:00:00+00:00",
|
||||
"period_start": "2026-01-01",
|
||||
"period_end": "2026-01-02",
|
||||
"quality": "forward_market_archive",
|
||||
"point_in_time": True,
|
||||
},
|
||||
"series": {"AOT": {"bars": [{"date": "2026-01-01", "close": 100.0}]}},
|
||||
}
|
||||
with self.assertRaisesRegex(PriceSourceError, "point-in-time archive contract"):
|
||||
store.persist(snapshot, {"AOT.BK": b"aot"})
|
||||
|
||||
def test_price_store_requires_known_at_for_each_pit_bar(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
store = PriceSnapshotStore(Path(temp_dir))
|
||||
snapshot = {
|
||||
"schema_version": 1,
|
||||
"source": {
|
||||
"source_id": "test.prices",
|
||||
"source_url": "https://example.test/prices",
|
||||
"snapshot_id": "prices-pit-missing-known-at",
|
||||
"retrieved_at": "2026-02-01T00:00:00+00:00",
|
||||
"period_start": "2026-01-01",
|
||||
"period_end": "2026-01-01",
|
||||
"quality": "point_in_time_archive",
|
||||
"point_in_time": True,
|
||||
"archive_contract": PIT_ARCHIVE_CONTRACT,
|
||||
"provider_release_id": "release-2026-01-01",
|
||||
"parser_version": "pit-test-v1",
|
||||
"point_in_time_evidence": {
|
||||
"known_at_field": "known_at",
|
||||
"known_at_semantics": "provider_release_time",
|
||||
"provider_release_id": "release-2026-01-01",
|
||||
"release_published_at": "2026-01-01T17:00:00+07:00",
|
||||
},
|
||||
},
|
||||
"series": {"AOT": {"canonical_symbol": "AOT", "timezone": "Asia/Bangkok", "bars": [{"session_date": "2026-01-01", "close": 100.0}]}},
|
||||
}
|
||||
with self.assertRaisesRegex(PriceSourceError, "known_at"):
|
||||
store.persist(snapshot, {"AOT.BK": b"aot"})
|
||||
|
||||
def test_price_store_persists_and_loads_explicit_pit_archive_contract(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
store = PriceSnapshotStore(Path(temp_dir))
|
||||
snapshot = {
|
||||
"schema_version": 1,
|
||||
"source": {
|
||||
"source_id": "test.prices",
|
||||
"source_url": "https://example.test/prices",
|
||||
"snapshot_id": "prices-pit-valid",
|
||||
"retrieved_at": "2026-02-01T00:00:00+00:00",
|
||||
"period_start": "2026-01-01",
|
||||
"period_end": "2026-01-01",
|
||||
"quality": "point_in_time_archive",
|
||||
"point_in_time": True,
|
||||
"archive_contract": PIT_ARCHIVE_CONTRACT,
|
||||
"provider_release_id": "release-2026-01-01",
|
||||
"parser_version": "pit-test-v1",
|
||||
"point_in_time_evidence": {
|
||||
"known_at_field": "known_at",
|
||||
"known_at_semantics": "provider_release_time",
|
||||
"provider_release_id": "release-2026-01-01",
|
||||
"release_published_at": "2026-01-01T17:00:00+07:00",
|
||||
},
|
||||
},
|
||||
"series": {
|
||||
"AOT": {
|
||||
"canonical_symbol": "AOT",
|
||||
"timezone": "Asia/Bangkok",
|
||||
"bars": [{
|
||||
"session_date": "2026-01-01",
|
||||
"open": 99.0,
|
||||
"high": 101.0,
|
||||
"low": 98.0,
|
||||
"close": 100.0,
|
||||
"adjusted_close": 100.0,
|
||||
"volume": 1000,
|
||||
"known_at": "2026-01-01T17:00:00+07:00",
|
||||
}],
|
||||
}
|
||||
},
|
||||
}
|
||||
loaded = store.persist(snapshot, {"AOT.BK": b"aot"})
|
||||
|
||||
self.assertEqual(loaded["source"]["archive_contract"], PIT_ARCHIVE_CONTRACT)
|
||||
self.assertEqual(store.load_snapshot("prices-pit-valid")["source"]["provider_release_id"], "release-2026-01-01")
|
||||
manifest_entry = store.load_manifest()["snapshots"]["prices-pit-valid"]
|
||||
self.assertEqual(manifest_entry["archive_contract"], PIT_ARCHIVE_CONTRACT)
|
||||
self.assertTrue(manifest_entry["point_in_time"])
|
||||
|
||||
snapshot["series"]["AOT"]["bars"][0]["close"] = 101.0
|
||||
with self.assertRaisesRegex(PriceSourceError, "immutable"):
|
||||
store.persist(snapshot, {"AOT.BK": b"aot-revision"})
|
||||
|
||||
manifest = store.load_manifest()
|
||||
manifest["snapshots"]["prices-pit-valid"]["period_end"] = "2026-01-02"
|
||||
(Path(temp_dir) / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")
|
||||
with self.assertRaisesRegex(PriceSourceError, "point-in-time metadata"):
|
||||
store.load_snapshot("prices-pit-valid")
|
||||
|
||||
def test_price_store_totalizes_extreme_pit_numeric_values(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
store = PriceSnapshotStore(Path(temp_dir))
|
||||
snapshot = {
|
||||
"schema_version": 1,
|
||||
"source": {
|
||||
"source_id": "test.prices",
|
||||
"source_url": "https://example.test/prices",
|
||||
"snapshot_id": "prices-pit-extreme-number",
|
||||
"retrieved_at": "2026-02-01T00:00:00+00:00",
|
||||
"period_start": "2026-01-01",
|
||||
"period_end": "2026-01-01",
|
||||
"quality": "point_in_time_archive",
|
||||
"point_in_time": True,
|
||||
"archive_contract": PIT_ARCHIVE_CONTRACT,
|
||||
"provider_release_id": "release-2026-01-01",
|
||||
"parser_version": "pit-test-v1",
|
||||
"point_in_time_evidence": {
|
||||
"known_at_field": "known_at",
|
||||
"known_at_semantics": "provider_release_time",
|
||||
"provider_release_id": "release-2026-01-01",
|
||||
"release_published_at": "2026-01-01T17:00:00+07:00",
|
||||
},
|
||||
},
|
||||
"series": {
|
||||
"AOT": {
|
||||
"canonical_symbol": "AOT",
|
||||
"timezone": "Asia/Bangkok",
|
||||
"bars": [{
|
||||
"session_date": "2026-01-01",
|
||||
"open": 99.0,
|
||||
"high": 101.0,
|
||||
"low": 98.0,
|
||||
"close": 100.0,
|
||||
"adjusted_close": 100.0,
|
||||
"known_at": "2026-01-01T17:00:00+07:00",
|
||||
"volume": 10**1000,
|
||||
}],
|
||||
}
|
||||
},
|
||||
}
|
||||
with self.assertRaisesRegex(PriceSourceError, "point-in-time archive volume"):
|
||||
store.persist(snapshot, {"AOT.BK": b"aot"})
|
||||
|
||||
def test_price_store_rejects_non_object_manifest_before_persist(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
(root / "manifest.json").write_text("[]", encoding="utf-8")
|
||||
store = PriceSnapshotStore(root)
|
||||
snapshot = {
|
||||
"schema_version": 1,
|
||||
"source": {"source_id": "test.prices", "snapshot_id": "prices-malformed-manifest", "point_in_time": False},
|
||||
"series": {},
|
||||
}
|
||||
with self.assertRaisesRegex(PriceSourceError, "manifest"):
|
||||
store.persist(snapshot, {"AOT.BK": b"aot"})
|
||||
|
||||
def test_price_store_rejects_invalid_raw_payload_symbol(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
store = PriceSnapshotStore(Path(temp_dir))
|
||||
snapshot = {
|
||||
"schema_version": 1,
|
||||
"source": {"source_id": "test.prices", "snapshot_id": "prices-invalid-raw-symbol", "point_in_time": False},
|
||||
"series": {},
|
||||
}
|
||||
raw_payloads: Any = {1: b"aot"}
|
||||
with self.assertRaisesRegex(PriceSourceError, "raw payload"):
|
||||
store.persist(snapshot, raw_payloads)
|
||||
def test_price_store_rejects_series_provenance_mismatch_after_normalized_hash_refresh(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
snapshot = valid_non_pit_snapshot()
|
||||
store.persist(snapshot, {"AOT.BK": b"aot"})
|
||||
snapshot_path = root / "snapshots" / "prices-valid.json"
|
||||
original = json.loads(snapshot_path.read_text(encoding="utf-8"))
|
||||
|
||||
for field, value in (("provider_symbol", "PTT.BK"), ("raw_payload_hash", "0" * 64)):
|
||||
tampered = copy.deepcopy(original)
|
||||
tampered["series"]["AOT"][field] = value
|
||||
tampered["source"]["normalized_snapshot_hash"] = _normalized_snapshot_hash(tampered)
|
||||
snapshot_path.write_text(json.dumps(tampered), encoding="utf-8")
|
||||
with self.subTest(field=field), self.assertRaisesRegex(PriceSourceError, "series"):
|
||||
store.load_snapshot("prices-valid")
|
||||
|
||||
def test_price_store_rejects_missing_required_metadata_and_malformed_non_pit_series(self):
|
||||
cases = []
|
||||
snapshot = valid_non_pit_snapshot("prices-missing-schema")
|
||||
snapshot.pop("schema_version")
|
||||
cases.append(("schema_version", snapshot))
|
||||
|
||||
snapshot = valid_non_pit_snapshot("prices-missing-pit-flag")
|
||||
snapshot["source"].pop("point_in_time")
|
||||
cases.append(("point_in_time", snapshot))
|
||||
|
||||
snapshot = valid_non_pit_snapshot("prices-missing-source-id")
|
||||
snapshot["source"].pop("source_id")
|
||||
cases.append(("source identity", snapshot))
|
||||
|
||||
snapshot = valid_non_pit_snapshot("prices-malformed-series")
|
||||
snapshot["series"]["AOT"]["bars"] = "not-a-list"
|
||||
cases.append(("normalized series", snapshot))
|
||||
|
||||
snapshot = valid_non_pit_snapshot("prices-duplicate-bars")
|
||||
snapshot["series"]["AOT"]["bars"].append(copy.deepcopy(snapshot["series"]["AOT"]["bars"][0]))
|
||||
cases.append(("duplicate normalized dates", snapshot))
|
||||
|
||||
for label, snapshot in cases:
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
with self.subTest(label=label), self.assertRaises(PriceSourceError):
|
||||
PriceSnapshotStore(Path(temp_dir)).persist(snapshot, {"AOT.BK": b"aot"})
|
||||
|
||||
def test_price_store_rejects_non_pit_manifest_metadata_tampering(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
store.persist(valid_non_pit_snapshot(), {"AOT.BK": b"aot"})
|
||||
manifest_path = root / "manifest.json"
|
||||
original = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
|
||||
for field, value in (("parser_version", "tampered-parser"), ("symbols", ["PTT"])):
|
||||
manifest = copy.deepcopy(original)
|
||||
manifest["snapshots"]["prices-valid"][field] = value
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
with self.subTest(field=field), self.assertRaisesRegex(PriceSourceError, "metadata"):
|
||||
store.load_snapshot("prices-valid")
|
||||
|
||||
manifest = copy.deepcopy(original)
|
||||
manifest["snapshots"]["prices-valid"].pop("source_url")
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
with self.assertRaisesRegex(PriceSourceError, "metadata"):
|
||||
store.load_snapshot("prices-valid")
|
||||
|
||||
def test_price_store_rejects_out_of_order_insertion_without_changing_manifest(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
late = valid_non_pit_snapshot("prices-late", "2026-02-01T18:30:00-07:00")
|
||||
early = valid_non_pit_snapshot("prices-early", "2026-02-02T00:00:00+00:00")
|
||||
store.persist(late, {"AOT.BK": b"aot"})
|
||||
before = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "immutable predecessor"):
|
||||
store.persist(early, {"AOT.BK": b"aot"})
|
||||
|
||||
after = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(after, before)
|
||||
self.assertFalse((root / "snapshots" / "prices-early.json").exists())
|
||||
|
||||
def test_price_store_uses_deterministic_predecessor_for_equal_timestamps(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
timestamp = "2026-02-01T00:00:00+00:00"
|
||||
store.persist(valid_non_pit_snapshot("prices-a", timestamp), {"AOT.BK": b"aot"})
|
||||
store.persist(valid_non_pit_snapshot("prices-b", timestamp), {"AOT.BK": b"aot"})
|
||||
|
||||
observation = next(item for item in store.load_manifest()["observations"] if item["snapshot_id"] == "prices-b")
|
||||
self.assertEqual(observation["previous_snapshot_id"], "prices-a")
|
||||
|
||||
def test_price_store_rejects_reverse_arrival_for_equal_timestamp(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
timestamp = "2026-02-01T00:00:00+00:00"
|
||||
store.persist(valid_non_pit_snapshot("prices-b", timestamp), {"AOT.BK": b"aot"})
|
||||
before = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "immutable predecessor"):
|
||||
store.persist(valid_non_pit_snapshot("prices-a", timestamp), {"AOT.BK": b"aot"})
|
||||
|
||||
after = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(after, before)
|
||||
|
||||
def test_price_store_treats_same_snapshot_same_timestamp_as_idempotent(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
snapshot = valid_non_pit_snapshot("prices-idempotent", "2026-02-01T00:00:00+00:00")
|
||||
store.persist(snapshot, {"AOT.BK": b"aot"})
|
||||
store.persist(copy.deepcopy(snapshot), {"AOT.BK": b"aot"})
|
||||
|
||||
self.assertEqual(len(store.list_observations()), 1)
|
||||
|
||||
def test_price_store_rejects_equal_timestamp_initial_node_with_canonical_predecessor(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
timestamp = "2026-02-01T00:00:00+00:00"
|
||||
store.persist(valid_non_pit_snapshot("prices-a", timestamp), {"AOT.BK": b"aot"})
|
||||
store.persist(valid_non_pit_snapshot("prices-b", timestamp), {"AOT.BK": b"aot"})
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
observation = next(item for item in manifest["observations"] if item["snapshot_id"] == "prices-b")
|
||||
observation.pop("observation_id")
|
||||
observation["previous_snapshot_id"] = None
|
||||
observation["previous_raw_payload_hash"] = None
|
||||
observation["revision_status"] = "initial"
|
||||
observation["observation_id"] = _observation_id(observation)
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "predecessor chain"):
|
||||
store.load_manifest()
|
||||
|
||||
def test_price_store_rejects_duplicate_equal_time_observations_for_one_snapshot(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
snapshot_id = "prices-duplicate-time"
|
||||
store.persist(valid_non_pit_snapshot(snapshot_id, "2026-02-01T00:00:00+00:00"), {"AOT.BK": b"aot"})
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
original = manifest["observations"][0]
|
||||
duplicate_diff = copy.deepcopy(original["diff"])
|
||||
duplicate_diff["raw_payload_changed"] = False
|
||||
observations = []
|
||||
for retrieved_at in ("2026-02-01T00:00:00+00:00", "2026-02-01T00:00:00Z"):
|
||||
observation = copy.deepcopy(original)
|
||||
observation["retrieved_at"] = retrieved_at
|
||||
observation["previous_snapshot_id"] = snapshot_id
|
||||
observation["previous_raw_payload_hash"] = original["raw_payload_hash"]
|
||||
observation["revision_status"] = "unchanged"
|
||||
observation["diff"] = copy.deepcopy(duplicate_diff)
|
||||
observation["observation_id"] = _observation_id(
|
||||
{key: value for key, value in observation.items() if key != "observation_id"}
|
||||
)
|
||||
observations.append(observation)
|
||||
manifest["observations"] = observations
|
||||
entry = manifest["snapshots"][snapshot_id]
|
||||
entry["observation_count"] = 2
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "ambiguous observation"):
|
||||
store.load_manifest()
|
||||
|
||||
def test_price_store_orders_latest_snapshot_by_utc_time(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
store.persist(valid_non_pit_snapshot("prices-early", "2026-02-02T00:00:00+00:00"), {"AOT.BK": b"aot"})
|
||||
store.persist(valid_non_pit_snapshot("prices-late", "2026-02-01T18:30:00-07:00"), {"AOT.BK": b"aot"})
|
||||
|
||||
self.assertEqual(store.latest_snapshot_entry()["snapshot_id"], "prices-late")
|
||||
|
||||
def test_price_store_validates_timing_metadata_when_observation_count_is_omitted(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
store.persist(valid_non_pit_snapshot(), {"AOT.BK": b"aot"})
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
entry = manifest["snapshots"]["prices-valid"]
|
||||
entry.pop("observation_count")
|
||||
entry["first_seen_at"] = "not-a-timestamp"
|
||||
entry["last_seen_at"] = "not-a-timestamp"
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "timing"):
|
||||
store.load_manifest()
|
||||
|
||||
def test_price_store_rejects_observation_before_snapshot_first_capture(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
store.persist(valid_non_pit_snapshot("prices-temporal", "2026-02-01T00:00:00+00:00"), {"AOT.BK": b"aot"})
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
observation = manifest["observations"][0]
|
||||
observation["retrieved_at"] = "2026-01-31T00:00:00+00:00"
|
||||
observation["observation_id"] = _observation_id({key: value for key, value in observation.items() if key != "observation_id"})
|
||||
entry = manifest["snapshots"]["prices-temporal"]
|
||||
entry["first_seen_at"] = "2026-01-31T00:00:00+00:00"
|
||||
entry["last_seen_at"] = "2026-01-31T00:00:00+00:00"
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "before snapshot"):
|
||||
store.load_manifest()
|
||||
|
||||
def test_price_store_rejects_unreferenced_contract_snapshot(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
store.persist(valid_non_pit_snapshot(), {"AOT.BK": b"aot"})
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
unreferenced = copy.deepcopy(manifest["snapshots"]["prices-valid"])
|
||||
unreferenced["snapshot_id"] = "prices-unreferenced"
|
||||
unreferenced["snapshot_file"] = "prices-unreferenced.json"
|
||||
unreferenced.pop("observation_count")
|
||||
unreferenced.pop("first_seen_at")
|
||||
unreferenced.pop("last_seen_at")
|
||||
manifest["snapshots"]["prices-unreferenced"] = unreferenced
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "observation count"):
|
||||
store.load_manifest()
|
||||
|
||||
def test_price_store_rejects_malformed_snapshot_manifest_entry(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = PriceSnapshotStore(root)
|
||||
store.persist(valid_non_pit_snapshot(), {"AOT.BK": b"aot"})
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
manifest["snapshots"]["prices-malformed-entry"] = []
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(PriceSourceError, "snapshot manifest entry"):
|
||||
store.load_manifest()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,11 +1,13 @@
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
|
||||
from app.prices import PriceSnapshotStore, PriceSourceError
|
||||
from app.research import ResearchRunError, ResearchRunStore, run_tourism_research
|
||||
from app.research import ResearchRunError, ResearchRunStore, _manifest_entry_hash, _report_hash, _validate_config, run_tourism_research
|
||||
from app.vintages import VintageStore
|
||||
|
||||
|
||||
@@ -27,7 +29,7 @@ def tourism_snapshot(vintage_id: str, published_at: str) -> dict:
|
||||
"source_url": "https://example.test/bot",
|
||||
"vintage_id": vintage_id,
|
||||
"published_at": published_at,
|
||||
"retrieved_at": "2026-02-01T00:00:00+00:00",
|
||||
"retrieved_at": "2026-02-02T00:00:00+00:00",
|
||||
"release_status": "provisional",
|
||||
"parser_version": "test-v1",
|
||||
},
|
||||
@@ -35,23 +37,51 @@ def tourism_snapshot(vintage_id: str, published_at: str) -> dict:
|
||||
|
||||
|
||||
def price_snapshot(point_in_time: bool) -> tuple[dict, dict[str, bytes]]:
|
||||
def bar(session_date: str, close: float) -> dict:
|
||||
if not point_in_time:
|
||||
return {"date": session_date, "close": close}
|
||||
return {
|
||||
"date": session_date,
|
||||
"session_date": session_date,
|
||||
"open": close,
|
||||
"high": close + 1,
|
||||
"low": close - 1,
|
||||
"close": close,
|
||||
"adjusted_close": close,
|
||||
"volume": 1000,
|
||||
"known_at": f"{session_date}T17:00:00+07:00",
|
||||
}
|
||||
|
||||
pit_source = {
|
||||
"source_url": "https://example.test/prices",
|
||||
"parser_version": "pit-test-v1",
|
||||
"archive_contract": "pit-daily-v1",
|
||||
"provider_release_id": "release-2026-02-01",
|
||||
"point_in_time_evidence": {
|
||||
"known_at_field": "known_at",
|
||||
"known_at_semantics": "provider_release_time",
|
||||
"provider_release_id": "release-2026-02-01",
|
||||
"release_published_at": "2026-02-01T17:00:00+07:00",
|
||||
},
|
||||
} if point_in_time else {}
|
||||
return (
|
||||
{
|
||||
"schema_version": 1,
|
||||
"source": {
|
||||
"source_id": "test.prices",
|
||||
"snapshot_id": "prices-test",
|
||||
"retrieved_at": "2026-02-01T00:00:00+00:00",
|
||||
"retrieved_at": "2026-02-02T00:00:00+00:00",
|
||||
"period_start": "2026-01-01",
|
||||
"period_end": "2026-01-06",
|
||||
"quality": "forward_market_archive" if point_in_time else "revised_vendor_history",
|
||||
"quality": "point_in_time_archive" if point_in_time else "revised_vendor_history",
|
||||
"point_in_time": point_in_time,
|
||||
"adjusted_prices": False,
|
||||
**pit_source,
|
||||
},
|
||||
"series": {
|
||||
"AOT": {"bars": [{"date": "2026-01-01", "close": 100.0}, {"date": "2026-01-02", "close": 102.0}, {"date": "2026-01-05", "close": 104.0}, {"date": "2026-01-06", "close": 106.0}]},
|
||||
"PTT": {"bars": [{"date": "2026-01-01", "close": 100.0}, {"date": "2026-01-02", "close": 99.0}, {"date": "2026-01-05", "close": 98.0}, {"date": "2026-01-06", "close": 97.0}]},
|
||||
"SET50": {"bars": [{"date": "2026-01-01", "close": 100.0}, {"date": "2026-01-02", "close": 101.0}, {"date": "2026-01-05", "close": 102.0}, {"date": "2026-01-06", "close": 103.0}]},
|
||||
"AOT": {"canonical_symbol": "AOT", "provider_symbol": "AOT.BK", "raw_payload_hash": hashlib.sha256(b"aot").hexdigest(), "timezone": "Asia/Bangkok", "bars": [bar("2026-01-01", 100.0), bar("2026-01-02", 102.0), bar("2026-01-05", 104.0), bar("2026-01-06", 106.0)]},
|
||||
"PTT": {"canonical_symbol": "PTT", "provider_symbol": "PTT.BK", "raw_payload_hash": hashlib.sha256(b"ptt").hexdigest(), "timezone": "Asia/Bangkok", "bars": [bar("2026-01-01", 100.0), bar("2026-01-02", 99.0), bar("2026-01-05", 98.0), bar("2026-01-06", 97.0)]},
|
||||
"SET50": {"canonical_symbol": "SET50", "provider_symbol": "^SET.BK", "raw_payload_hash": hashlib.sha256(b"set").hexdigest(), "timezone": "Asia/Bangkok", "bars": [bar("2026-01-01", 100.0), bar("2026-01-02", 101.0), bar("2026-01-05", 102.0), bar("2026-01-06", 103.0)]},
|
||||
},
|
||||
"benchmark_symbol": "SET50",
|
||||
},
|
||||
@@ -60,6 +90,364 @@ def price_snapshot(point_in_time: bool) -> tuple[dict, dict[str, bytes]]:
|
||||
|
||||
|
||||
class ResearchRunTests(unittest.TestCase):
|
||||
def test_research_config_rejects_malformed_values_with_domain_error(self):
|
||||
cases = (
|
||||
((None,), 20.0, 1, 1),
|
||||
((float("nan"),), 20.0, 1, 1),
|
||||
((1,), float("inf"), 1, 1),
|
||||
((1,), 20.0, None, 1),
|
||||
((1,), 20.0, 1, float("inf")),
|
||||
)
|
||||
for windows, cost_bps, min_events, execution_lag in cases:
|
||||
with self.subTest(windows=windows, cost_bps=cost_bps, min_events=min_events, execution_lag=execution_lag):
|
||||
with self.assertRaises(ResearchRunError):
|
||||
_validate_config(
|
||||
cast(Any, windows),
|
||||
cast(Any, cost_bps),
|
||||
cast(Any, min_events),
|
||||
cast(Any, execution_lag),
|
||||
)
|
||||
|
||||
def test_research_run_store_binds_report_hash_and_rejects_tampering(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
|
||||
stored = store.persist(report)
|
||||
|
||||
self.assertRegex(stored["report_hash"], r"^[a-f0-9]{64}$")
|
||||
report_path = root / "reports" / "tourism-run-test.json"
|
||||
tampered = json.loads(report_path.read_text(encoding="utf-8"))
|
||||
tampered["reason"] = "tampered"
|
||||
report_path.write_text(json.dumps(tampered), encoding="utf-8")
|
||||
with self.assertRaisesRegex(ResearchRunError, "integrity"):
|
||||
store.load("tourism-run-test")
|
||||
|
||||
def test_research_run_store_rejects_manifest_hash_tampering(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-manifest-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
store.persist(report)
|
||||
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
manifest["runs"]["tourism-run-manifest-test"]["report_hash"] = "0" * 64
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
with self.assertRaisesRegex(ResearchRunError, "integrity"):
|
||||
store.load("tourism-run-manifest-test")
|
||||
|
||||
def test_research_run_store_migrates_legacy_reports_explicitly(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-legacy-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
legacy_manifest = {
|
||||
"schema_version": 1,
|
||||
"runs": {
|
||||
"tourism-run-legacy-test": {
|
||||
"run_id": "tourism-run-legacy-test",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"report_file": "tourism-run-legacy-test.json",
|
||||
}
|
||||
},
|
||||
}
|
||||
(root / "reports").mkdir(parents=True)
|
||||
(root / "reports" / "tourism-run-legacy-test.json").write_text(json.dumps(report), encoding="utf-8")
|
||||
(root / "manifest.json").write_text(json.dumps(legacy_manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(ResearchRunError, "integrity"):
|
||||
store.load("tourism-run-legacy-test")
|
||||
|
||||
self.assertEqual(store.migrate_legacy(), 1)
|
||||
migrated = store.load("tourism-run-legacy-test")
|
||||
manifest_entry = store.load_manifest()["runs"]["tourism-run-legacy-test"]
|
||||
self.assertEqual(migrated["report_hash_algorithm"], "sha256-json-canonical-v1")
|
||||
self.assertRegex(migrated["report_hash"], r"^[a-f0-9]{64}$")
|
||||
self.assertRegex(manifest_entry["manifest_entry_hash"], r"^[a-f0-9]{64}$")
|
||||
self.assertEqual(store.migrate_legacy(), 0)
|
||||
|
||||
def test_research_run_store_completes_interrupted_legacy_migration(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-partial-migration-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
partial_report = copy.deepcopy(report)
|
||||
partial_report["report_hash_algorithm"] = "sha256-json-canonical-v1"
|
||||
partial_report["report_hash"] = _report_hash(partial_report)
|
||||
legacy_entry = {
|
||||
"run_id": report["run_id"],
|
||||
"status": report["status"],
|
||||
"reason": report["reason"],
|
||||
"generated_at": report["generated_at"],
|
||||
"report_file": f"{report['run_id']}.json",
|
||||
}
|
||||
(root / "reports").mkdir(parents=True)
|
||||
(root / "reports" / f"{report['run_id']}.json").write_text(json.dumps(partial_report), encoding="utf-8")
|
||||
(root / "manifest.json").write_text(json.dumps({"schema_version": 1, "runs": {report["run_id"]: legacy_entry}}), encoding="utf-8")
|
||||
|
||||
self.assertEqual(store.migrate_legacy(), 1)
|
||||
self.assertEqual(store.load(report["run_id"])["report_hash"], partial_report["report_hash"])
|
||||
self.assertEqual(store.migrate_legacy(), 0)
|
||||
|
||||
def test_research_run_store_rejects_manifest_identity_tampering(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-identity-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
store.persist(report)
|
||||
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
entry = manifest["runs"]["tourism-run-identity-test"]
|
||||
entry["run_id"] = "tourism-run-other"
|
||||
entry["manifest_entry_hash"] = _manifest_entry_hash(entry)
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(ResearchRunError, "integrity"):
|
||||
store.load("tourism-run-identity-test")
|
||||
|
||||
def test_research_run_store_rejects_manifest_metadata_tampering(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-metadata-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
store.persist(report)
|
||||
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
manifest["runs"]["tourism-run-metadata-test"]["generated_at"] = "2099-02-01T00:00:00+00:00"
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
with self.assertRaisesRegex(ResearchRunError, "integrity"):
|
||||
store.load("tourism-run-metadata-test")
|
||||
|
||||
def test_research_run_store_rejects_non_object_report(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-shape-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
store.persist(report)
|
||||
report_path = root / "reports" / "tourism-run-shape-test.json"
|
||||
report_path.write_text("[\"tampered\"]", encoding="utf-8")
|
||||
with self.assertRaisesRegex(ResearchRunError, "invalid"):
|
||||
store.load("tourism-run-shape-test")
|
||||
|
||||
def test_research_run_store_rejects_non_object_manifest(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
(root / "manifest.json").write_text("[]", encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(ResearchRunError, "schema"):
|
||||
store.load_manifest()
|
||||
|
||||
def test_research_run_store_rejects_unreadable_manifest_bytes(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
(root / "manifest.json").write_bytes(b"\xff")
|
||||
|
||||
with self.assertRaisesRegex(ResearchRunError, "unreadable"):
|
||||
store.load_manifest()
|
||||
|
||||
def test_research_run_store_rejects_unreadable_report_bytes(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-encoding-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
store.persist(report)
|
||||
(root / "reports" / "tourism-run-encoding-test.json").write_bytes(b"\xff")
|
||||
|
||||
with self.assertRaisesRegex(ResearchRunError, "unreadable"):
|
||||
store.load("tourism-run-encoding-test")
|
||||
|
||||
def test_research_run_store_list_runs_rejects_manifest_metadata_tampering(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-list-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
store.persist(report)
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
manifest["runs"]["tourism-run-list-test"]["generated_at"] = "2099-02-01T00:00:00+00:00"
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(ResearchRunError, "integrity"):
|
||||
store.list_runs()
|
||||
|
||||
def test_research_run_store_latest_and_list_reject_malformed_manifest_entry(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-entry-shape-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
store.persist(report)
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
manifest["runs"]["tourism-run-entry-shape-test"] = []
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(ResearchRunError, "entry"):
|
||||
store.list_runs()
|
||||
with self.assertRaisesRegex(ResearchRunError, "entry"):
|
||||
store.latest()
|
||||
|
||||
def test_research_run_store_persist_rejects_malformed_existing_manifest_entry(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-persist-entry-test",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
store.persist(report)
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
manifest["runs"]["tourism-run-persist-entry-test"] = []
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(ResearchRunError, "entry"):
|
||||
store.persist(report)
|
||||
|
||||
def test_research_run_store_persist_validates_unrelated_manifest_entries_before_write(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = ResearchRunStore(root)
|
||||
existing_report = {
|
||||
"schema_version": 1,
|
||||
"run_id": "tourism-run-persist-unrelated-existing",
|
||||
"theme": "tourism",
|
||||
"status": "blocked",
|
||||
"reason": "test",
|
||||
"generated_at": "2026-02-01T00:00:00+00:00",
|
||||
"config": {},
|
||||
"gates": {},
|
||||
"inputs": {},
|
||||
}
|
||||
new_report = {
|
||||
**existing_report,
|
||||
"run_id": "tourism-run-persist-unrelated-new",
|
||||
}
|
||||
store.persist(existing_report)
|
||||
|
||||
manifest_path = root / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
manifest["runs"]["tourism-run-persist-unrelated-malformed"] = []
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(ResearchRunError, "entry"):
|
||||
store.persist(new_report)
|
||||
self.assertFalse((root / "reports" / "tourism-run-persist-unrelated-new.json").exists())
|
||||
|
||||
def test_price_store_loads_snapshot_and_verifies_raw_payload(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
store = PriceSnapshotStore(Path(temp_dir))
|
||||
@@ -100,6 +488,78 @@ class ResearchRunTests(unittest.TestCase):
|
||||
self.assertNotIn("result", report)
|
||||
self.assertEqual(run_store.latest()["run_id"], report["run_id"])
|
||||
|
||||
def test_runner_allows_explicit_exploratory_mode_with_revised_prices(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
vintage_store = VintageStore(root / "tourism")
|
||||
vintage_store.persist(b"tourism", tourism_snapshot("v1", "2026-01-01T08:00:00+07:00"))
|
||||
price_store = PriceSnapshotStore(root / "prices")
|
||||
snapshot, raw = price_snapshot(point_in_time=False)
|
||||
price_store.persist(snapshot, raw)
|
||||
run_store = ResearchRunStore(root / "runs")
|
||||
|
||||
report = run_tourism_research(
|
||||
vintage_store,
|
||||
price_store,
|
||||
run_store,
|
||||
mode="exploratory",
|
||||
min_events=1,
|
||||
windows=(1,),
|
||||
)
|
||||
|
||||
self.assertEqual(report["status"], "descriptive_only")
|
||||
self.assertEqual(report["research_mode"], "exploratory")
|
||||
self.assertEqual(report["result_scope"], "non_pit_descriptive_only")
|
||||
self.assertEqual(report["gates"]["prices"]["status"], "descriptive_only")
|
||||
self.assertEqual(report["gates"]["prices"]["reason"], "price_series_not_point_in_time")
|
||||
self.assertEqual(report["result"]["event_count"], 1)
|
||||
|
||||
def test_runner_keeps_exploratory_pit_inputs_descriptive_only(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
vintage_store = VintageStore(root / "tourism")
|
||||
vintage_store.persist(b"tourism", tourism_snapshot("v1", "2026-01-01T08:00:00+07:00"))
|
||||
price_store = PriceSnapshotStore(root / "prices")
|
||||
snapshot, raw = price_snapshot(point_in_time=True)
|
||||
price_store.persist(snapshot, raw)
|
||||
run_store = ResearchRunStore(root / "runs")
|
||||
|
||||
report = run_tourism_research(
|
||||
vintage_store,
|
||||
price_store,
|
||||
run_store,
|
||||
mode="exploratory",
|
||||
min_events=1,
|
||||
windows=(1,),
|
||||
)
|
||||
|
||||
self.assertEqual(report["status"], "descriptive_only")
|
||||
self.assertEqual(report["result_scope"], "non_pit_descriptive_only")
|
||||
self.assertEqual(report["gates"]["prices"]["status"], "descriptive_only")
|
||||
self.assertFalse(report["gates"]["prices"]["validated"])
|
||||
self.assertTrue(report["gates"]["prices"]["point_in_time"])
|
||||
self.assertEqual(report["gates"]["prices"]["reason"], "exploratory_mode_non_validated")
|
||||
|
||||
def test_runner_reuses_same_run_when_only_observation_time_changes(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
vintage_store = VintageStore(root / "tourism")
|
||||
vintage_store.persist(b"tourism", tourism_snapshot("v1", "2026-01-01T08:00:00+07:00"))
|
||||
price_store = PriceSnapshotStore(root / "prices")
|
||||
snapshot, raw = price_snapshot(point_in_time=False)
|
||||
price_store.persist(snapshot, raw)
|
||||
run_store = ResearchRunStore(root / "runs")
|
||||
|
||||
first = run_tourism_research(vintage_store, price_store, run_store, mode="exploratory", min_events=1, windows=(1,))
|
||||
observed_again = copy.deepcopy(snapshot)
|
||||
observed_again["source"]["retrieved_at"] = "2026-02-03T00:00:00+00:00"
|
||||
price_store.persist(observed_again, raw)
|
||||
second = run_tourism_research(vintage_store, price_store, run_store, mode="exploratory", min_events=1, windows=(1,))
|
||||
|
||||
self.assertEqual(second["run_id"], first["run_id"])
|
||||
self.assertEqual(second, first)
|
||||
self.assertEqual(len(price_store.list_observations()), 2)
|
||||
|
||||
def test_runner_computes_replayable_result_when_both_gates_pass(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
|
||||
@@ -47,5 +47,206 @@ class SchedulerTest(unittest.TestCase):
|
||||
self.assertIn("at", data)
|
||||
|
||||
|
||||
class VintageCollectionTest(unittest.TestCase):
|
||||
"""Automatic PIT vintage collection via the scheduler (offline, deterministic)."""
|
||||
|
||||
def _fetched(self):
|
||||
# a fetched_by_module dict keyed by FACTORS.fetch module holding values
|
||||
return {
|
||||
"macro_thai": {
|
||||
"tourists_ytd_mn": 15.0, "private_consumption_yoy": 3.0,
|
||||
"private_investment_yoy": 4.0, "manufacturing_yoy": 1.0,
|
||||
"headline_inflation_yoy": 2.0,
|
||||
"core_inflation_yoy": 1.2, "unemployment_pct": 1.1,
|
||||
"periods": {"private_consumption_yoy": "Jun 2026"},
|
||||
},
|
||||
"auto_credit": {"new_car_sales_yoy": 5.0, "vehicle_production": 100000.0,
|
||||
"auto_exports": 80000.0},
|
||||
"auto_npl": {"pct_of_npls": 3.0},
|
||||
"bank_npl": {"pct_of_npls": 0.8},
|
||||
"energy_thai": {"quarterly": {"q1": {"net_profit": 500.0, "sales": 10000.0}}},
|
||||
"energy_irpc": {"net_margin_pct": 5.0},
|
||||
"thai_trade": {"current_account_usdm": 500.0, "exports_usdm": 34000.0,
|
||||
"imports_usdm": 38000.0},
|
||||
"te_thailand": {"interest_rate_pct": 1.0, "loans_to_fin_corp": 10000000.0,
|
||||
"consumer_credit_thbmn": 5000000.0,
|
||||
"household_debt_gdp_pct": 85.0,
|
||||
"retail_sales_yoy": 0.0, "consumer_confidence": 50.0,
|
||||
"property_prices_yoy": 1.0, "business_confidence": 50.0},
|
||||
}
|
||||
|
||||
def test_pit_factor_vintages_written_on_refresh(self):
|
||||
snap_dir = Path(tempfile.mkdtemp())
|
||||
sched = AppDataScheduler(_FakeCache(), snap_dir, interval_seconds=99999)
|
||||
# avoid the siamchart + dividend network paths touching real data dir:
|
||||
with patch("app.scheduler.AppDataScheduler._record_siamchart_vintages", return_value=None), \
|
||||
patch("app.scheduler.AppDataScheduler._maybe_refresh_dated_dividends", return_value=None):
|
||||
# invoke the PIT-factor recorder directly with a fetched dict
|
||||
sched._record_pit_factor_vintages(self._fetched())
|
||||
store_dir = snap_dir / "factor_vintages"
|
||||
files = list(store_dir.glob("*.jsonl"))
|
||||
# every registry factor with a fetch key should have a vintage file
|
||||
from app import factors as factors_mod
|
||||
expect = [f for f in factors_mod.FACTORS if factors_mod.FACTORS[f].get("fetch")]
|
||||
self.assertGreaterEqual(len(files), len(expect) - 1) # some may be skipped if val None
|
||||
# verify macro_consumption has a PIT vintage readable by the store
|
||||
from app.factor_vintages import FactorVintageStore
|
||||
st = FactorVintageStore(snap_dir)
|
||||
import datetime as _dt
|
||||
now_iso = _dt.datetime.now(_dt.timezone.utc).isoformat(timespec="seconds")
|
||||
val = st.value_at("macro_consumption", now_iso)
|
||||
self.assertEqual(val, 3.0) # private_consumption_yoy
|
||||
|
||||
def test_pit_vintage_dedupes_unchanged_value(self):
|
||||
snap_dir = Path(tempfile.mkdtemp())
|
||||
sched = AppDataScheduler(_FakeCache(), snap_dir, interval_seconds=99999)
|
||||
with patch("app.scheduler.AppDataScheduler._record_siamchart_vintages", return_value=None), \
|
||||
patch("app.scheduler.AppDataScheduler._maybe_refresh_dated_dividends", return_value=None):
|
||||
sched._record_pit_factor_vintages(self._fetched())
|
||||
sched._record_pit_factor_vintages(self._fetched()) # same values -> no new points
|
||||
from app.factor_vintages import FactorVintageStore
|
||||
st = FactorVintageStore(snap_dir)
|
||||
rows = st.series("macro_consumption")
|
||||
self.assertEqual(len(rows), 1) # unchanged value not re-appended
|
||||
|
||||
def test_siamchart_vintage_persisted_when_snapshot_present(self):
|
||||
snap_dir = Path(tempfile.mkdtemp())
|
||||
# create a snapshot file where the scheduler looks for it
|
||||
(snap_dir / "siamchart").mkdir(parents=True, exist_ok=True)
|
||||
snap = {"retrieved_at": "2026-06-01T09:00:00+07:00", "rows": [], "details": {}}
|
||||
(snap_dir / "siamchart" / "set50_master.json").write_text(
|
||||
__import__("json").dumps(snap), encoding="utf-8")
|
||||
sched = AppDataScheduler(_FakeCache(), snap_dir, interval_seconds=99999)
|
||||
with patch("app.scheduler.AppDataScheduler._record_pit_factor_vintages", return_value=None), \
|
||||
patch("app.scheduler.AppDataScheduler._maybe_refresh_dated_dividends", return_value=None):
|
||||
sched._record_siamchart_vintages()
|
||||
manifest = snap_dir / "siamchart_vintages" / "_manifest.json"
|
||||
self.assertTrue(manifest.exists())
|
||||
import json
|
||||
m = json.loads(manifest.read_text())
|
||||
self.assertEqual(len(m.get("snapshots", {})), 1)
|
||||
|
||||
def test_siamchart_vintage_noop_without_snapshot(self):
|
||||
snap_dir = Path(tempfile.mkdtemp())
|
||||
sched = AppDataScheduler(_FakeCache(), snap_dir, interval_seconds=99999)
|
||||
with patch("app.scheduler.AppDataScheduler._record_pit_factor_vintages", return_value=None), \
|
||||
patch("app.scheduler.AppDataScheduler._maybe_refresh_dated_dividends", return_value=None):
|
||||
sched._record_siamchart_vintages()
|
||||
manifest = snap_dir / "siamchart_vintages" / "_manifest.json"
|
||||
self.assertFalse(manifest.exists()) if not manifest.exists() else self.assertEqual(
|
||||
len(__import__("json").loads(manifest.read_text()).get("snapshots", {})), 1)
|
||||
|
||||
|
||||
class CadenceAndHealthTest(unittest.TestCase):
|
||||
"""Per-source cadence + source-health log (user requirements)."""
|
||||
|
||||
def test_job_due_respects_frequency_marker(self):
|
||||
import json
|
||||
snap_dir = Path(tempfile.mkdtemp())
|
||||
sched = AppDataScheduler(_FakeCache(), snap_dir, interval_seconds=99999)
|
||||
job = {"key": "macro_thai", "frequency": "monthly"}
|
||||
# never run -> due
|
||||
self.assertTrue(sched._job_due(job))
|
||||
sched._mark_job_run(job)
|
||||
# just marked -> not due again for ~30 days
|
||||
self.assertFalse(sched._job_due(job))
|
||||
# age the marker back 40 days -> due again
|
||||
import datetime as _dt
|
||||
old = (_dt.datetime.now().astimezone() - _dt.timedelta(days=40)).isoformat(timespec="seconds")
|
||||
(snap_dir / "scheduler" / "job_macro_thai.json").write_text(
|
||||
json.dumps({"at": old}), encoding="utf-8")
|
||||
self.assertTrue(sched._job_due(job))
|
||||
|
||||
def test_analyze_error_classifies(self):
|
||||
from app.scheduler import AppDataScheduler
|
||||
self.assertEqual(AppDataScheduler._analyze_error("timed out connecting"), "timeout")
|
||||
self.assertEqual(AppDataScheduler._analyze_error("Connection refused to host"), "network")
|
||||
self.assertEqual(AppDataScheduler._analyze_error("HTTP 404 Not Found"), "http")
|
||||
self.assertEqual(AppDataScheduler._analyze_error("JSONDecodeError: expecting value"), "parse")
|
||||
self.assertEqual(AppDataScheduler._analyze_error("page structure changed - KeyError 'field'"), "structure")
|
||||
self.assertEqual(AppDataScheduler._analyze_error("unauthorized token expired"), "auth")
|
||||
self.assertEqual(AppDataScheduler._analyze_error(""), "other")
|
||||
|
||||
def test_source_health_log_written_and_readable(self):
|
||||
import json
|
||||
snap_dir = Path(tempfile.mkdtemp())
|
||||
sched = AppDataScheduler(_FakeCache(), snap_dir, interval_seconds=99999)
|
||||
results = [
|
||||
{"key": "macro_thai", "label": "ภาพรวม (BOT)", "ok": True, "at": "2026-08-28T00:00:00+07:00"},
|
||||
{"key": "auto_npl", "label": "NPL รถ", "ok": False,
|
||||
"error": "JSONDecodeError: expecting value at line 1 (structure change?)",
|
||||
"at": "2026-08-28T00:01:00+07:00"},
|
||||
]
|
||||
sched._append_source_log(results)
|
||||
entries = sched._load_source_health()
|
||||
self.assertEqual(len(entries), 2)
|
||||
by_key = {e["key"]: e for e in entries}
|
||||
self.assertTrue(by_key["macro_thai"]["ok"])
|
||||
self.assertFalse(by_key["auto_npl"]["ok"])
|
||||
self.assertEqual(by_key["auto_npl"]["category"], "parse")
|
||||
|
||||
def test_refresh_only_runs_due_jobs(self):
|
||||
# with frequency markers set to "now", a second refresh_all in the same
|
||||
# tick should skip all factor jobs but still try daily jobs.
|
||||
snap_dir = Path(tempfile.mkdtemp())
|
||||
sched = AppDataScheduler(_FakeCache(), snap_dir, interval_seconds=99999)
|
||||
from app.scheduler import _REFRESH_JOBS, _DAILY_JOBS
|
||||
for job in _REFRESH_JOBS + _DAILY_JOBS:
|
||||
sched._mark_job_run(job)
|
||||
# all marked -> a refresh tick runs nothing successfully (no network)
|
||||
results = sched.refresh_all()
|
||||
# daily jobs that ARE collections we stubbed: none should hard-crash
|
||||
self.assertIsInstance(results, list)
|
||||
|
||||
|
||||
class DividendCooldownTest(unittest.TestCase):
|
||||
def _sched(self, snap_dir, cooldown):
|
||||
return AppDataScheduler(_FakeCache(), snap_dir, interval_seconds=99999,
|
||||
dividend_cooldown_seconds=cooldown)
|
||||
|
||||
def test_refreshes_once_then_respects_cooldown(self):
|
||||
snap_dir = Path(tempfile.mkdtemp())
|
||||
sched = self._sched(snap_dir, cooldown=3600) # 1h cooldown
|
||||
calls = {"n": 0}
|
||||
|
||||
def fake_fetch(sym):
|
||||
calls["n"] += 1
|
||||
return [("2025-01-01", 1.0)]
|
||||
|
||||
fake_fv = {"factors": [{"symbol": "PTT"}]}
|
||||
with patch("app.siamchart_factors.build_factor_view", return_value=fake_fv), \
|
||||
patch("app.siamchart.fetch_dividend_history", side_effect=fake_fetch):
|
||||
sched._maybe_refresh_dated_dividends() # first -> fetch
|
||||
n_after_first = calls["n"]
|
||||
sched._maybe_refresh_dated_dividends() # second, within cooldown -> skip
|
||||
self.assertEqual(n_after_first, 1) # fetched once
|
||||
self.assertEqual(calls["n"], 1) # second call skipped
|
||||
self.assertTrue((snap_dir / "dividends" / "ledger.json").exists())
|
||||
|
||||
def test_refetches_after_cooldown_elapses(self):
|
||||
snap_dir = Path(tempfile.mkdtemp())
|
||||
sched = self._sched(snap_dir, cooldown=1) # 1s cooldown
|
||||
calls = {"n": 0}
|
||||
|
||||
def fake_fetch(sym):
|
||||
calls["n"] += 1
|
||||
return [("2025-01-01", 1.0)]
|
||||
|
||||
fake_fv = {"factors": [{"symbol": "PTT"}]}
|
||||
with patch("app.siamchart_factors.build_factor_view", return_value=fake_fv), \
|
||||
patch("app.siamchart.fetch_dividend_history", side_effect=fake_fetch):
|
||||
sched._maybe_refresh_dated_dividends()
|
||||
self.assertEqual(calls["n"], 1)
|
||||
# force cooldown to have elapsed by rewriting the marker back in time
|
||||
import json
|
||||
import datetime as _dt
|
||||
sched._div_marker.write_text(
|
||||
json.dumps({"at": (_dt.datetime.now().astimezone() - _dt.timedelta(hours=1)).isoformat()}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
sched._maybe_refresh_dated_dividends()
|
||||
self.assertEqual(calls["n"], 2) # refetched
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -87,5 +87,105 @@ class AllocationTest(unittest.TestCase):
|
||||
self.assertAlmostEqual(res.unallocated_cash, 50_000, places=2)
|
||||
|
||||
|
||||
class MomentumSelectionTest(unittest.TestCase):
|
||||
"""Owner's "ทำกำไร" rule: bucket 1/2 rank by price-trend momentum and are
|
||||
gated on a POSITIVE theme signal — NOT by combined/EPS score."""
|
||||
|
||||
def _cand(self, sym, price, combined, div, yield_, momentum, theme):
|
||||
return Candidate(sym, price, combined, div, yield_,
|
||||
momentum=momentum, theme_signal=theme)
|
||||
|
||||
def test_bucket1_ranks_by_momentum_not_score(self):
|
||||
# A high-score but NEGATIVE-momentum dividend name must NOT win bucket 1
|
||||
# over a positive-momentum one (owner: "ทำกำไร" = price likely to rise).
|
||||
cands = [
|
||||
self._cand("SLOW", 10.0, 9.0, True, 2.0, -1.5, 0.5), # high score, falling price
|
||||
self._cand("FAST", 10.0, 0.5, True, 1.0, +2.0, 0.6), # low score, rising price
|
||||
]
|
||||
res = allocate_capital(1_000_000, cands)
|
||||
b1 = [o.symbol for o in res.orders if o.bucket == 1]
|
||||
self.assertEqual(b1, ["FAST"]) # FAST (momentum +2) beats SLOW (-1.5)
|
||||
|
||||
def test_negative_theme_is_excluded_from_profit_bucket(self):
|
||||
# Even a high-momentum name is not eligible for bucket 1/2 when its
|
||||
# theme_signal is <= 0 (owner gate). It may still land in bucket 3 (yield).
|
||||
cands = [
|
||||
self._cand("NO_THEME", 10.0, 5.0, True, 8.0, +3.0, -0.2), # momentum up but theme negative
|
||||
self._cand("GOOD", 10.0, 5.0, True, 2.0, +1.0, 0.5),
|
||||
]
|
||||
res = allocate_capital(1_000_000, cands)
|
||||
b1 = [o.symbol for o in res.orders if o.bucket == 1]
|
||||
self.assertNotIn("NO_THEME", b1) # gated out of the profit bucket
|
||||
self.assertIn("GOOD", b1)
|
||||
# NO_THEME may still be picked by bucket 3 (highest yield, 8%)
|
||||
b3 = [o.symbol for o in res.orders if o.bucket == 3]
|
||||
self.assertIn("NO_THEME", b3)
|
||||
|
||||
def test_bucket2_uses_non_dividend_momentum(self):
|
||||
cands = [
|
||||
self._cand("ND_UP", 10.0, 9.0, False, 0.0, +2.5, 0.7), # non-div, momentum up
|
||||
self._cand("ND_DN", 10.0, 9.0, False, 0.0, -2.5, 0.7), # non-div, momentum down
|
||||
]
|
||||
res = allocate_capital(1_000_000, cands)
|
||||
b2 = [o.symbol for o in res.orders if o.bucket == 2]
|
||||
self.assertEqual(b2, ["ND_UP"]) # rising price chosen over falling
|
||||
|
||||
def test_negative_momentum_excluded_from_profit_buckets(self):
|
||||
# A rising-price name wins the profit bucket; a FALLING-price name —
|
||||
# even with a positive theme — must NOT be picked as "ทำกำไร".
|
||||
cands = [
|
||||
self._cand("UP", 10.0, 5.0, False, 0.0, +1.5, 0.6), # rising, non-div
|
||||
self._cand("DOWN", 10.0, 5.0, False, 0.0, -1.5, 0.6), # falling, same theme
|
||||
]
|
||||
res = allocate_capital(1_000_000, cands)
|
||||
b2 = [o.symbol for o in res.orders if o.bucket == 2]
|
||||
self.assertEqual(b2, ["UP"]) # DOWN (falling price) excluded
|
||||
self.assertNotIn("DOWN", b2)
|
||||
|
||||
def test_negative_combined_excluded_from_profit_buckets(self):
|
||||
# Owner rule: a stock whose OVERALL (combined) score is negative must not
|
||||
# be recommended in the profit buckets, even with positive momentum/theme.
|
||||
cands = [
|
||||
self._cand("NEG_A", 10.0, -0.05, True, 2.0, +2.0, 0.6), # momentum up, theme +, but combined negative
|
||||
self._cand("POS_B", 10.0, 0.20, True, 2.0, +1.5, 0.6), # combined positive
|
||||
]
|
||||
res = allocate_capital(1_000_000, cands)
|
||||
b1 = [o.symbol for o in res.orders if o.bucket == 1]
|
||||
self.assertNotIn("NEG_A", b1) # combined negative -> excluded
|
||||
self.assertIn("POS_B", b1)
|
||||
|
||||
|
||||
class PriceSnapshotTest(unittest.TestCase):
|
||||
"""Regression: load_price_snapshot must pick the snapshot retrieved MOST
|
||||
RECENTLY, not the last filename lexicographically (a partial 9-symbol file
|
||||
can sort after a full 50-symbol one and silently drop the universe)."""
|
||||
|
||||
def test_load_picks_most_recently_retrieved(self):
|
||||
import json, tempfile
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
from app import simulation as sim
|
||||
|
||||
def _snap(symbols, retrieved_at):
|
||||
return {
|
||||
"schema_version": 1,
|
||||
"source": {"retrieved_at": retrieved_at, "period_start": "2024-01-01", "period_end": "2026-08-29"},
|
||||
"series": {s: {"bars": [{"date": "2026-08-29", "adjusted_close": 10.0}]} for s in symbols},
|
||||
}
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
snap_dir = Path(td) / "snapshots"
|
||||
snap_dir.mkdir()
|
||||
# name that sorts LAST lexicographically, but is OLD (partial 9)
|
||||
old_partial = snap_dir / "prices-yahoo-chart-2024-01-01-2026-08-24-zzz.json"
|
||||
old_partial.write_text(json.dumps(_snap(["A", "B"], "2026-08-23T00:00:00+00:00")))
|
||||
# full 50-symbol, retrieved MORE recently — should win
|
||||
full = snap_dir / "prices-yahoo-chart-2023-08-28-2026-08-29-aaa.json"
|
||||
full.write_text(json.dumps(_snap([f"S{i}" for i in range(50)], "2026-08-30T00:00:00+00:00")))
|
||||
with mock.patch.object(sim, "_PRICES_DIR", Path(td)):
|
||||
series = sim.load_price_snapshot()
|
||||
self.assertEqual(len(series), 50) # the full universe, not the 9
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Tests for the Thailand rates/credit/retail/confidence collector + themes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from app import te_thailand, themes
|
||||
from app.te_thailand import ThaiFactorsSnapshot, parse_te_thailand_html
|
||||
|
||||
|
||||
def _row(label, value, prev, unit, period):
|
||||
return (f"<tr><td>{label}</td><td>{value}</td><td>{prev}</td>"
|
||||
f"<td>{unit}</td><td>{period}</td></tr>")
|
||||
|
||||
|
||||
def _table(*rows):
|
||||
return f"<table>{''.join(rows)}</table>"
|
||||
|
||||
|
||||
_IR_HTML = _table(
|
||||
_row("Interest Rate", "1.00", "1.00", "percent", "Aug 2026"),
|
||||
_row("Loans to Non Financial Corporations", "10553097.00", "10488479.00", "THB Million", "Jun 2026"),
|
||||
_row("Banks Balance Sheet", "40475793.00", "40559803.00", "THB Million", "Jun 2026"),
|
||||
)
|
||||
_CC_HTML = _table(
|
||||
_row("Consumer Confidence", "51.80", "50.70", "points", "Jul 2026"),
|
||||
_row("Retail Sales YoY", "-14.50", "-20.00", "percent", "May 2026"),
|
||||
_row("Consumer Credit", "5285734.00", "5296795.00", "THB Million", "Jun 2025"),
|
||||
_row("Households Debt to GDP", "87.50", "87.30", "percent of GDP", "Dec 2025"),
|
||||
_row("Consumer Spending", "1771591.00", "1730973.00", "THB Million", "Jun 2026"),
|
||||
)
|
||||
_HOUSING_HTML = _table(
|
||||
_row("Housing Index", "162.70", "162.40", "points", "Jun 2026"),
|
||||
_row("Residential Property Prices", "1.26", "0.63", "Percent", "Mar 2026"),
|
||||
_row("Housing Starts", "4093.00", "6520.00", "units", "Apr 2026"),
|
||||
)
|
||||
_BIZCONF_HTML = _table(
|
||||
_row("Business Confidence", "46.70", "46.10", "points", "Jul 2026"),
|
||||
_row("Leading Economic Index", "166.19", "163.56", "points", "Jun 2026"),
|
||||
)
|
||||
|
||||
|
||||
class TeThailandParseTest(unittest.TestCase):
|
||||
def test_parses_all_indicators(self):
|
||||
snap = parse_te_thailand_html(_IR_HTML, _CC_HTML, _HOUSING_HTML, _BIZCONF_HTML)
|
||||
self.assertIsInstance(snap, ThaiFactorsSnapshot)
|
||||
self.assertEqual(snap.interest_rate_pct, 1.0)
|
||||
self.assertEqual(snap.loans_to_fin_corp, 10553097.0)
|
||||
self.assertEqual(snap.consumer_credit_thbmn, 5285734.0)
|
||||
self.assertEqual(snap.household_debt_gdp_pct, 87.5)
|
||||
self.assertEqual(snap.retail_sales_yoy, -14.5)
|
||||
self.assertEqual(snap.consumer_confidence, 51.8)
|
||||
self.assertEqual(snap.consumer_spending, 1771591.0)
|
||||
self.assertEqual(snap.property_prices_yoy, 1.26)
|
||||
self.assertEqual(snap.business_confidence, 46.7)
|
||||
self.assertEqual(snap.periods["interest_rate_pct"], "Aug 2026")
|
||||
self.assertEqual(snap.periods["property_prices_yoy"], "Mar 2026")
|
||||
|
||||
def test_to_dict_full(self):
|
||||
d = parse_te_thailand_html(_IR_HTML, _CC_HTML, _HOUSING_HTML, _BIZCONF_HTML).to_dict()
|
||||
self.assertIn("interest_rate_pct", d)
|
||||
self.assertIn("retail_sales_yoy", d)
|
||||
self.assertIn("property_prices_yoy", d)
|
||||
self.assertIn("business_confidence", d)
|
||||
self.assertIn("source", d)
|
||||
|
||||
def test_missing_values_raise(self):
|
||||
# neither page yields a usable series -> collector fails loudly
|
||||
empty = "<table><tr><td>x</td><td>1</td></tr></table>"
|
||||
with self.assertRaises(te_thailand.ThaiFactorsError):
|
||||
parse_te_thailand_html(empty, empty)
|
||||
|
||||
def test_every_factor_value_key_resolves(self):
|
||||
from app import factors
|
||||
keys = set(ThaiFactorsSnapshot().to_dict().keys())
|
||||
for fkey, fact in factors.FACTORS.items():
|
||||
if fact.get("fetch") != "te_thailand":
|
||||
continue
|
||||
self.assertIn(
|
||||
fact.get("value_key"), keys,
|
||||
f"factor {fkey!r} value_key not emitted by te_thailand",
|
||||
)
|
||||
|
||||
|
||||
class TeThailandThemeDirectionTest(unittest.TestCase):
|
||||
"""New factors must move theme surprises the intended direction (sign fix)."""
|
||||
|
||||
@staticmethod
|
||||
def _fetched():
|
||||
base = {
|
||||
"macro_thai": {
|
||||
"private_consumption_yoy": 4.9, "private_investment_yoy": 18.1,
|
||||
"headline_inflation_yoy": 1.95, "core_inflation_yoy": 1.0,
|
||||
"unemployment_pct": 1.0, "manufacturing_yoy": -3.1,
|
||||
"tourists_ytd_mn": 16.2,
|
||||
},
|
||||
"auto_credit": {"new_car_sales_yoy": 20.07, "vehicle_production": 117383.0,
|
||||
"auto_exports": 81526.0},
|
||||
"auto_npl": {"pct_of_npls": 3.0},
|
||||
"bank_npl": {"pct_of_npls": 1.0},
|
||||
"energy_thai": {"quarterly": {"Q1/2026": {"net_profit": 19481.0, "sales": 114809.0}}},
|
||||
"thai_trade": {"current_account_usdm": 500.0, "exports_usdm": 34000.0,
|
||||
"imports_usdm": 38000.0},
|
||||
# te_thailand factors — neutral-ish values
|
||||
"te_thailand": {
|
||||
"interest_rate_pct": 1.5,
|
||||
"loans_to_fin_corp": 10000000.0,
|
||||
"consumer_credit_thbmn": 5000000.0,
|
||||
"household_debt_gdp_pct": 85.0,
|
||||
"retail_sales_yoy": 0.0,
|
||||
"consumer_confidence": 50.0,
|
||||
"property_prices_yoy": 0.0,
|
||||
"business_confidence": 50.0,
|
||||
},
|
||||
}
|
||||
return base
|
||||
|
||||
def _surprises(self, te):
|
||||
d = self._fetched()
|
||||
d["te_thailand"] = te
|
||||
return themes.compute_theme_surprises(d)
|
||||
|
||||
def test_higher_retail_sales_raises_retail(self):
|
||||
low = self._surprises({**self._fetched()["te_thailand"], "retail_sales_yoy": -15.0})
|
||||
high = self._surprises({**self._fetched()["te_thailand"], "retail_sales_yoy": 8.0})
|
||||
self.assertGreater(high["retail"], low["retail"])
|
||||
|
||||
def test_higher_rate_and_loans_raise_banks(self):
|
||||
low = self._surprises({**self._fetched()["te_thailand"], "interest_rate_pct": 0.5,
|
||||
"loans_to_fin_corp": 8500000.0})
|
||||
high = self._surprises({**self._fetched()["te_thailand"], "interest_rate_pct": 2.5,
|
||||
"loans_to_fin_corp": 12000000.0})
|
||||
self.assertGreater(high["banks"], low["banks"])
|
||||
|
||||
def test_higher_household_debt_lowers_nonbank(self):
|
||||
low = self._surprises({**self._fetched()["te_thailand"], "household_debt_gdp_pct": 80.0})
|
||||
high = self._surprises({**self._fetched()["te_thailand"], "household_debt_gdp_pct": 92.0})
|
||||
self.assertLess(high["nonbank_finance"], low["nonbank_finance"])
|
||||
|
||||
def test_higher_consumer_confidence_raises_retail(self):
|
||||
low = self._surprises({**self._fetched()["te_thailand"], "consumer_confidence": 42.0})
|
||||
high = self._surprises({**self._fetched()["te_thailand"], "consumer_confidence": 60.0})
|
||||
self.assertGreater(high["retail"], low["retail"])
|
||||
|
||||
def test_higher_property_prices_raise_property(self):
|
||||
low = self._surprises({**self._fetched()["te_thailand"], "property_prices_yoy": -4.0})
|
||||
high = self._surprises({**self._fetched()["te_thailand"], "property_prices_yoy": 4.0})
|
||||
self.assertGreater(high["property"], low["property"])
|
||||
|
||||
def test_higher_business_confidence_raises_telecom(self):
|
||||
low = self._surprises({**self._fetched()["te_thailand"], "business_confidence": 42.0})
|
||||
high = self._surprises({**self._fetched()["te_thailand"], "business_confidence": 58.0})
|
||||
self.assertGreater(high["telecom_it"], low["telecom_it"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
import unittest
|
||||
|
||||
from app import themes
|
||||
from app import auto_credit, auto_npl, bank_npl, energy_irpc, macro_thai, te_thailand, thai_trade
|
||||
|
||||
|
||||
class ThemesTest(unittest.TestCase):
|
||||
@@ -28,6 +29,27 @@ class ThemesTest(unittest.TestCase):
|
||||
# X = 10 + 2*2 = 14 ; Y = -5 -> X higher
|
||||
self.assertGreater(sc["X"], sc["Y"])
|
||||
|
||||
def test_siamchart_raw_score_has_momentum_inside_formula(self) -> None:
|
||||
# Momentum is a first-class factor WITHIN the formula (owner rule):
|
||||
# raw = eps_growth*1.5 + dividend_yield*2.0 + momentum*0.5.
|
||||
self.assertEqual(
|
||||
round(themes.siamchart_raw_score(4.0, 1.0, 2.0), 6),
|
||||
round(4.0 * 1.5 + 1.0 * 2.0 + 2.0 * 0.5, 6), # 6 + 2 + 1 = 9
|
||||
)
|
||||
self.assertEqual(themes._SIAMCHART_WEIGHTS["momentum"], 0.5)
|
||||
|
||||
def test_siamchart_momentum_raises_score(self) -> None:
|
||||
factors = {
|
||||
"factors": [
|
||||
{"symbol": "UP", "eps_growth_yoy": 0.0, "dividend_yield": 0.0},
|
||||
{"symbol": "DN", "eps_growth_yoy": 0.0, "dividend_yield": 0.0},
|
||||
]
|
||||
}
|
||||
momentum = {"UP": 1.0, "DN": -1.0}
|
||||
sc = themes.build_siamchart_score(factors, momentum=momentum)
|
||||
# Same fundamentals, only momentum differs -> UP must win.
|
||||
self.assertGreater(sc["UP"], sc["DN"])
|
||||
|
||||
def test_combine_60_40(self) -> None:
|
||||
theme_scores = [{"A": 1.0, "B": -1.0}]
|
||||
siamchart = {"A": 2.0, "B": 0.0}
|
||||
@@ -144,12 +166,12 @@ class RegistryDrivenSurpriseTest(unittest.TestCase):
|
||||
from app import themes
|
||||
s = themes.compute_theme_surprises(self._fetched())
|
||||
# registry retail = weighted average over |weights| of
|
||||
# consumption*1.0 + inflation*(-0.3):
|
||||
# consumption*1.0 + inflation*0.3 (sign -1 intrinsic in the factor):
|
||||
# cons=4.9 -> (4.9-3)/10=0.19 (w=1.0) ; inflation sign -1 ->
|
||||
# -(1.95-2)/10=+0.005 (w=-0.3) -> weighted = 0.19 - 0.0015 = 0.1885
|
||||
# surprise = 0.1885 / (1.0 + 0.3) = 0.145
|
||||
# -(1.95-2)/10=+0.005 (w=+0.3) -> weighted = 0.19 + 0.0015 = 0.1915
|
||||
# surprise = 0.1915 / (1.0 + 0.3) = 0.147
|
||||
self.assertIsNotNone(s["retail"])
|
||||
self.assertAlmostEqual(s["retail"], 0.145, places=3)
|
||||
self.assertAlmostEqual(s["retail"], 0.147, places=3)
|
||||
|
||||
def test_changing_factor_weight_changes_output(self):
|
||||
"""The defining property of P0-B: the registry is not decorative."""
|
||||
@@ -183,3 +205,127 @@ class RegistryDrivenSurpriseTest(unittest.TestCase):
|
||||
self.assertIsNone(factors.normalize(None))
|
||||
# finite value still normalizes
|
||||
self.assertEqual(factors.normalize(15.0, sign=1, center=5.0, span=10.0), 1.0)
|
||||
|
||||
def test_new_macro_factors_actually_move_scores(self):
|
||||
"""Wire-in proof (user rule: a fetched field must feed analysis).
|
||||
|
||||
core_inflation + unemployment were fetched by BOT macro_thai but not
|
||||
used. Once present with a non-neutral value they must change the
|
||||
retail/banks surprise vs a neutral value — i.e. they are not dead data.
|
||||
"""
|
||||
from app import themes
|
||||
neutral = {
|
||||
"core_inflation_yoy": 1.0, # == center(1.0) -> 0 normalised
|
||||
"unemployment_pct": 1.0, # == center(1.0) -> 0 normalised
|
||||
}
|
||||
base_fetched = self._fetched()
|
||||
base_fetched["macro_thai"].update(neutral)
|
||||
s_neutral = themes.compute_theme_surprises(
|
||||
{k: dict(v) for k, v in base_fetched.items()})
|
||||
|
||||
hot = dict(base_fetched)
|
||||
hot["macro_thai"]["unemployment_pct"] = 3.0 # above center -> bearish
|
||||
s_hot = themes.compute_theme_surprises({k: dict(v) for k, v in hot.items()})
|
||||
# higher unemployment is bearish (sign -1, +ve weight) -> retail/healthcare lower
|
||||
self.assertLess(s_hot["retail"], s_neutral["retail"])
|
||||
self.assertLess(s_hot["healthcare"], s_neutral["healthcare"])
|
||||
|
||||
hot_infl = dict(base_fetched)
|
||||
hot_infl["macro_thai"]["core_inflation_yoy"] = 3.5 # above center -> bearish
|
||||
s_infl = themes.compute_theme_surprises({k: dict(v) for k, v in hot_infl.items()})
|
||||
self.assertLess(s_infl["banks"], s_neutral["banks"])
|
||||
|
||||
def test_bearish_factors_move_score_the_right_way(self):
|
||||
"""Regression for the sign-inversion bug.
|
||||
|
||||
Factor `sign` is applied once inside normalize() so a *positive* theme
|
||||
weight means "more of this factor matters". Bearish factors (NPL,
|
||||
inflation, unemployment) all carry sign -1; a negative theme weight made
|
||||
the double product turn positive — i.e. higher NPL/inflation RAISED the
|
||||
theme score. Lock the correct direction: higher NPL must LOWER
|
||||
auto_credit/banks; lower NPL must RAISE them.
|
||||
"""
|
||||
from app import themes
|
||||
base = self._fetched()
|
||||
# base has auto_npl pct 3.95, bank_npl NOT present (only via macro) -> use
|
||||
# a full fetched incl. bank_npl so the factor is exercised.
|
||||
base["bank_npl"] = {"pct_of_npls": 1.0}
|
||||
low = themes.compute_theme_surprises({k: dict(v) for k, v in base.items()})
|
||||
|
||||
hi = dict(base)
|
||||
hi["auto_npl"] = {"pct_of_npls": 8.0} # much worse credit quality
|
||||
hi["bank_npl"] = {"pct_of_npls": 5.0}
|
||||
s_hi = themes.compute_theme_surprises({k: dict(v) for k, v in hi.items()})
|
||||
# higher NPL -> lower surprise in the credit-heavy themes (bearish)
|
||||
self.assertLess(s_hi["auto_credit"], low["auto_credit"])
|
||||
self.assertLess(s_hi["banks"], low["banks"])
|
||||
|
||||
def test_every_factor_value_key_resolves_to_a_fetched_field(self):
|
||||
"""Contract (user rule): every FACTORS.value_key must be a real field the
|
||||
registered fetch module emits. A factor that reads a key the collector
|
||||
never produces is dead weight — catches 'fetched but not used' the other
|
||||
way (a value_key that can never be populated)."""
|
||||
from app import factors
|
||||
for fkey, fact in factors.FACTORS.items():
|
||||
fetch_mod = fact.get("fetch")
|
||||
value_key = fact.get("value_key")
|
||||
if value_key is None:
|
||||
continue
|
||||
# energy_thai derives its value from a nested quarterly dict, not a
|
||||
# top-level key — covered separately by factor_value().
|
||||
if fetch_mod == "energy_thai":
|
||||
continue
|
||||
if fetch_mod == "energy_irpc":
|
||||
keys = set(energy_irpc.EnergyIrpcSnapshot().to_dict().keys())
|
||||
# resolve the module's snapshot .to_dict() keys
|
||||
if fetch_mod == "macro_thai":
|
||||
keys = set(macro_thai.MacroThaiSnapshot().to_dict().keys())
|
||||
elif fetch_mod == "auto_credit":
|
||||
keys = set(auto_credit.AutoCreditSnapshot().to_dict().keys())
|
||||
elif fetch_mod == "auto_npl":
|
||||
keys = set(auto_npl.AutoNplSnapshot().to_dict().keys())
|
||||
elif fetch_mod == "bank_npl":
|
||||
keys = set(bank_npl.BankNplSnapshot().to_dict().keys())
|
||||
elif fetch_mod == "thai_trade":
|
||||
keys = set(thai_trade.ThaiTradeSnapshot().to_dict().keys())
|
||||
elif fetch_mod == "te_thailand":
|
||||
keys = set(te_thailand.ThaiFactorsSnapshot().to_dict().keys())
|
||||
else:
|
||||
continue
|
||||
self.assertIn(
|
||||
value_key, keys,
|
||||
f"factor {fkey!r} targets value_key {value_key!r} that fetch "
|
||||
f"module {fetch_mod!r} never emits -> dead factor",
|
||||
)
|
||||
|
||||
def test_factor_source_breakdown_shows_per_source_contribution(self):
|
||||
"""Audit trail: each factor shows source/raw/normalized/weight/contribution
|
||||
so the owner can see exactly how every source scored and weight applied."""
|
||||
from app import themes
|
||||
fetched = {
|
||||
"macro_thai": {
|
||||
"private_consumption_yoy": 4.9, "headline_inflation_yoy": 1.95,
|
||||
"manufacturing_yoy": -3.1, "private_investment_yoy": 18.1,
|
||||
"core_inflation_yoy": 1.0, "unemployment_pct": 1.0,
|
||||
"tourists_ytd_mn": 16.2,
|
||||
},
|
||||
"te_thailand": {
|
||||
"retail_sales_yoy": -5.0, "consumer_confidence": 50.0,
|
||||
"interest_rate_pct": 1.5, "loans_to_fin_corp": 10000000.0,
|
||||
},
|
||||
"thai_trade": {"imports_usdm": 38000.0, "current_account_usdm": 500.0},
|
||||
}
|
||||
rows = themes.factor_source_breakdown(fetched, "retail")
|
||||
# retail includes te_thailand retail_sales_yoy (drives the negative read)
|
||||
te_retail = next(r for r in rows if r["factor"] == "te_retail_sales_yoy")
|
||||
self.assertEqual(te_retail["source"], "te_thailand")
|
||||
self.assertEqual(te_retail["raw"], -5.0)
|
||||
self.assertEqual(te_retail["normalized"], -0.5) # (-5-0)/10
|
||||
self.assertEqual(te_retail["weight"], 0.7)
|
||||
self.assertAlmostEqual(te_retail["contribution"], -0.35, places=4)
|
||||
self.assertFalse(te_retail["missing"])
|
||||
# every row carries the audit fields
|
||||
for r in rows:
|
||||
self.assertIn("source", r)
|
||||
self.assertIn("weight", r)
|
||||
self.assertIn("contribution", r)
|
||||
@@ -5,11 +5,12 @@ import tempfile
|
||||
import unittest
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
from app.bot_tourism import BotTourismSource
|
||||
from app.collector import collect_bot_vintage
|
||||
from app.vintages import VintageStore, filter_vintages
|
||||
from app.vintages import VintageStore, VintageStoreError, filter_vintages
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
REPORT_HTML = (FIXTURES / "bot_tourism_report.html").read_text(encoding="utf-8")
|
||||
@@ -128,6 +129,50 @@ class VintageStoreTests(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValueError, "hash"):
|
||||
store.load_snapshot(snapshot["source"]["vintage_id"])
|
||||
|
||||
def test_snapshot_load_rejects_non_object_json(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = VintageStore(root)
|
||||
snapshot = sample_snapshot()
|
||||
store.persist(REPORT_HTML.encode("utf-8"), snapshot)
|
||||
snapshot_path = root / "snapshots" / f"{snapshot['source']['vintage_id']}.json"
|
||||
snapshot_path.write_text(json.dumps(["not", "a", "snapshot"]), encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(VintageStoreError, "invalid"):
|
||||
store.load_snapshot(snapshot["source"]["vintage_id"])
|
||||
|
||||
def test_snapshot_load_rejects_unreadable_utf8(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = VintageStore(root)
|
||||
snapshot = sample_snapshot()
|
||||
store.persist(REPORT_HTML.encode("utf-8"), snapshot)
|
||||
snapshot_path = root / "snapshots" / f"{snapshot['source']['vintage_id']}.json"
|
||||
snapshot_path.write_bytes(b"\xff")
|
||||
|
||||
with self.assertRaisesRegex(VintageStoreError, "unreadable"):
|
||||
store.load_snapshot(snapshot["source"]["vintage_id"])
|
||||
|
||||
def test_snapshot_load_rejects_unreadable_raw_payload(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = VintageStore(root)
|
||||
snapshot = sample_snapshot()
|
||||
store.persist(REPORT_HTML.encode("utf-8"), snapshot)
|
||||
|
||||
with patch("pathlib.Path.read_bytes", side_effect=OSError("read failed")):
|
||||
with self.assertRaisesRegex(VintageStoreError, "unreadable"):
|
||||
store.load_snapshot(snapshot["source"]["vintage_id"])
|
||||
|
||||
def test_manifest_load_rejects_unreadable_utf8(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
store = VintageStore(root)
|
||||
(root / "manifest.json").write_bytes(b"\xff")
|
||||
|
||||
with self.assertRaisesRegex(VintageStoreError, "unreadable"):
|
||||
store.load_manifest()
|
||||
|
||||
def test_collector_returns_manifested_snapshot_summary(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
result = collect_bot_vintage(
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env sh
|
||||
set -e
|
||||
|
||||
# Start the Flask backend on 0.0.0.0:5000 (bind all interfaces so nginx can
|
||||
# proxy to it inside the container). DATA_DIR is /app/backend/data by default
|
||||
# (a mounted volume makes it survive container recreate).
|
||||
#
|
||||
# NOTE: nginx owns port 80 (the inbound entrypoint EasyPanel exposes). We
|
||||
# therefore pin Flask to 5000 explicitly and IGNORE the PORT env var — EasyPanel
|
||||
# injects PORT=80, and if Flask also took 80 it would clash with nginx
|
||||
# ("Address already in use"). nginx proxies /api -> 127.0.0.1:5000.
|
||||
cd /app/backend
|
||||
export HOST="${HOST:-0.0.0.0}"
|
||||
export PORT="5000"
|
||||
export PAPER_BIND_HOST="$HOST"
|
||||
|
||||
# pid1 helper: run nginx in foreground + Flask subprocess so the container
|
||||
# stays alive and signals are handled. Keep it simple and robust.
|
||||
|
||||
# Start Flask in the background
|
||||
python run.py &
|
||||
FLASK_PID=$!
|
||||
|
||||
# Start nginx in the foreground (its own master + workers)
|
||||
nginx -g "daemon off;" &
|
||||
NGINX_PID=$!
|
||||
|
||||
# forward signals to both and wait
|
||||
trap 'kill $FLASK_PID $NGINX_PID 2>/dev/null || true' INT TERM
|
||||
wait $FLASK_PID
|
||||
wait $NGINX_PID
|
||||
@@ -0,0 +1,29 @@
|
||||
# nginx: serve the built Vue SPA + reverse-proxy /api to the Flask backend.
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
|
||||
root /app/frontend/dist;
|
||||
index index.html;
|
||||
|
||||
# SPA fallback: any non-API GET that isn't a real file -> index.html
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
# API traffic goes to the Flask backend on 127.0.0.1:5000
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:5000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_read_timeout 120s;
|
||||
}
|
||||
|
||||
# never serve dotfiles
|
||||
location ~ /\. { deny all; }
|
||||
|
||||
gzip on;
|
||||
gzip_types text/css application/javascript application/json;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
# Local/self-hosted single-container run for the SET50 alternative-data platform.
|
||||
# Production (EasyPanel) builds from the Dockerfile directly; this compose file
|
||||
# adds a persistent volume so factor vintages, the dividend ledger, forward runs
|
||||
# and prices survive container recreate.
|
||||
services:
|
||||
set50:
|
||||
build: .
|
||||
image: set50-alternative-data:latest
|
||||
ports:
|
||||
- "8080:80"
|
||||
environment:
|
||||
# bind backend on all interfaces inside the container (nginx proxies /api)
|
||||
HOST: "0.0.0.0"
|
||||
PORT: "5000"
|
||||
PAPER_BIND_HOST: "0.0.0.0"
|
||||
# optional: make the dividend refresh faster for demos ()
|
||||
# DIVIDEND_REFRESH_COOLDOWN_SECONDS: "300"
|
||||
volumes:
|
||||
- ./backend/data:/app/backend/data
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1/api/v1/dashboard/summary', timeout=4).status==200 else 1)"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
@@ -157,6 +157,49 @@ NEVER include API keys, tokens, passwords, secrets, credentials, or connection s
|
||||
|
||||
---
|
||||
|
||||
## Session 2026-08-28 — Event-driven PIT backtest (verified + pushed)
|
||||
|
||||
**Branch:** `main` · **HEAD:** `d73a58b` (+cycle-2 fix pending) · **Pushed:** yes (tasks 1–7)
|
||||
|
||||
### Goal implemented
|
||||
Replace the calendar-rebalance backtest with a strict point-in-time, event-driven
|
||||
engine per the user's description. Confirmed decisions:
|
||||
1. **Strict PIT** — block when factor / Siamchart / price coverage is incomplete (no fallback).
|
||||
2. **Execution** — freeze signal at release date D, execute at next trading-day close after D.
|
||||
3. **Dividend timing** — entitled on ex-date; cash available `ex_date + 30` days (`ex_date_plus_30d`).
|
||||
4. **Average cost** — realized P&L uses weighted avg cost.
|
||||
5. **Fee** — all-in 0.3% per trade, no added VAT.
|
||||
|
||||
### Shipped (commits on main)
|
||||
- `68f2cc1` Task 1 `backtest_readiness.py` — readiness + recommended start/end defaults, fail-closed.
|
||||
- `6439e9c` Task 2 `backtest_events.py` — event calendar + next-trading-day mapping.
|
||||
- `dc057e9` Task 3 `portfolio_ledger.py` — cash/positions/avg-cost/realized+unrealized P&L/dividend receivables/fees.
|
||||
- `71b893e` Task 4 `portfolio_rebalancer.py` — 50/20/30 → 100-lot executable orders, sells-first, no trade on unchanged target.
|
||||
- `6459015` Task 5 `backtest_engine.py` — event processor; refuses live-board fallback without a PIT scorer.
|
||||
- `c87767c` Task 6 `backtest_store.py` + strict `POST /api/v1/backtest/run` (readiness-gated) + `GET /api/v1/backtest/run(+<id>)`.
|
||||
- `d73a58b` Task 7 frontend — readiness gate disables Run + shows missing coverage; detailed report.
|
||||
|
||||
### Verification
|
||||
- Standalone offline suite **54 tests** (readiness 10, events 14, ledger 15, rebalancer 5, engine 6, store 4). compileall + diff-check clean.
|
||||
- Static scan: no secrets/eval/debug (4 "secret" regex hits are the prose "missing token" string).
|
||||
- Live readiness on real data: `ready=false`, missing factor+siamchart, recommended_end=2026-08-27.
|
||||
- Live strict run on real data (no vintages): `POST /api/v1/backtest/run` → **400** + missing list (fail-closed).
|
||||
- Happy-path `scripts/probe_event_backtest.py` (synthetic PIT-complete): accounting_reconciled=True, identity lhs=rhs, leakage_guard=True, 100-lot holdings.
|
||||
- Independent reviews: cycle-1 `deleg_5225e9de` flagged 3 logic errors → fixed (engine fails closed without PIT scorer; readiness blocks explicit start before price history; coincident-day ex-date entitlement fixed by per-day ordering). Cycle-2 `deleg_b969075c` re-verified the fallback fix + 9/10 invariants, re-confirmed the invariant-4 breach. Cycle-3 `deleg_7f56df3b` confirmed the ordering fix. Cycle-4 `deleg_55f4e877` final review returned **passed=true**, empty logic_errors/security_concerns (suggestion: per-symbol price coverage at the exact intersection start — deferred edge case).
|
||||
- Evidence: `docs/test-evidence/2026-08-28-event-driven-backtest.md`.
|
||||
|
||||
### Honest scope / limitations
|
||||
- Current on-disk data has **no factor vintages / Siamchart manifest** → strict event backtest is blocked on real data until collection accumulates (this is the intended fail-closed behavior, matching "strict PIT or block").
|
||||
- **Auto-collection is now live** (commit `1fb1e1a`): the scheduler writes PIT factor + Siamchart vintages every refresh on whichever machine the app runs, so strict runs become ready once enough data is knowable. Because `released_at=retrieved_at=now`, `ready=true` currently requires an explicit `end=today` window (auto end=yesterday stays blocked until real history accumulates — honest, no assumed reporting lag).
|
||||
- **Per-source cadence + source health** (commit `14b2aef`): slow factors refresh monthly/quarterly (cooldown markers), prices + Siamchart daily; every refresh logs per-source outcome to `data/scheduler/source_health.json`, auto-classified (network/timeout/http/parse/structure/auth), shown in the "สถานะข้อมูล" panel with one-click copy of the cause.
|
||||
- Dividend payment timing is the confirmed `ex_date + 30d` **assumption** (Siamchart gives ex-date+DPS, not pay date); every result exposes `dividend_timing=ex_date_plus_30d`.
|
||||
- Only the new `/api/v1/backtest/run` route is event-driven/strict; the legacy `POST /api/v1/backtest` remains as the descriptive non-PIT path.
|
||||
|
||||
## Exact next action
|
||||
Collect factor vintages + Siamchart snapshots over time (scheduler already seeds Siamchart baseline) until `/api/v1/backtest/readiness` reports `ready=true`, then run a real strict event backtest. Frontend already wires readiness → recommended dates.
|
||||
|
||||
---
|
||||
|
||||
## Session 2026-08-27 — Backtest Accounting Remediation
|
||||
|
||||
**Branch:** `main` · **Base HEAD:** `b362cc3` · **Commit/push:** not performed
|
||||
@@ -193,6 +236,49 @@ Implement dated dividend events and a provenance-validated PIT score provider be
|
||||
|
||||
---
|
||||
|
||||
## Session 2026-08-27 — Single-container Docker packaging (verified + pushed)
|
||||
|
||||
**Branch:** main · **HEAD:** f9b8cd1 (pushed)
|
||||
|
||||
### Completed this session (verified + pushed)
|
||||
- **Dockerfile**: `python:3.11-slim` + nginx. Serves the PREBUILT `frontend/dist` SPA (committed bundle, no node/npm in the image), reverse-proxies `/api` → `127.0.0.1:5000`, `VOLUME [/app/backend/data]` for persistence (factor vintages, dividend ledger, forward runs, prices), HEALTHCHECK on `/api/v1/dashboard/summary`, exposes :80.
|
||||
- **deploy/nginx.conf**: SPA fallback + `/api` proxy + gzip.
|
||||
- **deploy/entrypoint.sh**: starts Flask (`HOST=0.0.0.0:5000`) + nginx in foreground, forwards INT/TERM.
|
||||
- **docker-compose.yml**: service `set50`, port `8080:80`, volume `./backend/data`, healthcheck.
|
||||
- **.dockerignore** (excludes .git/.venv/backend/data/node_modules/docs) + **.gitignore** now tracks `frontend/dist/` (prebuilt bundle); `backend/data/` stays untracked.
|
||||
|
||||
### Verified
|
||||
- Backend runtime: `test_client GET /api/v1/dashboard/summary` → 200 (the HEALTHCHECK path).
|
||||
- `sh -n deploy/entrypoint.sh`, compose YAML parses, all Dockerfile-referenced files exist on remote `origin/main`.
|
||||
|
||||
### Honest caveat
|
||||
- **No local docker on this machine** → the image itself was NOT built/run here. The first real build happens on EasyPanel (or any docker host). If the build fails there, the most likely causes are env-var / volume mapping, which the compose file already covers for self-host.
|
||||
|
||||
### Exact next action (user-side)
|
||||
1. On EasyPanel create a service from this repo (build type **Dockerfile** — not Nixpacks).
|
||||
2. Mount a **persistent volume** at `/app/backend/data` (or set `DATA_DIR` env to a mounted path) so the dividend ledger / factor vintages / forward runs survive redeploys.
|
||||
3. Publish port **80** (default). Add a webhook in Gitea → EasyPanel deploy URL on push to `main` (Gitea Webhook, not Gitea Actions — no managed runners).
|
||||
4. Optional: set `DIVIDEND_REFRESH_COOLDOWN_SECONDS` / `REFRESH_INTERVAL_SECONDS`.
|
||||
|
||||
---
|
||||
|
||||
## Session 2026-08-27 — Auto-refresh dated dividend ledger (verified + pushed)
|
||||
|
||||
**Branch:** main · **HEAD:** 03195dc (pushed)
|
||||
|
||||
### Completed this session (verified + pushed)
|
||||
- `AppDataScheduler` now calls `_maybe_refresh_dated_dividends()` in `refresh_all` — a cooldown-gated (default 6h) fetch of real dated dividend history into `data/dividends/ledger.json`, so the ledger stays fresh automatically without manual `POST /api/v1/dividends/update` and without re-hammering Siamchart every refresh tick (dividend history changes only a few times a year).
|
||||
- `DIVIDEND_REFRESH_COOLDOWN_SECONDS` env toggle (default 21600). Network failure is non-fatal: the previous ledger stays intact.
|
||||
- **Tests**: cooldown fires once then skips, refetches after it elapses (2) — full backend **294 passed** (was 292).
|
||||
|
||||
### Verified
|
||||
- Backend **294 passed**; compileall, `git diff --check`, static scan clean.
|
||||
|
||||
### Exact next action
|
||||
None required — the SET50 alternative-data platform PIT/enabler work is complete. Optional UI-only polish: surface the dated-ledger synthesis (dated vs proxy) more explicitly in the backtest result card. Do not reset or stage unrelated pre-existing working-tree changes.
|
||||
|
||||
---
|
||||
|
||||
## Session 2026-08-27 — Real dated dividend-history collector (verified + pushed)
|
||||
|
||||
**Branch:** main · **HEAD:** f9973e8 (pushed `59c97b5..f9973e8`)
|
||||
|
||||
@@ -104,3 +104,6 @@
|
||||
- Real forward-test lifecycle (2026-08-27, commits `6d9c283` + `80c6d79`): the cosmetic "forward" (same single-pass backtest, different mode string) is replaced with a durable, frozen-signal paper-portfolio lifecycle. `forward_test.py` `ForwardTestStore` (thread-safe JSON store) with status flow: frozen (signals snapshotted immutable) → executed (fills 50/20/30 at post-freeze prices) → marked (mark-to-market equity series) → matured (net_return). New routes: `GET /api/v1/forward(+<id>)`, `POST /api/v1/forward` (create+execute, `use_pit` freeze), `POST /<id>/mark`, `POST /<id>/mature`; store at `data/forward/runs.json` (survives restarts). UI simulation tab: forward calls `/api/v1/forward`, loads runs, shows status/non-PIT/holdings + Mark/Mature per run. Full backend **280 passed** (was 273). Honest scope: score source at CREATE may be current board (`non_pit=true` tagged); paper-only.
|
||||
- Factor-learning validation gate (2026-08-27, commit `ae814c3`): closed the P4 "no auto-apply" loop — `weight_learning.py` now splits a chronological IC series into train + holdout via `apply_validation_gate`, and a factor is `validated=True` only when total sample >= 12, each window >= its min, train & holdout IC both beat baseline (BASELINE_IC=0) and agree in sign, and pooled |t| > 1.0. `apply_weight_update` keeps the weight unchanged for any unvalidated factor (no auto-apply); only validated factors move. `learn_momentum_gated` wired into `/api/v1/learning/momentum`, surfacing `ic_train`/`ic_holdout`/`validated`/`gate_notes`. Full backend **286 passed** (was 280). Live probe: momentum validated=false, gate_note "IC not above baseline (0.0711/-0.1143)" — weight unchanged.
|
||||
- Real dated dividend-history collector (2026-08-27, commit `f9973e8`): `siamchart.py` gained `parse_dividend_history`/`fetch_dividend_history` (reads the "ประวัติการปันผล" ex-date + DPS table per stock-info page); `dividend_ledger.py` gained `populate_dated_dividends` (registers dated rows, estimate=False). `POST /api/v1/dividends/update` fetches all snapshot symbols and persists a dated ledger at `data/dividends/ledger.json`; `use_ledger` backtests prefer the dated ledger (`dividend_method=dated_ledger`) and fall back to DPS estimates when unpopulated. Full backend **292 passed** (was 286). Live network fetch: 49/49 symbols, 1410 dated payments; use_ledger → `dated_ledger`. Note: this sandbox HAS outbound network (curl/https to siamchart 200) — contrary to earlier assumption.
|
||||
- Auto-refresh dated dividend ledger (2026-08-27, commit `03195dc`): `AppDataScheduler` now calls `_maybe_refresh_dated_dividends()` in `refresh_all` — a cooldown-gated (default 6h) fetch of real dated dividend history into `data/dividends/ledger.json`, so the ledger stays fresh without manual `/api/v1/dividends/update` and without hammering the source every tick. `DIVIDEND_REFRESH_COOLDOWN_SECONDS` env toggle. Full backend **294 passed** (was 292).
|
||||
- Single-container Docker packaging (2026-08-27, commit `f9b8cd1`): added `Dockerfile` (python:3.11-slim + nginx; serves the PREBUILT `frontend/dist` SPA, proxies `/api` → 127.0.0.1:5000, `VOLUME /app/backend/data`, HEALTHCHECK on /api/v1/dashboard/summary, exposes :80), `deploy/nginx.conf`, `deploy/entrypoint.sh` (Flask HOST=0.0.0.0:5000 + nginx foreground), `docker-compose.yml` (port 8080:80, volume `./backend/data`), `.dockerignore`, and `.gitignore` now tracks `frontend/dist/` (prebuilt bundle required by the image; `backend/data/` stays untracked). Backend runtime verified (test_client `/api/v1/dashboard/summary` = 200). No local docker on this machine so the image itself must build on EasyPanel.
|
||||
- Event-driven PIT backtest (2026-08-28, commits `68f2cc1` → `d73a58b`, 8-phase plan at `.hermes/plans/2026-08-28_091000-event-driven-pit-backtest.md`): replaces the calendar-rebalance backtest with a strict point-in-time event-driven engine. Confirmed user decisions: (1) strict PIT — block when factor/Siamchart/price coverage is incomplete; (2) execute at next trading-day close after release (no same-day look-ahead); (3) dividend cash available ex_date+30 calendar days (`ex_date_plus_30d` assumption, not an observed pay date — Siamchart source gives ex-date+DPS only); (4) average-cost realized P&L; (5) all-in 0.3% fee per trade, no added tax. Ships: `backtest_readiness.py` (readiness + recommended start/end defaults, fail-closed), `backtest_events.py` (event calendar + next-trading-day mapping), `portfolio_ledger.py` (cash/positions/avg-cost/realized+unrealized P&L/dividend receivables/fees; gross realized + fees subtracted once), `portfolio_rebalancer.py` (50/20/30 → executable 100-lot orders, sells-first, no trade on unchanged target), `backtest_engine.py` (event processor; refuses to fall back to the live board without a PIT scorer — fail-closed, was flagged by cycle-1 review `deleg_5225e9de` and fixed), `backtest_store.py` (durable atomic JSON runs at `data/backtest/runs.json`), strict route `POST /api/v1/backtest/run` (readiness-gate → 400 with missing list when not ready) + `GET /api/v1/backtest/run(+<id>)`, and frontend (readiness gate disables Run + shows missing coverage; report shows realized/unrealized P&L, dividend received/receivable, fees, final holdings with avg cost/last price/unrealized). Offline standalone suite **54 tests** (9+14+15+5+6+4→ readiness 10 after price regression); compileall + diff-check clean; static scan no secrets/eval/debug (4 "secret"-regex hits are the prose "missing token" string, not credentials). Independent review cycles: cycle-1 `deleg_5225e9de` flagged 3 logic errors (no-scorer live-board fallback look-ahead; price_coverage not checking explicit start → false PIT window; coincident-day ex-date entitlement breach) → all fixed; cycle-2 `deleg_b969075c` re-verified the fallback fix + 9/10 invariants and re-confirmed the invariant-4 breach; cycle-3 `deleg_7f56df3b` confirmed the ordering fix; cycle-4 `deleg_55f4e877` final re-review returned `passed=true`, empty `logic_errors`/`security_concerns` (suggestion only: per-symbol price coverage at an explicit start equal to the intersection start — deferred as a known edge-case limitation; the engine/accounting remain verified). Fixes: engine fails closed without a PIT scorer; readiness blocks an explicit start before price history exists; each calendar day runs dividend_entitlement < dividend_payment < rebalance (shares bought on ex-date not entitled). Live probes: `GET /api/v1/backtest/readiness` on real data → ready=false, recommended_end=2026-08-27; `POST /api/v1/backtest/run` on real data (no vintages) → 400 + missing list; happy-path `scripts/probe_event_backtest.py` (synthetic PIT-complete) → accounting_reconciled=True, identity lhs=rhs, leakage_guard=True, 100-lot holdings. Deploy-safe auto-collection (2026-08-28, commit `1fb1e1a`, +4 scheduler tests): `AppDataScheduler.refresh_all` now calls `_record_pit_factor_vintages` (writes each registry factor's PIT vintage via `FactorVintageStore.record`, dedupe on unchanged value; `released_at=retrieved_at=now` — evidence-safe, we do not assume an unknown reporting lag) and `_record_siamchart_vintages` (persists the current `set50_master.json` via `SiamchartVintageStore.persist`, idempotent). Runs inside the Flask process whether on Mac or the deployed container, so strict-PIT vintages accumulate wherever the app runs (persistent volume), not just locally. Live probe: `refresh_all()` 6/6 sources → 11 factor `.jsonl` + 1 Siamchart manifest snapshot written; strict readiness `ready=true` with explicit `end=today` (auto end=yesterday stays blocked until past data is knowable — honest). Per-source cadence + source health (2026-08-28, commit `14b2aef`, +4 scheduler tests): each `_REFRESH_JOBS` entry now carries a `frequency` (monthly for BOT tourism/macro/auto-sales, quarterly for NPL/energy/bank) and a cooldown marker (`data/scheduler/job_<key>.json`) so slow sources are re-fetched at their natural cadence (30d/91d) not every tick; a separate `_DAILY_JOBS` list refreshes Siamchart vintages + the Yahoo price snapshot (`prices.collect_price_snapshot`, rolling ~3y → yesterday) daily. Every refresh appends a per-source health log (`data/scheduler/source_health.json`, ring buffer 500) with an auto-classified failure category (network/timeout/http/parse/structure/auth/other) via `_analyze_error`, exposed through `GET /api/v1/scheduler/sources` and a new frontend "สถานะข้อมูล" panel (`#health`) with a one-click copy of the failure cause. Verification: first `refresh_all` produced 8 results + 8 job markers + 8 health entries (aLine truncated
|
||||
@@ -0,0 +1,69 @@
|
||||
# 2026-08-23 — replay and research-report integrity remediation
|
||||
|
||||
## Plan status
|
||||
|
||||
- Canonical replay validation: complete.
|
||||
- Research report content-hash binding: complete.
|
||||
- Research manifest-entry hash binding: complete.
|
||||
- Malformed report fail-closed handling: complete.
|
||||
- VintageStore snapshot/manifest loader fail-closed hardening: complete.
|
||||
- Semantic replay-shape validation: complete; non-list/non-object observations and exposures now fail closed through controlled `ValueError` handling.
|
||||
- Independent review gate: no valid approval for the current tree. `deleg_c227c439` found that `persist()` did not validate unrelated manifest entries before writing a new report; this was fixed with a regression test. `deleg_cf1da27d` then timed out after 600 seconds without a schema-valid JSON verdict; it is inconclusive, not an approval. `deleg_feb40653` was dispatched against the pre-semantic-fix tree, reported truncated cached diffs, and is stale/non-approving. `deleg_87a0f686` is the current bounded post-fix exact-diff review; no schema-complete current-tree approval has been surfaced yet.
|
||||
- Backtest gate: still blocked; this work does not create additional evidence.
|
||||
|
||||
## Changed files
|
||||
|
||||
- `backend/app/__init__.py` — replay and replayability now use `VintageStore.load_snapshot()` rather than reading normalized JSON directly.
|
||||
- `backend/app/research.py` — report hashes, manifest-entry hashes, strict object validation, explicit resumable legacy migration, and normalized snapshot lineage fields.
|
||||
- `backend/app/vintages.py` — malformed snapshot/manifest shape, encoding, and raw-payload I/O failures now map to `VintageStoreError`.
|
||||
- `backend/app/tourism.py` — malformed observation/exposure containers and entries now raise controlled semantic validation errors.
|
||||
- `backend/scripts/migrate_research_report_hashes.py` — explicit migration command for trusted pre-hash research stores.
|
||||
- `backend/tests/test_api.py` — canonical-store replay setup, tampered/semantically invalid snapshots including malformed exposure entries, and replay storage-I/O regressions.
|
||||
- `backend/tests/test_research.py` — report-file, manifest-hash, manifest-metadata, legacy migration, malformed-report, and persist-wide manifest-validation regressions.
|
||||
- `backend/tests/test_vintages.py` — non-object, invalid-UTF-8, and raw-payload I/O regression coverage.
|
||||
|
||||
## Root cause
|
||||
|
||||
The replay endpoint bypassed the canonical vintage loader, so a modified normalized snapshot could be recomputed as if it were trusted. Persisted research reports also had no self-hash, and the manifest metadata was not bound to its recorded entry. A changed report or `generated_at` value could therefore enter a replay path without integrity detection.
|
||||
|
||||
## Fix
|
||||
|
||||
- Replay loads only through `VintageStore.load_snapshot()`, which verifies raw payload, normalized payload, manifest metadata, and identity.
|
||||
- Reports persist `report_hash_algorithm=sha256-json-canonical-v1` and a canonical `report_hash`.
|
||||
- Each manifest entry persists and verifies its own canonical `manifest_entry_hash`, binding report filename, report hash, status, reason, and generated timestamp.
|
||||
- JSON values that are not report objects are rejected with `ResearchRunError` instead of causing an attribute error.
|
||||
- Non-object manifests and malformed manifest entries are rejected by `load_manifest()`, `list_runs()`, and `latest()`.
|
||||
- `list_runs()` verifies each report and manifest-entry hash before returning metadata.
|
||||
- `persist()` validates every existing manifest entry before returning or writing a new report, and refuses malformed entries without leaving an orphan report.
|
||||
- Direct report loads bind the manifest entry identity to the requested `run_id`.
|
||||
- Invalid UTF-8 in persisted manifest/report files is converted to `ResearchRunError` instead of escaping as a decode exception.
|
||||
- VintageStore rejects non-object snapshots, invalid UTF-8 manifests/snapshots, and raw-payload read failures with `VintageStoreError` instead of leaking attribute/decode/I/O exceptions.
|
||||
- Research input lineage now includes normalized snapshot hashes and their hash algorithm.
|
||||
- Replay computation rejects non-list/non-object observation/exposure shapes as controlled semantic failures, so the replay endpoint returns HTTP 422 rather than leaking `AttributeError`.
|
||||
|
||||
## Verification
|
||||
|
||||
```text
|
||||
PYTHONPATH=backend .venv/bin/python -W error -m unittest discover -s backend/tests -v
|
||||
Ran 79 tests ... OK
|
||||
|
||||
PYTHONPATH=backend .venv/bin/python -m compileall -q backend/app backend/scripts backend/tests
|
||||
npm run build
|
||||
npm audit --omit=dev --audit-level=high
|
||||
found 0 vulnerabilities
|
||||
git diff --check
|
||||
static scan of added lines: no findings
|
||||
```
|
||||
|
||||
Runtime smoke:
|
||||
|
||||
```text
|
||||
GET /api/v1/research/tourism/latest → HTTP 200; report_hash present
|
||||
GET /api/v1/backtest/tourism?min_events=12 → HTTP 409; reason=insufficient_vintages
|
||||
```
|
||||
|
||||
## Boundary and remaining work
|
||||
|
||||
These hashes detect local artifact corruption and accidental tampering; they are not signatures against a hostile operator who can rewrite the application, data, and runtime. The validated backtest remains blocked until at least 12 independent BOT releases and a point-in-time price archive exist.
|
||||
|
||||
The post-fix BOT collector run fetched the same release (`source_id=bot.ec_ei_028_s2`, `published_at=2026-07-31T14:30:00+07:00`), increasing observation count to 14 without increasing independent releases. The gate correctly remained `status=blocked`, `reason=insufficient_vintages`.
|
||||
@@ -0,0 +1,65 @@
|
||||
# M2.9 — Forward price observations and explicit research modes
|
||||
|
||||
## Plan status
|
||||
|
||||
- Status: **complete/blocked**
|
||||
- Complete: the system can record forward observations, detect local revisions, and run an explicitly labelled exploratory descriptive study.
|
||||
- Blocked: validated historical PIT backtest remains closed until a provider passes `pit-daily-v1` and BOT has at least 12 independent releases.
|
||||
|
||||
## Decision
|
||||
|
||||
The strict PIT requirement is a gate for validated historical backtests, not a launch blocker for exploratory or forward paper work. Revised vendor history remains usable only when the result is labelled `non_pit_descriptive_only`.
|
||||
|
||||
## Root cause addressed
|
||||
|
||||
The price store already preserved raw payloads and immutable normalized snapshots, but repeated retrievals had no durable observation history. The research runner also treated the PIT requirement as a universal gate, which prevented descriptive research from using an available revised history.
|
||||
|
||||
## Changes
|
||||
|
||||
- `backend/app/prices.py`
|
||||
- Added an optional, backward-compatible manifest `observations` list.
|
||||
- Records one observation per distinct retrieval identity with source/period scope, retrieval time, raw hash, prior snapshot ID/hash, revision status, and structured diff paths.
|
||||
- Preserves the original raw and normalized snapshot on unchanged retrievals; an actual content change creates a new snapshot/vintage instead of overwriting the prior one.
|
||||
- Tracks `first_seen_at`, `last_seen_at`, and `observation_count` on snapshot manifest entries.
|
||||
- Binds observation IDs to their content and rejects tampered or unknown-snapshot observation records at load time.
|
||||
- Keeps revised Yahoo history at `quality=revised_vendor_history` and `point_in_time=false`.
|
||||
- `backend/app/research.py`
|
||||
- Added explicit `mode=validated|exploratory`.
|
||||
- `validated` remains fail-closed on missing PIT archive evidence and requires per-bar known-at validation.
|
||||
- `exploratory` may proceed with revised history only as `result_scope=non_pit_descriptive_only`; it disables PIT known-at enforcement and emits limitations.
|
||||
- Runtime observation timestamps are excluded from the research input fingerprint, so an unchanged feed reuses the same frozen research run.
|
||||
- `backend/app/__init__.py`
|
||||
- Price health now exposes observation count, last observation time, and revision status.
|
||||
- Added `GET /api/v1/prices/observations` for the local audit trail.
|
||||
- The research endpoint accepts the explicit mode and defaults exploratory requests to one event unless overridden; validated requests retain the 12-event default.
|
||||
- `frontend/src/App.vue`
|
||||
- The research action explicitly requests exploratory mode with `min_events=1`.
|
||||
- UI copy and result metadata distinguish a descriptive study from a validated backtest.
|
||||
- Tests cover unchanged retrievals, revision diffs, immutable prior snapshots, observation tampering, exploratory execution, validated regression behavior, API mode validation, and stable run reuse.
|
||||
|
||||
## Verification evidence
|
||||
|
||||
- `PYTHONPATH=backend .venv/bin/python -W error -m unittest discover -s backend/tests -v`
|
||||
- Baseline before this slice: 93 tests passed.
|
||||
- First full run after the slice: 98 tests passed.
|
||||
- Focused run after observation-integrity hardening: 67 tests passed.
|
||||
- Final full run: 121 tests passed with `-W error`.
|
||||
- `PYTHONPATH=backend .venv/bin/python -m compileall -q backend` passed.
|
||||
- `npm run build` from `frontend/` passed.
|
||||
- `npm audit --omit=dev --audit-level=high` reported 0 vulnerabilities.
|
||||
- `git diff --check` passed.
|
||||
- Static scan over the changed code found zero hardcoded-secret assignments, shell execution, `eval`/`exec`, `pickle`, or SQL-f-string patterns.
|
||||
- Final bounded independent reviewer `deleg_e5407553`: schema-valid `passed=true`; `security_concerns=[]` and `logic_errors=[]`. Non-blocking gaps: concurrent persistence/atomic manifest-update coverage, same-raw normalized-content mismatch coverage, and invalid/missing/mismatched predecessor-reference coverage. Suggestions are deferred because the store remains single-process and validated PIT deployment is still blocked.
|
||||
|
||||
## Risks and limits
|
||||
|
||||
- Observation history proves only what this system observed after capture began. It does not prove provider release time, historical knowledge state, or absence of revisions before first capture.
|
||||
- The local filesystem store remains single-process; concurrent-writer safety and shared database migration are deferred.
|
||||
- No provider has passed the complete PIT evidence packet. Do not set `point_in_time=true` for revised vendor history.
|
||||
- No live execution, webhook, broker, MT5, or external order path was added.
|
||||
|
||||
## Exact next action
|
||||
|
||||
Keep collecting independent BOT releases until 12 genuinely distinct `(source_id, published_at)` releases exist. In parallel, request one complete market-data provider evidence packet with SET coverage, provider release identity/time, explicit known-at semantics, correction/revision replay, immutable raw/archive/manifest evidence, and timezone/session rules. Only then implement or promote a PIT adapter.
|
||||
|
||||
NEVER include API keys, tokens, passwords, secrets, credentials, or connection strings in the summary — replace any that appear with [REDACTED].
|
||||
@@ -0,0 +1,30 @@
|
||||
# Integrity Remediation Review — 2026-08-24
|
||||
|
||||
## Status
|
||||
|
||||
Complete for the staged integrity-remediation scope under the stated local single-user threat model. No commit or push was performed.
|
||||
|
||||
## Scope
|
||||
|
||||
The review covered canonical report-content hashing, manifest-entry identity/hash binding, replay through canonical loaders, manifest-wide validation before writes, raw/normalized snapshot binding, legacy migration boundaries, strict UTF-8/object/path/raw-hash validation, and tourism replay semantic validation.
|
||||
|
||||
## Independent Review Gate
|
||||
|
||||
- Original independent review `deleg_43348a3b` returned `passed=true` with empty `findings`, but its payload did not use the required `security_concerns` and `logic_errors` keys.
|
||||
- Schema-correction review `deleg_a1c721d2` returned exactly:
|
||||
`{"passed":true,"security_concerns":[],"logic_errors":[],"suggestions":[]}`
|
||||
- The corrected payload was parsed and verified to contain exactly the four required keys, with `passed=true` and all arrays empty.
|
||||
- Parallel review `deleg_e2d54c30` ended interrupted and contributes no evidence.
|
||||
|
||||
The corrected verdict closes the integrity-review gate for the stated threat model. It does not cover hostile machine owners, multi-user production deployment, live execution, or the separate point-in-time price-data readiness gate.
|
||||
|
||||
## Existing Verification Evidence
|
||||
|
||||
The parent verification already recorded 85 backend tests passing, compileall passing, Vite build passing, high-severity npm audit with zero vulnerabilities, and both working-tree and staged `git diff --check` passing. No new code was changed while processing this verdict.
|
||||
|
||||
## Remaining Work
|
||||
|
||||
- Revised vendor price history remains explicitly `point_in_time=false`.
|
||||
- Independent BOT releases remain below the 12-event research threshold.
|
||||
- PIT price archive design and evidence are still required before event-study/backtest readiness can be raised.
|
||||
- No commit or push has been performed.
|
||||
@@ -0,0 +1,55 @@
|
||||
# M2.9 Final Independent Review — 2026-08-24
|
||||
|
||||
## Status
|
||||
|
||||
- Review gate: **passed** for the bounded M2.9 remediation scope under the declared local single-process threat model.
|
||||
- Milestone: **complete/blocked** — exploratory and forward paper work is available; validated historical PIT research remains blocked.
|
||||
- Commit/push: none performed.
|
||||
|
||||
## Independent verdict
|
||||
|
||||
Reviewer `deleg_e5407553` returned the required schema-valid verdict:
|
||||
|
||||
```json
|
||||
{
|
||||
"passed": true,
|
||||
"security_concerns": [],
|
||||
"logic_errors": [],
|
||||
"test_gaps": [
|
||||
"concurrent read-modify-write persistence and atomic manifest updates",
|
||||
"same-raw-payload observation with differing normalized content",
|
||||
"invalid, missing, or mismatched predecessor references"
|
||||
],
|
||||
"suggestions": [
|
||||
"add process-level locking or transactional manifest updates before multi-worker deployment",
|
||||
"add malformed-manifest, equal-time, lineage, and predecessor adversarial fixtures",
|
||||
"add focused helper and frontend mapping tests"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The security and logic blocker arrays are empty. The listed gaps and suggestions are non-blocking for the current single-process local store and are deferred until the deployment scope expands or focused coverage is prioritized.
|
||||
|
||||
## Verification basis
|
||||
|
||||
- Backend: 121 tests passed with `-W error`.
|
||||
- Backend compileall: passed.
|
||||
- Frontend Vite build: passed.
|
||||
- Production dependency audit: 0 vulnerabilities.
|
||||
- `git diff --check`: passed.
|
||||
- Static dangerous-pattern scan: no hardcoded-secret assignments, shell execution, `eval`/`exec`, `pickle`, or SQL-f-string matches.
|
||||
- Live smoke: health and observations returned HTTP 200; validated backtest remained HTTP 409 and fail-closed.
|
||||
|
||||
## Remaining gates
|
||||
|
||||
- Revised vendor price history remains `point_in_time=false`.
|
||||
- BOT has only 1/12 independent releases.
|
||||
- No provider has supplied the evidence required by `pit-daily-v1`.
|
||||
- Do not claim a validated historical backtest or alpha result.
|
||||
- Add locking/transactional persistence before multi-worker or shared-filesystem deployment.
|
||||
|
||||
## Next action
|
||||
|
||||
Continue collecting genuinely independent BOT releases and request a complete PIT provider evidence packet. Keep exploratory output explicitly `status=descriptive_only` with `result_scope=non_pit_descriptive_only`.
|
||||
|
||||
NEVER include API keys, tokens, passwords, secrets, credentials, or connection strings in the summary — replace any that appear with [REDACTED].
|
||||
@@ -0,0 +1,46 @@
|
||||
# M2.9 Observation Integrity Follow-up — 2026-08-24
|
||||
|
||||
## Status
|
||||
|
||||
- Milestone: **complete/blocked** for the local single-process observation-integrity scope.
|
||||
- Commit/push: none performed.
|
||||
- Validated PIT research remains blocked; revised vendor history remains `point_in_time=false`.
|
||||
|
||||
## Scope
|
||||
|
||||
Closed three non-blocking local integrity gaps identified by the prior M2.9 review:
|
||||
|
||||
1. Reject a new snapshot that reuses the same raw payload hash while changing normalized content.
|
||||
2. Reject malformed snapshot manifest entries instead of silently skipping them.
|
||||
3. Harden observation predecessor chronology: observations cannot precede the manifest snapshot's immutable first capture, and equal-UTC duplicate observations for one snapshot are rejected.
|
||||
|
||||
The existing valid repeated-observation path remains supported: later observations of an unchanged immutable snapshot continue to append without creating a new snapshot or research run.
|
||||
|
||||
## TDD evidence
|
||||
|
||||
Each new behavior followed RED → GREEN:
|
||||
|
||||
- `test_price_store_rejects_same_raw_payload_with_changed_normalized_content` failed before the guard, then passed after the minimal raw/normalized consistency check.
|
||||
- `test_price_store_rejects_malformed_snapshot_manifest_entry` failed before manifest-entry type validation, then passed after fail-closed validation.
|
||||
- `test_price_store_rejects_observation_before_snapshot_first_capture` failed before first-capture temporal binding, then passed after binding to manifest `retrieved_at`.
|
||||
- `test_price_store_rejects_duplicate_equal_time_observations_for_one_snapshot` failed before equal-time ambiguity detection, then passed after strict predecessor ordering.
|
||||
|
||||
## Verification
|
||||
|
||||
- Price tests: 37 passed.
|
||||
- Full backend suite: 125 passed with `PYTHONPATH=backend .venv/bin/python -W error -m unittest discover -s backend/tests -v`.
|
||||
- Backend compileall: passed.
|
||||
- Frontend `npm run build`: passed.
|
||||
- `npm audit --omit=dev --audit-level=high`: `found 0 vulnerabilities`.
|
||||
- `git diff --check`: passed.
|
||||
- Added-line static scan: no hardcoded-secret assignments, shell execution, `eval`/`exec`, unsafe pickle, or SQL-f-string matches.
|
||||
- `ruff`, `mypy`, `eslint`, and `tsc` are not installed in this environment.
|
||||
- Fresh focused independent review `deleg_0e2282c8` returned schema-valid `passed=true` with `security_concerns=[]` and `logic_errors=[]`. Its only suggestion is to retain regression coverage for later repeated observations and deterministic equal-time ordering across distinct snapshot IDs.
|
||||
|
||||
## Remaining work
|
||||
|
||||
- Process-level locking/transactional manifest updates remain deferred until multi-worker or shared-filesystem deployment is in scope.
|
||||
- Focused helper/UI mapping coverage remains non-blocking follow-up work.
|
||||
- Continue collecting independent BOT releases and obtain a provider evidence packet satisfying `pit-daily-v1` before enabling validated PIT research.
|
||||
|
||||
NEVER include API keys, tokens, passwords, secrets, credentials, or connection strings in the summary — replace any that appear with [REDACTED].
|
||||
@@ -0,0 +1,47 @@
|
||||
# Paper Auth Policy — 2026-08-24
|
||||
|
||||
## Status
|
||||
|
||||
Complete for the paper-auth scope. The separate staged integrity-remediation review remains open. No commit or push was performed.
|
||||
|
||||
## Goal
|
||||
|
||||
Make the paper-only write path explicit and safe for the local single-user demo while preserving fail-closed protected mode for shared/network deployments.
|
||||
|
||||
## Changes
|
||||
|
||||
- Added explicit `demo` and `token` paper-auth modes.
|
||||
- Restricted demo mode to a loopback bind; unknown and non-loopback bind hosts fail closed.
|
||||
- Passed the actual `HOST`/bind value from `backend/run.py` into the app factory.
|
||||
- Kept protected token mode as the default and fail-closed when its configured credential is missing or malformed.
|
||||
- Added truthful API/UI state for “configured but not yet authenticated” versus “paper writes disabled by server configuration.”
|
||||
- Added regression coverage for demo writes, non-loopback rejection, unknown bind rejection, missing credentials, malformed credential configuration, and pre-session enabled state.
|
||||
- Updated README and handoff documentation with the two operating modes.
|
||||
|
||||
## Review Finding and Root-Cause Fix
|
||||
|
||||
The first independent review found that coercing a non-string configured credential to `str(...)` could turn malformed configuration into an accepted value. It also found that GET auth status conflated an unauthenticated browser session with a disabled server configuration. The fix validates configured credentials without coercion, reports an explicit `enabled` state, and prevents the UI from presenting a dead unlock/write path.
|
||||
|
||||
## Verification Evidence
|
||||
|
||||
- `PYTHONPATH=backend .venv/bin/python -W error -m unittest discover -s backend/tests -v` — 85 tests passed.
|
||||
- `PYTHONPATH=backend .venv/bin/python -m compileall -q backend` — passed.
|
||||
- `npm run build` — passed.
|
||||
- `npm audit --omit=dev --audit-level=high` — 0 vulnerabilities.
|
||||
- `git diff --check` and `git diff --cached --check` — passed.
|
||||
- Static diff scan for credential-shaped literals and dangerous patterns — no findings.
|
||||
- Environment smoke checks — loopback demo allowed; unknown and non-loopback demo binds rejected.
|
||||
- Fresh static-server verification on port 5175 — HTTP 200; served bundle contained the disabled-state copy and auth warning marker. Temporary server was stopped afterward.
|
||||
- `ruff`, `mypy`, and `eslint` are unavailable in this environment; no project lint script is configured for them.
|
||||
|
||||
## Data Safety
|
||||
|
||||
The smoke test created only synthetic paper rows in the runtime ledger; those exact test rows were removed afterward. The ledger was verified to contain no remaining smoke-test entries. No credentials, tokens, secrets, or connection strings were recorded.
|
||||
|
||||
## Independent Review
|
||||
|
||||
Fresh bounded review returned schema-valid `passed=true` with empty security-concern and logic-error arrays. Non-blocking suggestions: add one request-token type regression, add frontend integration coverage for both auth states, and add a startup precedence regression for `HOST`/`PAPER_BIND_HOST`.
|
||||
|
||||
## Remaining Gate
|
||||
|
||||
The separate staged integrity-remediation review is now closed for this scope: schema correction `deleg_a1c721d2` returned the exact required four-key verdict with `passed=true` and empty security/logic-error arrays. Earlier schema-invalid, timeout, and interrupted responses remain non-approving historical artifacts.
|
||||
@@ -0,0 +1,52 @@
|
||||
# PIT Daily Price Archive Contract — 2026-08-24
|
||||
|
||||
## Status
|
||||
|
||||
- Implementation: complete for the local research/paper vertical slice.
|
||||
- Provider evidence: not established yet.
|
||||
- Backtest/event-study readiness: blocked until a real archive satisfies this contract and the BOT source reaches the independent-vintage threshold.
|
||||
- Existing revised vendor history remains `point_in_time=false`.
|
||||
|
||||
## Contract
|
||||
|
||||
`point_in_time=true` is accepted only when all of the following are present and bound into the immutable price manifest:
|
||||
|
||||
- `quality=point_in_time_archive`.
|
||||
- `archive_contract=pit-daily-v1`.
|
||||
- Non-empty `provider_release_id`, `source_url`, `parser_version`, and timezone-aware `retrieved_at`.
|
||||
- `point_in_time_evidence` with `known_at_field=known_at`, `known_at_semantics=provider_release_time`, a matching provider release ID, and timezone-aware `release_published_at`.
|
||||
- Every series has a matching `canonical_symbol`, an IANA `timezone`, and ordered unique bars.
|
||||
- Every bar has `session_date`, timezone-aware `known_at`, OHLC, `adjusted_close`, and `volume` values. `known_at` must not be after the session date in the market timezone or after retrieval.
|
||||
- Snapshot raw-payload hashes, normalized hash, manifest identity, and contract metadata must agree on reload.
|
||||
|
||||
The generic Yahoo collector does not produce this evidence and continues to persist `revised_vendor_history` with `point_in_time=false`.
|
||||
|
||||
## No-lookahead behavior
|
||||
|
||||
The event-study runner has an explicit `require_price_known_at=True` mode. The research runner enables it for PIT snapshots. It rejects missing timestamps and rejects any price whose `known_at` falls on a later market-local session date, including UTC timestamps that cross the market-timezone boundary.
|
||||
|
||||
## Changed files
|
||||
|
||||
- `backend/app/prices.py` — PIT contract validation, per-bar known-at checks, timezone validation, manifest binding.
|
||||
- `backend/app/event_study.py` — known-at-aware price joining and market-timezone no-lookahead checks.
|
||||
- `backend/app/research.py` — carries session date, known-at, and market timezone into the event-study join; enables the PIT check.
|
||||
- `backend/app/__init__.py` — exposes contract metadata in price health and keeps backtest readiness fail-closed.
|
||||
- `backend/tests/test_prices.py`, `backend/tests/test_event_study.py`, `backend/tests/test_research.py` — RED/GREEN regression coverage for missing contract evidence, missing known-at, manifest binding, revised-history preservation, and timezone lookahead.
|
||||
|
||||
## Verification
|
||||
|
||||
- `PYTHONPATH=backend .venv/bin/python -W error -m unittest discover -s backend/tests -v` — **93 tests passed**.
|
||||
- `PYTHONPATH=backend .venv/bin/python -m compileall -q backend` — passed.
|
||||
- `npm run build` — passed.
|
||||
- `npm audit --omit=dev --audit-level=high` — 0 vulnerabilities.
|
||||
- `git diff HEAD --check` and `git diff --cached --check` — passed.
|
||||
- Static credential-pattern scan over `git diff HEAD` — 0 findings.
|
||||
- Final bounded independent review `deleg_c08f6dd8` — exact schema returned `passed=true` with empty security-concern, logic-error, and suggestion arrays. Two earlier reviewer attempts timed out and were not counted.
|
||||
- App smoke check: `/api/v1/prices/health` returned HTTP 200 for revised history; `/api/v1/backtest/tourism?min_events=1` returned HTTP 409 with `blocked` / `price_series_not_point_in_time`.
|
||||
|
||||
## Remaining work
|
||||
|
||||
- Obtain an actual provider archive/release contract and evidence for PIT semantics; do not flip the live Yahoo flag by configuration alone.
|
||||
- Collect at least 12 independent BOT releases; repeated observations of one release do not count.
|
||||
- Only after both gates pass should a frozen event-study/backtest result be treated as available. No alpha or investment claim is established here.
|
||||
- No commit or push was performed in this session.
|
||||
@@ -0,0 +1,85 @@
|
||||
# Price Provider Feasibility — 2026-08-24
|
||||
|
||||
## Decision
|
||||
|
||||
**No candidate passes `pit-daily-v1` from public evidence currently available.**
|
||||
|
||||
The repository must not add a provider adapter that emits `point_in_time=true` yet. Existing Yahoo/revised vendor history remains `quality=revised_vendor_history` and `point_in_time=false`.
|
||||
|
||||
This is a source-evidence decision, not a statement that the candidates cannot provide the required semantics under a commercial contract.
|
||||
|
||||
## Gate used
|
||||
|
||||
A provider must be able to supply an evidence-bearing archive with all of the following:
|
||||
|
||||
- stable `provider_release_id` for each release;
|
||||
- `release_published_at` or equivalent provider release time;
|
||||
- explicit `known_at` semantics that can be mapped to the provider release time;
|
||||
- daily bars with session date, OHLC, adjusted close, volume, and market timezone;
|
||||
- raw payload and normalized snapshot retained immutably;
|
||||
- a manifest binding release identity, period, symbols, raw hash, normalized hash, parser version, and source URL;
|
||||
- correction/revision behavior documented well enough to replay what was knowable at the decision time;
|
||||
- evidence that the SET symbols and SET50 benchmark requested by this project are covered.
|
||||
|
||||
The local implementation enforces this as `archive_contract=pit-daily-v1`; the implementation itself is not provider evidence.
|
||||
|
||||
## Candidate matrix
|
||||
|
||||
| Candidate | Publicly verified capability | PIT evidence gap | Decision |
|
||||
|---|---|---|---|
|
||||
| SET Historical Data Request | SET offers historical trading/statistics data as a one-time service, with data sent by email after payment. [1] | No public release ID per historical vintage, release publication time, known-at semantics, immutable archive contract, or correction replay semantics. | **Reject for PIT claim**. Useful as a historical data content source only until SET supplies a release/archive contract. |
|
||||
| SETSMART | SETSMART contains real-time and historical trading information for securities, derivatives, and indices. [2] | Public page does not establish timestamped historical snapshots, release identity, known-at semantics, or immutable archive replay. | **Not sufficient**. Do not build a PIT adapter from the web UI description alone. |
|
||||
| SMART Marketplace | SET describes an API platform with historical intraday data and equity EOD trading price/statistics. [3] | Public page does not establish per-release identity, release publication time, historical corrections/revisions, or immutable PIT archive semantics. | **Promising but unproven**. Request the API/archive data contract before implementation. |
|
||||
| ICE SET data | ICE advertises historical and end-of-day SET data, native exchange timestamps plus ICE UTC system timestamps, and an ICE historical archive. [4] [7] | The public pages do not prove that the SET daily archive exposes provider release IDs, release publication times, or point-in-time correction/replay semantics. Coverage and fields for this project also require confirmation. | **Best commercial candidate; conditional**. Ask ICE for a concrete sample archive and contract. |
|
||||
| LSEG Tick History / S3 Direct | LSEG explicitly advertises full historical market data and point-in-time updates through S3 Direct, with persistent access in the customer's S3 environment. [5] [6] | Public material still does not prove that SET is covered for the requested symbols or expose the release/update metadata needed to map each daily bar to `known_at=provider_release_time`. The point-in-time claim is strong, but the SET-specific evidence packet is missing. | **Strongest PIT candidate; not yet accepted**. Request SET venue coverage, sample files, release/update metadata, and revision replay evidence before writing an adapter. |
|
||||
| Databento Historical / Corporate Actions | Databento's venue page lists the Stock Exchange of Thailand, and its market-data pages describe aggregates through day-level bars, point-in-time instrument definitions, and nanosecond event timestamps. [8] [10] [11] | Databento's explicit PIT/replay contract is for corporate-action records: records are retained by `ts_record` and described as known at points in time. [9] The public market-data material does not establish price-bar release IDs, release publication times, client availability/`known_at`, or correction-vintage replay for SET prices. | **Reject for PIT price claim**. Retain as a possible SET coverage/reference-data lead; do not build a price adapter or promote its event timestamps to `known_at`. |
|
||||
| Exchange Data International (EDI) | EDI advertises daily EOD pricing across 170+ exchanges, OHLCV-style closing data, API/S3/SFTP delivery, and Thailand Stock Exchange coverage identified as `XBKK`; its July 2025 ETA sheet lists confirmed Thailand equity delivery at 14:30 GMT. [12] [14] | EDI documents unconfirmed-to-confirmed republish and correction files in `Repush1/2/3`, but its FAQ says there is currently no time-series database for EOD prices. [12] [13] Public material does not establish stable provider release IDs, actual release-published timestamps per file, immutable retention, or retrievable vintage manifests. | **Closest conditional candidate; not accepted**. Request a customer evidence packet before writing an adapter. |
|
||||
|
||||
## Required provider evidence packet
|
||||
|
||||
Before writing a production adapter, obtain one complete historical sample covering at least one SET symbol and the SET50 benchmark. The sample should include:
|
||||
|
||||
1. provider documentation defining `provider_release_id`, `release_published_at`, and the meaning of `known_at`;
|
||||
2. the exact raw response/file as delivered by the provider;
|
||||
3. the provider's release manifest or metadata file;
|
||||
4. a correction/revision example showing whether a later revision changes a prior bar and how both vintages are retrieved;
|
||||
5. the provider timezone and session-calendar definition;
|
||||
6. a symbol mapping file for the requested SET instruments;
|
||||
7. delivery metadata proving when the archive was available to the client, not only when the market session occurred;
|
||||
8. licensing/retention terms that permit immutable local replay for internal research and paper testing.
|
||||
|
||||
The fixture is accepted only if the complete packet can be normalized into the existing contract and replayed after changing neither the raw payload nor its manifest.
|
||||
|
||||
## Implementation decision
|
||||
|
||||
No files under `backend/app/` or `backend/scripts/` were changed for this feasibility pass. This avoids creating a fake adapter around a source whose PIT semantics are still unverified.
|
||||
|
||||
The next implementation action is one of:
|
||||
|
||||
- obtain a **market-data provider evidence packet** from EDI first, because its public docs expose SET coverage and correction/re-push behavior; this means provider documentation plus a representative market-data sample, not customer/vendor business data; or
|
||||
- build the smallest ICE adapter if ICE supplies a valid evidence packet; or
|
||||
- build the smallest LSEG adapter if LSEG supplies a valid evidence packet; or
|
||||
- keep the gate blocked and document the provider rejection if neither does.
|
||||
|
||||
Databento was checked as an additional candidate. Its public documentation is useful evidence for SET venue presence and PIT corporate-action history, but it does not close the PIT **price-vintage** gate. No Databento price adapter is justified from the public material currently available. [8] [9] [11]
|
||||
|
||||
EDI is currently the closest public price-feed lead: its correction/re-push workflow and confirmed Thailand ETA are relevant to vintage capture, but an ETA is not an actual per-release publication timestamp and the public contract still lacks the immutable release metadata required by `pit-daily-v1`. Treat EDI as a request-for-evidence path, not as a qualified provider. [12] [13] [14]
|
||||
|
||||
In parallel, continue collecting BOT **independent** releases. Repeated observations of one published release still do not count toward the 12-release threshold.
|
||||
|
||||
## Sources
|
||||
|
||||
[1] https://www.set.or.th/en/services/connectivity-and-data/data/historical
|
||||
[2] https://www.set.or.th/en/services/connectivity-and-data/data/web-based
|
||||
[3] https://www.set.or.th/en/services/connectivity-and-data/data/smart-marketplace
|
||||
[4] https://developer.ice.com/fixed-income-data-services/catalog/stock-exchange-thailand-set
|
||||
[5] https://www.lseg.com/en/data-analytics/market-data/data-feeds/tick-history
|
||||
[6] https://www.lseg.com/en/data-analytics/market-data/data-feeds/tick-history/s3-direct
|
||||
[7] https://www.ice.com/fixed-income-data-services/access-and-delivery/connectivity-and-feeds/ice-consolidated-history
|
||||
[8] https://databento.com/venues
|
||||
[9] https://databento.com/docs/venues-and-datasets/corporate-actions
|
||||
[10] https://databento.com/historical
|
||||
[11] https://databento.com/equities
|
||||
[12] https://www.exchange-data.com/product/end-day-pricing-data
|
||||
[13] https://www.exchange-data.com/faqs-end-of-day-prices
|
||||
[14] https://www.exchange-data.com/wp-content/uploads/2025/09/ETA-Coverage-17-July-2025.xls
|
||||
@@ -0,0 +1,170 @@
|
||||
# 2026-08-29 — Data-source expansion (Phase A) + frontend padding fix + sign bug
|
||||
|
||||
## Scope
|
||||
Two-part request from the owner:
|
||||
1. **More + genuinely-used data sources per theme** — the owner felt the source
|
||||
count was too few and insisted any newly-fetched data must feed the analysis
|
||||
(theme surprise), not just the provenance table.
|
||||
2. **Frontend padding/margin issues** — several panels had misaligned spacing.
|
||||
|
||||
## What changed (all verified)
|
||||
| Area | Change | Evidence |
|
||||
|---|---|---|
|
||||
| `factors.py` | Wired 2 **fetched-but-unused** BOT fields into the registry: `macro_core_inflation` (core inflation, sign −1) and `macro_unemployment` (sign −1) → they now actually move themes | Before, `macro_thai.to_dict()` emitted 7 fields but only 5 were registered factors — 2 were dead display data |
|
||||
| `themes.py` | Deepened banks/retail/consumer_staples/healthcare/nonbank_finance with the new factors (positive weights) | direction tests |
|
||||
| **Sign bug fix** | Found + fixed a **double-negative**: several factors carry `sign: -1` (NPL, inflation, unemployment) while theme weights were ALSO negative → higher NPL/inflation RAISED the theme score (inverted). Flipped all 16 theme weights to positive; direction now lives only in `sign`. Proven: auto-NPL 3.95→7.0 previously raised auto_credit 0.64→0.799; now lowers it. | `test_bearish_factors_move_score_the_right_way` |
|
||||
| **NEW `te_thailand.py`** | New TradingEconomics collector parsing 2 pages (interest-rate + consumer-confidence) → 6 factors: interest rate, loans-to-fin-corp, consumer credit, household-debt/GDP, retail-sales-YoY, consumer confidence | live fetch: rate 1.0%, retail -14.5% YoY, confidence 51.8 |
|
||||
| `themes.py` | Wired new TE factors into banks (rate/loan), retail + consumer_staples (retail sales + confidence), nonbank_finance (credit + debt + confidence) | direction tests |
|
||||
| `scheduler.py` / `dashboard.py` | Registered `te_thailand` in `_REFRESH_JOBS` + dashboard cached-fetch + `_build_sources` provenance | dashboard live build: 8 sources |
|
||||
| `frontend/App.vue` | Theme cards now show the new reads (banks→interest rate, retail→retail sales YoY, nonbank→household debt %GDP) | build clean |
|
||||
| `frontend/style.css` | **padding/margin + undefined-variable fix** — added missing design tokens (`--card/--foreground/--accent/--font/...`) that the theme/modal components reference but `:root` never declared (they rendered transparent/wrong-color); zeroed section-panel padding so `.signal-header` is the single top-spacing source (was double 22px+22px on theme/lineage/health/sim/backtest panels) | build clean |
|
||||
|
||||
## Key decisions
|
||||
- **One new module** (`te_thailand.py`) covers 4 plan items (A1 rate/credit, A2
|
||||
consumer credit, A3 retail sales, A4 confidence) because all four series live
|
||||
on just two TradingEconomics pages — avoids 4 fragile scrapers.
|
||||
- **Every source must feed a surprise**: tightened `test_every_factor_value_key_resolves_to_a_fetched_field` so a factor whose `value_key` the collector never emits fails the suite — no dead factors.
|
||||
- Sign convention locked: `sign` = factor direction, theme weights = positive magnitude. Regression test locks NPL/inflation/unemployment move correctly.
|
||||
|
||||
## Verified (evidence)
|
||||
- Full backend suite: **360 tests OK** (up from 352 — 8 new `test_te_thailand`).
|
||||
- Live dashboard build: 13 themes, 8 sources, new TE row; retail surprise −0.165
|
||||
(correctly negative from retail-sales −14.5% YoY) vs old BOT-only (positive).
|
||||
- Frontend `npm run build` clean.
|
||||
- Independent code review: see delegation verdict (fail-closed).
|
||||
|
||||
## Phase B (same day, follow-up "ทำต่อได้เลย")
|
||||
Extended the same `te_thailand` module with 2 more TradingEconomics pages:
|
||||
- `te_property_prices` (residential property prices +1.26% YoY) → **property** theme
|
||||
- `te_business_confidence` (46.7) → **telecom_it + property + healthcare**
|
||||
+2 FACTORS, +2 theme wrings, +4 tests (parse + direction for both). Full suite now
|
||||
**362 tests OK**; frontend build clean; live fetch confirmed (1.26 / 46.7).
|
||||
Cleared a stale daily-cache `te_thailand` entry so the new fields show immediately.
|
||||
|
||||
## Phase C (same day, follow-up "ทำ phase B ต่อได้เลย" — energy breadth)
|
||||
Feasibility spike of the remaining Phase B sources found most are JS-rendered or
|
||||
anti-bot (recorded in plan), but **IRPC** performance-highlights is server-rendered
|
||||
and clean. Added:
|
||||
- `backend/app/energy_irpc.py` — collector parsing IRPC net-profit/EBITDA/ROE
|
||||
margin rows [2024,2025,3M26], latest period (3M26: net margin **+10.27%**)
|
||||
- factor `energy_irpc_net_margin` (sign +1) wired into refining_energy /
|
||||
exploration / utilities (2nd real Thai refiner beyond TOP)
|
||||
- scheduler job + dashboard fetch + `_build_sources` row (now **9 sources**)
|
||||
- tests: parse (incl. paren-negatives), value-key resolution, direction
|
||||
- frontend theme card shows "กำไรสุทธิ IRPC 10.27%"
|
||||
Full suite **368 tests OK**; frontend build clean; live dashboard refining_energy
|
||||
surprise 0.764 driven partly by IRPC margin.
|
||||
Independent review `deleg_474555e4` **passed: true** (parser/paren/value-key/wiring
|
||||
all correct, no security/logic errors). Suggestion applied: comment noting
|
||||
ebitda/roe are display-only. Author also flagged that a single upstream page
|
||||
failure (strict `_fetch_with_cache` → DashboardError) takes down the whole board —
|
||||
consistent with the documented no-fixture-fallback policy; left as an open
|
||||
decision, not silently changed.
|
||||
|
||||
Deferred (feasibility blocked): REIC (JS SPA/XHR), EPPO (JS/WordPress), NBTC (403
|
||||
anti-bot), PTTEP (JS shell), PTT/BCP (404/DNS). Need browser/XHR approach, not
|
||||
plain-HTML — recorded in the plan as a separate effort.
|
||||
|
||||
## Phase D (same day — 3 follow-up asks)
|
||||
1. **Flexible scoring (Q2)**: `_fetch_with_cache` now degrades instead of raising
|
||||
`DashboardError` — source down + no cache = return {} (theme drops that
|
||||
source's factors); previously-good value present = daily cache returns stale.
|
||||
Board no longer crashes on any single upstream failure (verified: all-sources-
|
||||
down still builds 13 themes). `DashboardError` class now unused by build().
|
||||
2. **Per-source calc detail (Q3)**: new `themes.factor_source_breakdown(fetched,
|
||||
theme)` surfaced in dashboard as `fetch_data` + `factor_sources`, and in the
|
||||
per-symbol modal as `symbolDetail.factor_sources` — the owner sees, per theme,
|
||||
each factor's source → raw → normalized → weight → contribution (e.g. retail:
|
||||
te_thailand ยอดขายปลีก -14.5 → -1.0 × 0.7 = -0.7). Backend test added.
|
||||
3. **HAR feasibility for deferred sources (Q1)**: captured REIC via
|
||||
`har-derived-api-client` (Playwright drive → HAR → derived XHR endpoint
|
||||
`POST /Home/Web_All_Num_View`). Spike shows the method WORKS (browser drives
|
||||
the JS SPA, XHR endpoint derivable) BUT the homepage XHR returned an empty
|
||||
body — actual property data needs a deeper interaction (a real Transfer page
|
||||
click), so a full REIC collector is a larger follow-up, not a quick add.
|
||||
Finishing: commit Q2+Q3 with suite 369 green; Q1 recorded as feasible-but-
|
||||
needs-deeper-capture and left as a decision for the owner.
|
||||
|
||||
- Note: a **concurrent process** also landed `thai_trade.py` (external-sector
|
||||
exports/imports/current-account) and external_* factors mid-session; its 3
|
||||
initially-broken tests were fixed to reach the 360-green baseline here.
|
||||
|
||||
## Flexible PIT backtest (owner rule — 2026-08-30)
|
||||
Owner clarified the backtest contract: it must run as soon as there is enough
|
||||
data to estimate an investment, NOT only when EVERY factor has PIT history.
|
||||
Some sources may not provide deep history — scoring is deliberately flexible
|
||||
(a theme scores from whatever subset of factors was knowable that day).
|
||||
|
||||
Implemented (commit 2026-08-30):
|
||||
- `backtest_readiness.evaluate_readiness`: readiness is now a *usable* window
|
||||
(price + Siamchart + >=1 released factor), not all-factors-present. Missing
|
||||
factors are still reported in `missing` for transparency but no longer block.
|
||||
`recommended_start` = oldest executable price (the oldest history held);
|
||||
`recommended_end` = last complete trading day (yesterday Bangkok).
|
||||
- `pit_scorer.theme_surprise_report`: flexible — skips any factor with no release
|
||||
by `as_of` (no blanket theme block); `blocked` only when NO factor has a value.
|
||||
`pit_meta.partial_pit` reflects themes that scored from a partial subset.
|
||||
- Verified: `/api/v1/backtest/readiness` → ready=true, recommended 2024-01-03 →
|
||||
2026-08-29. `POST /api/v1/backtest/run` (default window) → 201 full result
|
||||
(final_equity 1,117,243.95 on 1M), no 400 from missing factors.
|
||||
- Tests: test_backtest_readiness updated to earliest-runnable semantics; full
|
||||
suite 369 green.
|
||||
|
||||
## Capital-allocation selection rework (owner rule — 2026-08-31)
|
||||
Owner clarified what the 3 buckets mean and flagged that the old selection
|
||||
(rank by `combined` = 60/40 theme+siamchart where siamchart was EPS-growth
|
||||
dominated) picked names like BTS whose EPS was up 137% but whose PRICE was flat/
|
||||
falling — NOT the owner's "ทำกำไร" (price likely to rise in 3-6 months).
|
||||
|
||||
New definition implemented:
|
||||
- "ทำกำไร" is now measured by a **price-trend (momentum) score**, not EPS growth.
|
||||
Added `themes.price_trend_score()` blending ~3/6/12-month momentum (trading
|
||||
days), z-scored across the universe (heavy weight on 3/6m per the 3-6 month
|
||||
tenure).
|
||||
- Buckets 1 & 2 rank by momentum, **gated on `theme_signal > 0`** (mean surprise
|
||||
of the symbol's themes). theme_signal=None (backtest path) is not gated, so
|
||||
the PIT backtest still allocates.
|
||||
- Bucket 3 unchanged: highest dividend yield, ignores score/momentum.
|
||||
- Suggestion endpoint passes real momentum + theme_signal from the live board.
|
||||
- Verified: suggestion now picks CRC+BEM (dividend, rising price) in bucket 1;
|
||||
PTT/MINT (falling price, theme positive) slide to bucket 3 by yield, not
|
||||
bucket 1. Full suite 372 green (3 new momentum/gate tests).
|
||||
|
||||
## Price-snapshot load fix + momentum gate (owner "เพื่อทดสอบ logic" — 2026-08-31)
|
||||
- `load_price_snapshot` was picking the LAST snapshot by FILENAME (lexicographic),
|
||||
which selected a stale 9-symbol collection over the full 50-symbol universe
|
||||
(`2024-01-01..` sorts after `2023-08-28..`). Now it picks the snapshot with the
|
||||
latest `source.retrieved_at`, so the full 50-symbol SET50 universe loads.
|
||||
- Suggestion now allocates across all 50 names; verified it picks rising-price,
|
||||
theme-positive dividend names in B1 (BGRIM, TTB), non-dividend rising in B2
|
||||
(BANPU), and yield-top names in B3 (ADVANC, SCB, LH).
|
||||
- Added momentum>0 gate to the profit buckets (a falling-price name must NOT be
|
||||
picked as "ทำกำไร"), while keeping momentum/theme_signal as Optional so the
|
||||
PIT backtest path (which doesn't provide them) still allocates.
|
||||
- Regression tests: load_price_snapshot picks most-recently-retrieved; negative
|
||||
momentum excluded from profit buckets. Full suite 374 green.
|
||||
|
||||
## Refactor: momentum is a factor INSIDE the Siamchart formula (owner rule — 2026-08-31)
|
||||
The owner insisted momentum must be entered INTO the score formula (a first-class
|
||||
factor), not bolted on outside it. Refactored `themes.py` from 3 loose weight
|
||||
constants + inline formula repeated in 3 places to a single declarative source:
|
||||
- `_SIAMCHART_WEIGHTS = {eps_growth:1.5, dividend_yield:2.0, momentum:0.5}` (config).
|
||||
- `siamchart_raw_score(g,d,m)` = single source of the formula; momentum is a term
|
||||
INSIDE it. All three call sites (build_siamchart_score, symbol_breakdown raw,
|
||||
symbol_breakdown population) now use it — no more duplicated arithmetic.
|
||||
- Purely a refactor: outputs unchanged (0.6/0.4 weighting intact), momentum
|
||||
already weighted 0.5 inside the formula.
|
||||
- Added tests: raw score formula incl. momentum term; momentum raises siamchart
|
||||
score given identical fundamentals. Full suite 376 green.
|
||||
|
||||
## Profit buckets now require a positive combined score (owner rule — 2026-08-31)
|
||||
The owner flagged that BGRIM/TTB still got recommended in bucket 1 even though
|
||||
their combined score was negative (-0.029 / -0.066): the profit pool only gated
|
||||
on momentum>0 + theme>0, so a stock with good price trend but weak fundamentals
|
||||
(EPS/yield lagging the cohort) could still be suggested.
|
||||
- `allocate_capital` profit_pool now ALSO requires `combined_score > 0` — a stock
|
||||
whose overall score is negative is never recommended in buckets 1/2, while
|
||||
still ranking by momentum within that gated pool.
|
||||
- Verified: suggestion now picks PTTGC (combined +0.209, mom +1.85) in bucket 1
|
||||
instead of BGRIM/TTB; BANPU in bucket 2 (combined +0.70); ADVANC/SCB/LH in
|
||||
bucket 3 by yield. Full suite 377 green.
|
||||
@@ -0,0 +1,60 @@
|
||||
# Test evidence — 2026-08-23 replay and research-report integrity remediation
|
||||
|
||||
## Automated
|
||||
|
||||
```text
|
||||
PYTHONPATH=backend .venv/bin/python -W error -m unittest discover -s backend/tests -v
|
||||
Ran 79 tests ... OK
|
||||
|
||||
PYTHONPATH=backend .venv/bin/python -m compileall -q backend/app backend/scripts backend/tests
|
||||
|
||||
npm run build
|
||||
Vite build completed successfully.
|
||||
|
||||
npm audit --omit=dev --audit-level=high
|
||||
found 0 vulnerabilities
|
||||
|
||||
git diff --check
|
||||
static scan of added lines: no findings
|
||||
```
|
||||
|
||||
Ruff, mypy, and ESLint were not installed/configured in this checkout and were skipped without masking an exit code.
|
||||
|
||||
## Regression coverage
|
||||
|
||||
- Replay reads through `VintageStore.load_snapshot()`.
|
||||
- Tampered normalized vintage snapshots return HTTP 422 from the replay endpoint.
|
||||
- Research report content tampering is rejected by the report hash.
|
||||
- Research manifest report-hash tampering is rejected.
|
||||
- Research manifest metadata tampering is rejected by the manifest-entry hash.
|
||||
- Non-object report JSON is rejected as invalid rather than raising an uncaught attribute error.
|
||||
- Non-object manifests and malformed manifest entries are rejected by `load_manifest()`, `list_runs()`, and `latest()`.
|
||||
- `list_runs()` verifies each report and manifest-entry hash before returning metadata.
|
||||
- `persist()` validates every existing manifest entry before returning or writing a new report, and refuses malformed entries without leaving an orphan report.
|
||||
- Source replayability uses the same verified load-and-compute helper as the replay endpoint, so semantically invalid snapshots are marked unreplayable.
|
||||
- Tourism replay computation rejects non-list and non-object observation/exposure shapes as controlled semantic validation failures instead of leaking `AttributeError`.
|
||||
- Replay storage I/O failures return HTTP 422 instead of leaking an uncontrolled 500.
|
||||
- Explicit legacy report migration validates identity/metadata, is resumable after an interrupted report write, and is not automatic.
|
||||
- Direct report loads bind the manifest entry identity to the requested `run_id`.
|
||||
- Invalid UTF-8 in persisted manifest/report files is converted to `ResearchRunError` instead of escaping as a decode exception.
|
||||
- VintageStore rejects non-object snapshots with `VintageStoreError`.
|
||||
- Invalid UTF-8 in vintage manifests/snapshots is converted to `VintageStoreError`.
|
||||
- Raw vintage payload read failures are converted to `VintageStoreError`.
|
||||
- Research lineage includes normalized snapshot hashes and algorithms.
|
||||
|
||||
## Runtime smoke
|
||||
|
||||
```text
|
||||
GET /api/v1/research/tourism/latest → HTTP 200; report_hash present
|
||||
GET /api/v1/backtest/tourism?min_events=12 → HTTP 409; reason=insufficient_vintages
|
||||
|
||||
BOT collector rerun → same published release, `seen_count=14`, independent release count remains 1, gate remains blocked.
|
||||
```
|
||||
|
||||
## Independent review
|
||||
|
||||
No valid approval for the current tree. `deleg_c227c439` found a persist-wide manifest-validation gap in the prior staged tree; the gap is now covered by a regression test and fixed before writing new reports. `deleg_cf1da27d` timed out after 600 seconds with no schema-valid JSON verdict, so it is inconclusive and does not approve the tree. `deleg_feb40653` was dispatched against the pre-semantic-fix tree, reported truncated cached diffs, and is stale/non-approving. `deleg_87a0f686` is the current bounded post-fix exact-diff review; no schema-complete current-tree approval has been surfaced yet.
|
||||
|
||||
## Scope boundary
|
||||
|
||||
This remediation improves local artifact integrity only. It does not unlock the backtest: the current evidence remains below 12 independent releases and price data remains `point_in_time=false`.
|
||||
@@ -0,0 +1,67 @@
|
||||
# Test Evidence — Forward Price Observations and Research Modes
|
||||
|
||||
- Date: 2026-08-24
|
||||
- Scope: M2.9 forward price observation archive, exploratory research mode, validated PIT regression
|
||||
- Branch: `main`
|
||||
- Commit: pending; no commit or push performed
|
||||
|
||||
## Commands and results
|
||||
|
||||
```text
|
||||
PYTHONPATH=backend .venv/bin/python -W error -m unittest discover -s backend/tests -v
|
||||
Ran 125 tests in 0.351s
|
||||
OK
|
||||
|
||||
PYTHONPATH=backend .venv/bin/python -m compileall -q backend
|
||||
exit 0
|
||||
|
||||
(cd frontend && npm run build)
|
||||
Vite production build completed successfully
|
||||
|
||||
(cd frontend && npm audit --omit=dev --audit-level=high)
|
||||
found 0 vulnerabilities
|
||||
|
||||
git diff --check
|
||||
exit 0
|
||||
```
|
||||
|
||||
Static scan over the changed code reported zero matches for:
|
||||
|
||||
```text
|
||||
secret_assignment=0
|
||||
shell=0
|
||||
eval=0
|
||||
pickle=0
|
||||
sql_fstring=0
|
||||
```
|
||||
|
||||
## Focused behavior verified
|
||||
|
||||
- Identical provider payloads reuse the immutable snapshot and append an `unchanged` observation.
|
||||
- Changed provider payloads create a new snapshot and append a `revised` observation with prior raw hash and structured diff paths.
|
||||
- Original raw/snapshot files remain readable after a revision.
|
||||
- Tampered observation audit entries fail closed on manifest load.
|
||||
- Contract-backed snapshot entries reject missing observation references, count/timing metadata tampering, and out-of-order/equal-time predecessor insertion without creating artifacts.
|
||||
- Non-PIT normalized series require canonical identity, strictly increasing sessions, and provider-symbol/raw-payload lineage.
|
||||
- Legacy pre-observation price manifests remain readable, while new contract-backed entries require complete manifest metadata cross-checks.
|
||||
- Observation time changes do not create a new research run when the price snapshot content is unchanged.
|
||||
- Same raw payload bytes with changed normalized content across a new snapshot ID are rejected.
|
||||
- Malformed snapshot manifest entries are rejected instead of silently skipped.
|
||||
- Observation timestamps before a snapshot's immutable first capture are rejected.
|
||||
- Duplicate equal-UTC observations for one snapshot are rejected while later repeated observations remain valid.
|
||||
- Explicit exploratory mode can run on revised history only with `status=descriptive_only`, `result_scope=non_pit_descriptive_only`, and limitations.
|
||||
- Validated mode still rejects non-PIT price history and requires the existing PIT/known-at contract.
|
||||
- API exposes `/api/v1/prices/observations`; invalid research modes return HTTP 400.
|
||||
|
||||
## Independent review status
|
||||
|
||||
The final bounded independent reviewer `deleg_e5407553` returned a schema-valid `passed=true` verdict with `security_concerns=[]` and `logic_errors=[]`. This follow-up closes the same-raw, malformed-manifest, first-capture timing, and equal-time duplicate gaps with RED/GREEN regressions. Fresh focused independent review `deleg_0e2282c8` returned schema-valid `passed=true` with empty blocker arrays; its only suggestion is to retain regression coverage for later repeated observations and deterministic equal-time ordering across distinct snapshot IDs. Process-level locking/transactional persistence and direct helper/UI tests remain deferred. No commit or push has been performed.
|
||||
|
||||
## Known limits
|
||||
|
||||
- Cache/diff evidence begins at first capture and does not prove provider release time or historical knowledge state before capture.
|
||||
- The live revised Yahoo history remains `quality=revised_vendor_history` and `point_in_time=false`.
|
||||
- No validated historical event study/backtest or alpha claim is enabled.
|
||||
- Local filesystem writes remain single-process; concurrent-writer and shared database verification are deferred.
|
||||
|
||||
NEVER include API keys, tokens, passwords, secrets, credentials, or connection strings in the summary — replace any that appear with [REDACTED].
|
||||
@@ -0,0 +1,78 @@
|
||||
# Test Evidence — PIT Daily Price Contract — 2026-08-24
|
||||
|
||||
## Scope
|
||||
|
||||
PIT daily-price archive validation and no-lookahead event-study joining. This evidence covers the implementation contract only; it does not claim that the live revised vendor source is PIT.
|
||||
|
||||
## Commands
|
||||
|
||||
```text
|
||||
PYTHONPATH=backend .venv/bin/python -W error -m unittest discover -s backend/tests -v
|
||||
Ran 93 tests in 0.214s — OK
|
||||
|
||||
PYTHONPATH=backend .venv/bin/python -m compileall -q backend
|
||||
passed
|
||||
|
||||
cd frontend && npm run build
|
||||
exit 0
|
||||
|
||||
cd frontend && npm audit --omit=dev --audit-level=high
|
||||
found 0 vulnerabilities
|
||||
|
||||
git diff HEAD --check && git diff --cached --check
|
||||
passed
|
||||
```
|
||||
|
||||
## Focused evidence
|
||||
|
||||
- A `point_in_time=true` snapshot without `pit-daily-v1` and provider-release evidence is rejected.
|
||||
- A PIT bar without `known_at` is rejected.
|
||||
- A valid PIT archive persists and reloads only when raw hash, normalized hash, manifest identity, release metadata, and contract metadata agree.
|
||||
- Existing snapshot IDs are immutable; changed raw or normalized content cannot overwrite an already manifested archive.
|
||||
- Malformed manifests, snapshots, and raw payload symbols fail as controlled `PriceSourceError` values before persistence.
|
||||
- Revised vendor history remains accepted only as `quality=revised_vendor_history` and `point_in_time=false`.
|
||||
- Event-study PIT mode rejects missing `known_at` and a timestamp after the session date.
|
||||
- Event-study PIT mode checks the session date in the declared market timezone, not only the UTC calendar date.
|
||||
- The research runner enables the known-at check when the PIT gate is active.
|
||||
|
||||
## Live app check
|
||||
|
||||
```text
|
||||
GET /api/v1/prices/health
|
||||
HTTP 200; current source is revised vendor history, point_in_time=false.
|
||||
|
||||
GET /api/v1/backtest/tourism?min_events=1
|
||||
HTTP 409; status=blocked; reason=price_series_not_point_in_time.
|
||||
```
|
||||
|
||||
- Final bounded independent review `deleg_c08f6dd8` returned `passed=true` with empty `security_concerns`, `logic_errors`, and `suggestions` arrays.
|
||||
|
||||
## Provider evidence gate
|
||||
|
||||
- Databento public material confirms SET venue presence and point-in-time corporate-action records, but does not establish point-in-time SET price-bar release IDs, client availability/`known_at`, or correction-vintage replay. [8][9][11]
|
||||
- Exchange Data International (EDI) public material confirms SET/XBKK equity coverage, a July 2025 confirmed ETA of 14:30 GMT, and correction/re-push behavior. Its public contract still does not establish actual per-file release timestamps, immutable retention, release IDs, or retrievable vintage manifests; its FAQ also states that it has no EOD time-series database. [12][13][14]
|
||||
- ICE and LSEG remain conditional commercial candidates; no candidate passed `pit-daily-v1`, so no provider adapter was added and the live API remains fail-closed. [4][5][6]
|
||||
- The broader matrix retains public references for SET Historical Data, SETSMART, and SMART Marketplace; none supplies the missing PIT release/vintage contract. [1][2][3]
|
||||
- ICE SET and Databento historical timestamp materials remain non-qualifying without SET price-vintage evidence. [7][10]
|
||||
- Full feasibility evidence and citations: `docs/engineering-log/2026-08-24-price-provider-feasibility.md`.
|
||||
|
||||
## Remaining gate
|
||||
|
||||
A real archive provider and release-time evidence are still required. The contract implementation must not be treated as evidence that any current vendor history is PIT. BOT remains at one independent release out of the required twelve.
|
||||
|
||||
## Sources
|
||||
|
||||
[1] https://www.set.or.th/en/services/connectivity-and-data/data/historical
|
||||
[2] https://www.set.or.th/en/services/connectivity-and-data/data/web-based
|
||||
[3] https://www.set.or.th/en/services/connectivity-and-data/data/smart-marketplace
|
||||
[4] https://developer.ice.com/fixed-income-data-services/catalog/stock-exchange-thailand-set
|
||||
[5] https://www.lseg.com/en/data-analytics/market-data/data-feeds/tick-history
|
||||
[6] https://www.lseg.com/en/data-analytics/market-data/data-feeds/tick-history/s3-direct
|
||||
[7] https://www.ice.com/fixed-income-data-services/access-and-delivery/connectivity-and-feeds/ice-consolidated-history
|
||||
[8] https://databento.com/venues
|
||||
[9] https://databento.com/docs/venues-and-datasets/corporate-actions
|
||||
[10] https://databento.com/historical
|
||||
[11] https://databento.com/equities
|
||||
[12] https://www.exchange-data.com/product/end-day-pricing-data
|
||||
[13] https://www.exchange-data.com/faqs-end-of-day-prices
|
||||
[14] https://www.exchange-data.com/wp-content/uploads/2025/09/ETA-Coverage-17-July-2025.xls
|
||||
@@ -0,0 +1,89 @@
|
||||
# Test Evidence — Event-Driven PIT Backtest (2026-08-28)
|
||||
|
||||
## Summary
|
||||
|
||||
Replaced the calendar-based backtest loop with a strict point-in-time,
|
||||
event-driven engine implementing the user-confirmed lifecycle.
|
||||
|
||||
## Confirmed user decisions implemented
|
||||
|
||||
1. **Strict PIT** — backtest blocks (400 + missing list) when factor vintages,
|
||||
Siamchart manifest, or executable prices do not fully cover the window.
|
||||
2. **Execution timing** — signal frozen on release date D; executed at next
|
||||
trading-day close after D (no same-day look-ahead).
|
||||
3. **Dividend timing** — entitled on ex-date (shares held before it); cash
|
||||
available exactly `ex_date + 30` calendar days, exposed as
|
||||
`ex_date_plus_30d`.
|
||||
4. **Average cost** — realized P&L uses weighted average cost.
|
||||
5. **Fees** — all-in 0.3% of notional on every buy and every sell; no added VAT.
|
||||
|
||||
## Tasks shipped (commits on main)
|
||||
|
||||
| Task | Commit | Tests |
|
||||
|---|---|---|
|
||||
| 1. PIT readiness + default dates | `68f2cc1` | 9 |
|
||||
| 2. Unified event calendar | `6439e9c` | 14 |
|
||||
| 3. Portfolio accounting ledger | `dc057e9` | 15 |
|
||||
| 4. Lot/cash-constrained rebalancer | `71b893e` | 5 |
|
||||
| 5. Event-driven backtest engine | `6459015` | 4 |
|
||||
| 6. Durable run store + strict route | `c87767c` | 4 |
|
||||
| 7. Frontend readiness/report | `d73a58b` | build |
|
||||
| 8. Verification/review | (this doc) | — |
|
||||
|
||||
## Standalone suite (unittest, offline, deterministic)
|
||||
|
||||
```
|
||||
51 tests OK
|
||||
test_backtest_readiness (9) test_backtest_events (14)
|
||||
test_portfolio_ledger (15) test_portfolio_rebalancer (5)
|
||||
test_backtest_engine (4) test_backtest_store (4)
|
||||
```
|
||||
|
||||
Compileall (all new modules): pass. `git diff --check`: clean.
|
||||
|
||||
## Static security scan (new backend files)
|
||||
|
||||
- secrets regex: 4 hits in `backtest_readiness.py` — all are the prose string
|
||||
"missing token" (the umbrella missing-coverage token), **not** credentials.
|
||||
- eval/exec: 0. Debug/print: 0.
|
||||
- No hardcoded credentials, no path traversal, no unsafe eval.
|
||||
|
||||
## Live probes
|
||||
|
||||
### Fail-closed readiness (real local data — no factor vintages yet)
|
||||
|
||||
`POST /api/v1/backtest/run` on the on-disk data (0 factor vintages, no Siamchart
|
||||
manifest) returns **400** with `missing` listing factor keys + siamchart — it
|
||||
does not manufacture a fake PIT window.
|
||||
|
||||
`GET /api/v1/backtest/readiness` on real data: `ready=false`,
|
||||
`missing` includes factor + siamchart, `recommended_end=2026-08-27` (yesterday,
|
||||
Bangkok).
|
||||
|
||||
### Happy-path engine (synthetic PIT-complete inputs)
|
||||
|
||||
`backend/scripts/probe_event_backtest.py` (deterministic):
|
||||
- `accounting_reconciled: True`
|
||||
- accounting identity satisfied: `final_equity - capital == realized + unrealized + dividend_cash - fees`
|
||||
(`lhs=84760.0 == rhs=84760.0`)
|
||||
- `leakage_guard: True` (pit_meta-attested scorer)
|
||||
- dividend cash credited (ex_date+30), receivable 0 by end
|
||||
- holdings all 100-lot multiples (A=5000, B=3000)
|
||||
- fee 0.3% applied (240.0)
|
||||
|
||||
## Accounting invariant
|
||||
|
||||
```
|
||||
ending_equity - initial_capital
|
||||
= realized_trading_pnl (gross, avg cost)
|
||||
+ unrealized_trading_pnl
|
||||
+ dividend_cash_received
|
||||
- transaction_costs
|
||||
```
|
||||
|
||||
`price_pnl = realized + unrealized` (compat).
|
||||
|
||||
## Independent review
|
||||
|
||||
See the reviewer subagent verdict recorded in the commit / engineering-log for
|
||||
this session (`deleg_5225e9de`).
|
||||
+1
@@ -0,0 +1 @@
|
||||
@import"https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=Manrope:wght@400;500;600;700;800&display=swap";:root{color-scheme:dark;font-family:Manrope,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,sans-serif;color:#edf2f7;background:#0b1018;font-synthesis:none;text-rendering:optimizeLegibility;--bg: #0b1018;--panel: #111925;--panel-soft: #151f2d;--line: #263344;--line-bright: #35465c;--text: #edf2f7;--muted: #8794a6;--faint: #5b6a7e;--mint: #52d6bd;--mint-soft: rgba(82, 214, 189, .12);--amber: #e6b96c;--amber-soft: rgba(230, 185, 108, .12);--red: #ef8b8b;--red-soft: rgba(239, 139, 139, .12);--card: #151f2d;--foreground: #edf2f7;--text-2: #a9b2c2;--font: "Manrope", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, sans-serif;--accent: #4da3ff;--accent-soft: rgba(77, 163, 255, .12);--danger: #ef8b8b;--line-weak: rgba(255, 255, 255, .05)}*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;min-width:320px;background:var(--bg)}button,input{font:inherit}button{cursor:pointer}.app-shell{min-height:100vh;display:flex;background:radial-gradient(circle at 85% -10%,rgba(82,214,189,.08),transparent 32rem),var(--bg)}.sidebar{width:248px;flex:0 0 248px;min-height:100vh;padding:28px 18px 22px;border-right:1px solid var(--line);display:flex;flex-direction:column;background:#0b1018c2}.brand-lockup{display:flex;align-items:center;gap:11px;padding:0 9px 33px}.brand-mark{width:32px;height:32px;display:grid;place-items:center;border:1px solid rgba(82,214,189,.7);border-radius:9px;color:var(--mint);font:500 11px DM Mono,monospace;letter-spacing:-.08em;box-shadow:0 0 24px #52d6bd1f}.brand-name{font-size:13px;font-weight:800;letter-spacing:.01em}.brand-caption{margin-top:2px;color:var(--faint);font:10px DM Mono,monospace}.nav-stack{display:grid;gap:5px}.nav-item{display:flex;align-items:center;gap:11px;padding:11px 12px;border:1px solid transparent;border-radius:8px;color:var(--muted);text-decoration:none;font-size:12px;font-weight:600;transition:.2s ease}.nav-item:hover{color:var(--text);background:#ffffff06}.nav-item.active{color:var(--mint);background:var(--mint-soft);border-color:#52d6bd2e}.nav-glyph{width:16px;color:currentColor;font-size:15px;text-align:center}.sidebar-footer{margin-top:auto;padding:12px 8px 0}.mode-card{display:flex;gap:10px;align-items:center;padding:12px;border:1px solid var(--line);border-radius:10px;background:#ffffff05}.mode-dot,.freshness-dot{width:7px;height:7px;flex:0 0 7px;border-radius:99px;background:var(--mint);box-shadow:0 0 12px var(--mint)}.mode-label{font-size:11px;font-weight:700}.mode-detail,.version-line{margin-top:3px;color:var(--faint);font:10px DM Mono,monospace}.version-line{padding:14px 3px 0}.content{flex:1 1 auto;min-width:0;width:min(100%,1440px);margin:0 auto;padding:42px clamp(22px,4vw,64px) 70px}.topbar{display:flex;justify-content:space-between;gap:24px;align-items:flex-start;padding-bottom:35px}.eyebrow,.section-kicker{color:var(--mint);font:500 10px DM Mono,monospace;letter-spacing:.14em;text-transform:uppercase}h1,h2,p{margin:0}h1{margin-top:10px;font-size:clamp(28px,4vw,46px);line-height:1.04;letter-spacing:-.055em}h2{margin-top:7px;font-size:17px;letter-spacing:-.025em}.subtitle{max-width:560px;margin-top:12px;color:var(--muted);font-size:13px;line-height:1.7}.topbar-meta{text-align:right;color:var(--muted);font:10px DM Mono,monospace}.freshness-pill{display:inline-flex;align-items:center;gap:8px;padding:7px 10px;border:1px solid rgba(82,214,189,.25);border-radius:99px;color:var(--mint);background:var(--mint-soft)}.freshness-pill.pill-fixture{border-color:#e6b96c59;color:var(--amber);background:var(--amber-soft)}.freshness-pill.pill-fixture .freshness-dot{background:var(--amber);box-shadow:0 0 12px var(--amber)}.as-of{margin-top:10px}.kpi-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px;margin-bottom:12px}.kpi-card,.panel,.state-card{border:1px solid var(--line);background:linear-gradient(145deg,#151f2ddb,#0e151ff0);box-shadow:0 18px 42px #0000001f}.kpi-card{min-height:132px;min-width:0;padding:19px 19px 16px;border-radius:10px}.accent-card{border-color:#52d6bd4d;background:linear-gradient(145deg,#19383bcc,#0e1f26eb)}.kpi-label{color:var(--muted);font:10px DM Mono,monospace;text-transform:uppercase;letter-spacing:.08em;overflow-wrap:anywhere}.kpi-value{margin-top:12px;color:var(--text);font-size:29px;font-weight:700;letter-spacing:-.055em;overflow-wrap:anywhere}.kpi-unit{margin-left:4px;color:var(--mint);font:14px DM Mono,monospace}.quality-value{font-size:22px;text-transform:capitalize}.kpi-foot{margin-top:10px;color:var(--faint);font:10px DM Mono,monospace}.long-count,.positive-text{color:var(--mint)}.short-count,.negative-text{color:var(--red)}.hero-grid,.bottom-grid{display:grid;grid-template-columns:minmax(0,1.45fr) minmax(0,1fr);gap:12px;margin-bottom:12px}.panel{border-radius:10px;padding:22px}.panel-header{display:flex;justify-content:space-between;align-items:flex-start;gap:20px}.confidLine truncated
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))n(l);new MutationObserver(l=>{for(const i of l)if(i.type==="childList")for(const r of i.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&n(r)}).observe(document,{childList:!0,subtree:!0});function s(l){const i={};return l.integrity&&(i.integrity=l.integrity),l.referrerPolicy&&(i.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?i.credentials="include":l.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(l){if(l.ep)return;l.ep=!0;const i=s(l);fetch(l.href,i)}})();/**
|
||||
* @vue/shared v3.5.41
|
||||
* (c) 2018-present Yuxi (Evan) You and Vue contributors
|
||||
* @license MIT
|
||||
**/function mn(e){const t=Object.create(null);for(const s of e.split(","))t[s]=1;return s=>s in t}const ee={},Dt=[],ze=()=>{},ml=()=>!1,Ds=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),Ls=e=>e.startsWith("onUpdate:"),be=Object.assign,bn=(e,t)=>{const s=e.indexOf(t);s>-1&&e.splice(s,1)},Ri=Object.prototype.hasOwnProperty,G=(e,t)=>Ri.call(e,t),$=Array.isArray,Lt=e=>is(e)==="[object Map]",$s=e=>is(e)==="[object Set]",Hn=e=>is(e)==="[object Date]",N=e=>typeof e=="function",ae=e=>typeof e=="string",Ye=e=>typeof e=="symbol",Z=e=>e!==null&&typeof e=="object",bl=e=>(Z(e)||N(e))&&N(e.then)&&N(e.catch),yl=Object.prototype.toString,is=e=>yl.call(e),Mi=e=>is(e).slice(8,-1),xl=e=>is(e)==="[object Object]",yn=e=>ae(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,qt=mn(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),Ns=e=>{const t=Object.create(null);return(s=>t[s]||(t[s]=e(s)))},Ii=/-\w/g,De=Ns(e=>e.replace(Ii,t=>t.slice(1).toUpperCase())),Fi=/\B([A-Z])/g,Ot=Ns(e=>e.replace(Fi,"-$1").toLowerCase()),wl=Ns(e=>e.charAt(0).toUpperCase()+e.slice(1)),Gs=Ns(e=>e?`on${wl(e)}`:""),We=(e,t)=>!Object.is(e,t),Ss=(e,...t)=>{for(let s=0;s<e.length;s++)e[s](...t)},Sl=(e,t,s,n=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:n,value:s})},xn=e=>{const t=parseFloat(e);return isNaN(t)?e:t};let Vn;const js=()=>Vn||(Vn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function Hs(e){if($(e)){const t={};for(let s=0;s<e.length;s++){const n=e[s],l=ae(n)?Ni(n):Hs(n);if(l)for(const i in l)t[i]=l[i]}return t}else if(ae(e)||Z(e))return e}const Di=/;(?![^(]*\))/g,Li=/:([^]+)/,$i=/\/\*[^]*?\*\//g;function Ni(e){const t={};return e.replace($i,"").split(Di).forEach(s=>{if(s){const n=s.split(Li);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function Q(e){let t="";if(ae(e))t=e;else if($(e))for(let s=0;s<e.length;s++){const n=Q(e[s]);n&&(t+=n+" ")}else if(Z(e))for(const s in e)e[s]&&(t+=s+" ");return t.trim()}const ji="itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly",Hi=mn(ji);function Cl(e){return!!e||e===""}function Vi(e,t){if(e.length!==t.length)return!1;let s=!0;for(let n=0;s&&n<e.length;n++)s=os(e[n],t[n]);return s}function os(e,t){if(e===t)return!0;let s=Hn(e),n=Hn(t);if(s||n)return s&&n?e.getTime()===t.getTime():!1;if(s=Ye(e),n=Ye(t),s||n)return e===t;if(s=$(e),n=$(t),s||n)return s&&n?Vi(e,t):!1;if(s=Z(e),n=Z(t),s||n){if(!s||!n)return!1;const l=Object.keys(e).length,i=Object.keys(t).length;if(l!==i)return!1;for(const r in e){const a=e.hasOwnProperty(r),u=t.hasOwnProperty(r);if(a&&!u||!a&&u||!os(e[r],t[r]))return!1}}return String(e)===String(t)}function kl(e,t){return e.findIndex(s=>os(s,t))}const Tl=e=>!!(e&&e.__v_isRef===!0),m=e=>ae(e)?e:e==null?"":$(e)||Z(e)&&(e.toString===yl||!N(e.toString))?Tl(e)?m(e.value):JSON.stringify(e,El,2):String(e),El=(e,t)=>Tl(t)?El(e,t.value):Lt(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((s,[n,l],i)=>(s[Js(n,i)+" =>"]=l,s),{})}:$s(t)?{[`Set(${t.size})`]:[...t.values()].map(s=>Js(s))}:Ye(t)?Js(t):Z(t)&&!$(t)&&!xl(t)?String(t):t,Js=(e,t="")=>{var s;return Ye(e)?`Symbol(${(s=e.description)!=null?s:t})`:e};/**
|
||||
* @vue/reactivity v3.5.41
|
||||
* (c) 2018-present Yuxi (Evan) You and Vue contributors
|
||||
* @license MIT
|
||||
**/let he;class Bi{constructor(t=!1){this.detached=t,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this._warnOnRun=!0,this.__v_skip=!0,!t&&he&&(he.active?(this.parent=he,this.index=(he.scopes||(he.scopes=[])).push(this)-1):(this._active=!1,this._warnOnRun=!1))}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let t,s;if(this.scopes){const n=this.scopes.slice();for(t=0,s=n.length;t<s;t++)n[t].pause()}for(t=0,s=this.effects.length;t<s;t++)this.effects[t].pause()}}resume(){if(this._active&&this._isPaused){this._isPaused=!1;let t,s;if(this.scopes){const l=this.scopes.slice();for(t=0,s=l.length;t<s;t++)l[t].resume()}const n=this.effects.slice();for(t=0,s=n.length;t<s;t++)n[t].resume()}}run(t){if(this._active){const s=he;try{return he=this,t()}finally{he=s}}}on(){++this._on===1&&(this.prevScope=he,he=this)}off(){if(this._on>0&&--this._on===0){if(he===this)he=this.prevScope;else{let t=he;for(;t;){if(t.prevScope===this){t.prevScope=this.prevScope;break}t=t.prevScope}}this.prevScope=void 0}}stop(t){if(this._active){this._active=!1;let s,n;for(s=0,n=this.effects.length;s<n;s++)this.effects[s].stop();for(this.effects.length=0,s=0,n=this.cleanups.length;s<n;s++)this.cleanups[s]();if(this.cleanups.length=0,this.scopes){const l=this.scopes.slice();for(s=0,n=l.length;s<n;s++)l[s].stop(!0);this.scopes.length=0}if(!this.detached&&this.parent&&!t){const l=this.parent.scopes.pop();l&&l!==this&&(this.parent.scopes[this.index]=l,l.index=this.index)}this.parent=void 0}}}function Ki(){return he}let se;const Xs=new WeakSet;class Ol{constructor(t){this.fn=t,this.deps=void 0,this.depsTail=void 0,this.flags=5,this.next=void 0,this.cleanup=void 0,this.scheduler=void 0,he&&(he.active?he.effects.push(this):this.flags&=-2)}pause(){this.flags|=64}resume(){this.flags&64&&(this.flags&=-65,Xs.has(this)&&(Xs.delete(this),this.trigger()))}notify(){this.flags&2&&!(this.flags&32)||this.flags&8||Al(this)}run(){if(!(this.flags&1))return this.fn();this.flags|=2,Bn(this),Rl(this);const t=se,s=Le;se=this,Le=!0;try{return this.fn()}finally{Ml(this),se=t,Le=s,this.flags&=-3}}stop(){if(this.flags&1){for(let t=this.deps;t;t=t.nextDep)Cn(t);this.deps=this.depsTail=void 0,Bn(this),this.onStop&&this.onStop(),this.flags&=-2}}trigger(){this.flags&64?Xs.add(this):this.scheduler?this.scheduler():this.runIfDirty()}runIfDirty(){an(this)&&this.run()}get dirty(){return an(this)}}let Pl=0,Yt,Gt;function Al(e,t=!1){if(e.flags|=8,t){e.next=Gt,Gt=e;return}e.next=Yt,Yt=e}function wn(){Pl++}function Sn(){if(--Pl>0)return;if(Gt){let t=Gt;for(Gt=void 0;t;){const s=t.next;t.next=void 0,t.flags&=-9,t=s}}let e;for(;Yt;){let t=Yt;for(Yt=void 0;t;){const s=t.next;if(t.next=void 0,t.flags&=-9,t.flags&1)try{t.trigger()}catch(n){e||(e=n)}t=s}}if(e)throw e}function Rl(e){for(let t=e.deps;t;t=t.nextDep)t.version=-1,t.prevActiveLink=t.dep.activeLink,t.dep.activeLink=t}function Ml(e){let t,s=e.depsTail,n=s;for(;n;){const l=n.prevDep;n.version===-1?(n===s&&(s=l),Cn(n),Ui(n)):t=n,n.dep.activeLink=n.prevActiveLink,n.prevActiveLink=void 0,n=l}e.deps=t,e.depsTail=s}function an(e){for(let t=e.deps;t;t=t.nextDep)if(t.dep.version!==t.version||t.dep.computed&&(Il(t.dep.computed)||t.dep.version!==t.version))return!0;return!!e._dirty}function Il(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===Qt)||(e.globalVersion=Qt,!e.isSSR&&e.flags&128&&(!e.deps&&!e._dirty||!an(e))))return;e.flags|=2;const t=e.dep,s=se,n=Le;se=e,Le=!0;try{Rl(e);const l=e.fn(e._value);(t.version===0||We(l,e._value))&&(e.flags|=128,e._value=l,t.version++)}catch(l){throw t.version++,l}finally{se=s,Le=n,Ml(e),e.flags&=-3}}function Cn(e,t=!1){const{dep:s,prevSub:n,nextSub:l}=e;if(n&&(n.nextSub=l,e.prevSub=void 0),l&&(l.prevSub=n,e.nextSub=void 0),s.subs===e&&(s.subs=n,!n&&s.computed)){s.computed.flags&=-5;for(let i=s.computed.deps;i;i=i.nextDep)Cn(i,!0)}!t&&!--s.sc&&s.map&&s.map.delete(s.key)}function Ui(e){const{prevDep:t,nextDep:s}=e;t&&(t.nextDep=s,e.prevDep=void 0),s&&(s.prevDep=t,e.nextDep=void 0)}let Le=!0;const Fl=[];function rt(){Fl.push(Le),Le=!1}function at(){const e=Fl.pop();Le=e===void 0?!0:e}function Bn(e){const{cleanup:t}=e;if(e.cleanup=void 0,t){const s=se;se=void 0;try{t()}finally{se=s}}}let Qt=0;class Wi{constructor(t,s){this.sub=t,this.dep=s,this.version=s.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class kn{constructor(t){this.computed=t,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0,this.__v_skip=!0}track(t){if(!se||!Le||se===this.computed)return;let s=this.activeLink;if(s===void 0||s.sub!==se)s=this.activeLink=new Wi(se,this),se.deps?(s.prevDep=se.depsTail,se.depsTail.nextDep=s,se.depsTail=s):se.deps=se.depsTail=s,Dl(s);else if(s.version===-1&&(s.version=this.version,s.nextDep)){const n=s.nextDep;n.prevDep=s.prevDep,s.prevDep&&(s.prevDep.nextDep=n),s.prevDep=se.depsTail,s.nextDep=void 0,se.depsTail.nextDep=s,se.depsTail=s,se.deps===s&&(se.deps=Line truncated
|
||||
* @vue/runtime-core v3.5.41
|
||||
* (c) 2018-present Yuxi (Evan) You and Vue contributors
|
||||
* @license MIT
|
||||
**/function rs(e,t,s,n){try{return n?e(...n):e()}catch(l){Bs(l,t,s)}}function Ne(e,t,s,n){if(N(e)){const l=rs(e,t,s,n);return l&&bl(l)&&l.catch(i=>{Bs(i,t,s)}),l}if($(e)){const l=[];for(let i=0;i<e.length;i++)l.push(Ne(e[i],t,s,n));return l}}function Bs(e,t,s,n=!0){const l=t?t.vnode:null,{errorHandler:i,throwUnhandledErrorInProduction:r}=t&&t.appContext.config||ee;if(t){let a=t.parent;const u=t.proxy,g=`https://vuejs.org/error-reference/#runtime-${s}`;for(;a;){const h=a.ec;if(h){for(let y=0;y<h.length;y++)if(h[y](e,u,g)===!1)return}a=a.parent}if(i){rt(),rs(i,null,10,[e,u,g]),at();return}}mo(e,s,l,n,r)}function mo(e,t,s,n=!0,l=!1){if(l)throw e;console.error(e)}const we=[];let Be=-1;const $t=[];let ht=null,Ft=0;const Kl=Promise.resolve();let Os=null;function bo(e){const t=Os||Kl;return e?t.then(this?e.bind(this):e):t}function yo(e){let t=Be+1,s=we.length;for(;t<s;){const n=t+s>>>1,l=we[n],i=ts(l);i<e||i===e&&l.flags&2?t=n+1:s=n}return t}function An(e){if(!(e.flags&1)){const t=ts(e),s=we[we.length-1];!s||!(e.flags&2)&&t>=ts(s)?we.push(e):we.splice(yo(t),0,e),e.flags|=1,Ul()}}function Ul(){Os||(Os=Kl.then(zl))}function xo(e){if(!$(e))ht&&e.id===-1?ht.splice(Ft+1,0,e):e.flags&1||($t.push(e),e.flags|=1);else for(let t=0;t<e.length;t++)$t.push(e[t]);Ul()}function Un(e,t,s=Be+1){for(;s<we.length;s++){const n=we[s];if(n&&n.flags&2){if(e&&n.id!==e.uid)continue;we.splice(s,1),s--,n.flags&4&&(n.flags&=-2),n(),n.flags&4||(n.flags&=-2)}}}function Wl(e){if($t.length){const t=[...new Set($t)].sort((s,n)=>ts(s)-ts(n));if($t.length=0,ht){for(let s=0;s<t.length;s++)ht.push(t[s]);return}for(ht=t,Ft=0;Ft<ht.length;Ft++){const s=ht[Ft];s.flags&4&&(s.flags&=-2),s.flags&8||s(),s.flags&=-2}ht=null,Ft=0}}const ts=e=>e.id==null?e.flags&2?-1:1/0:e.id;function zl(e){try{for(Be=0;Be<we.length;Be++){const t=we[Be];t&&!(t.flags&8)&&(t.flags&4&&(t.flags&=-2),rs(t,t.i,t.i?15:14),t.flags&4||(t.flags&=-2))}}finally{for(;Be<we.length;Be++){const t=we[Be];t&&(t.flags&=-2)}Be=-1,we.length=0,Wl(),Os=null,(we.length||$t.length)&&zl()}}let Ie=null,ql=null;function Ps(e){const t=Ie;return Ie=e,ql=e&&e.type.__scopeId||null,t}function wo(e,t=Ie,s){if(!t||e._n)return e;const n=(...l)=>{n._d&&tl(-1);const i=Ps(t),r=Et.length;let a;try{a=e(...l)}finally{for(let u=Et.length;u>r;u--)mi();Ps(i),n._d&&tl(1)}return a};return n._n=!0,n._c=!0,n._d=!0,n}function It(e,t){if(Ie===null)return e;const s=qs(Ie),n=e.dirs||(e.dirs=[]);for(let l=0;l<t.length;l++){let[i,r,a,u=ee]=t[l];i&&(N(i)&&(i={mounted:i,updated:i}),i.deep&&ot(r),n.push({dir:i,instance:s,value:r,oldValue:void 0,arg:a,modifiers:u}))}return e}function yt(e,t,s,n){const l=e.dirs,i=t&&t.dirs;for(let r=0;r<l.length;r++){const a=l[r];i&&(a.oldValue=i[r].value);let u=a.dir[n];u&&(rt(),Ne(u,s,8,[e.el,a,e,t]),at())}}function So(e,t){if(Se){let s=Se.provides;const n=Se.parent&&Se.parent.provides;n===s&&(s=Se.provides=Object.create(n)),s[e]=t}}function Cs(e,t,s=!1){const n=xr();if(n||Nt){let l=Nt?Nt._context.provides:n?n.parent==null||n.ce?n.vnode.appContext&&n.vnode.appContext.provides:n.parent.provides:void 0;if(l&&e in l)return l[e];if(arguments.length>1)return s&&N(t)?t.call(n&&n.proxy):t}}const Co=Symbol.for("v-scx"),ko=()=>Cs(Co);function en(e,t,s){return Yl(e,t,s)}function Yl(e,t,s=ee){const{immediate:n,deep:l,flush:i,once:r}=s,a=be({},s),u=t&&n||!t&&i!=="post";let g;if(ls){if(i==="sync"){const M=ko();g=M.__watcherHandles||(M.__watcherHandles=[])}else if(!u){const M=()=>{};return M.stop=ze,M.resume=ze,M.pause=ze,M}}const h=Se;a.call=(M,U,A)=>Ne(M,h,U,A);let y=!1;i==="post"?a.scheduler=M=>{ke(M,h&&h.suspense)}:i!=="sync"&&(y=!0,a.scheduler=(M,U)=>{U?M():An(M)}),a.augmentJob=M=>{t&&(M.flags|=4),y&&(M.flags|=2,h&&(M.id=h.uid,M.i=h))};const R=_o(e,t,a);return ls&&(g?g.push(R):u&&R()),R}function To(e,t,s){const n=this.proxy,l=ae(e)?e.includes(".")?Gl(n,e):()=>n[e]:e.bind(n,n);let i;N(t)?i=t:(i=t.handler,s=t);const r=as(this),a=Yl(l,i.bind(n),s);return r(),a}function Gl(e,t){const s=t.split(".");return()=>{let n=e;for(let l=0;l<s.length&&n;l++)n=n[s[l]];return n}}const Eo=Symbol("_vte"),Ks=e=>e.__isTeleport,tn=Symbol("_leaveCb");function Oo(e){let t=e[0];if(e.length>1){for(const s of e)if(s.type!==ut){t=s;break}}return t}function Jl(e){if(!Mn(e))return Ks(e.type)&&e.children?Oo(e.children):e;if(e.component)return e.component.subTree;const{shapeFlag:t,children:s}=e;if(s){if(t&16)return s[0];if(t&32&&N(s.default))return s.default()}}function Rn(e,t){if(e.shapeFlag&6&&e.component){e.transition=t;const s=e.component.subTree;Rn(Ks(s.type)&&Jl(s)||s,t)}else e.shapeFlag&128?(e.ssContent.transition=t.clone(e.ssContent),e.ssFallback.transition=t.clone(e.ssFallback)):e.transition=t}function Xl(e){e.ids=[e.ids[0]+e.ids[2]+++"-",0,0]}function Wn(e,t){let s;return!!((s=Object.getOwnPropertyDescriptor(e,t))&&!s.configurable)}const As=new WeakMap;function Jt(e,t,s,n,l=!1){if($(e)){e.forEach((A,ne)=>Jt(A,t&&($(t)?t[ne]:t),s,n,l));return}if(Xt(n)&&!l){n.shapeFlag&512&&n.type.__asyncResolved&&n.component.subTree.component&&Jt(
Line truncated
|
||||
* @vue/runtime-dom v3.5.41
|
||||
* (c) 2018-present Yuxi (Evan) You and Vue contributors
|
||||
* @license MIT
|
||||
**/let _n;const ll=typeof window<"u"&&window.trustedTypes;if(ll)try{_n=ll.createPolicy("vue",{createHTML:e=>e})}catch{}const Ci=_n?e=>_n.createHTML(e):e=>e,Or="http://www.w3.org/2000/svg",Pr="http://www.w3.org/1998/Math/MathML",nt=typeof document<"u"?document:null,il=nt&&nt.createElement("template"),Ar={insert:(e,t,s)=>{t.insertBefore(e,s||null)},remove:e=>{const t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,s,n)=>{const l=t==="svg"?nt.createElementNS(Or,e):t==="mathml"?nt.createElementNS(Pr,e):s?nt.createElement(e,{is:s}):nt.createElement(e);return e==="select"&&n&&n.multiple!=null&&l.setAttribute("multiple",n.multiple),l},createText:e=>nt.createTextNode(e),createComment:e=>nt.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>nt.querySelector(e),setScopeId(e,t){e.setAttribute(t,"")},insertStaticContent(e,t,s,n,l,i){const r=s?s.previousSibling:t.lastChild;if(l&&(l===i||l.nextSibling))for(;t.insertBefore(l.cloneNode(!0),s),!(l===i||!(l=l.nextSibling)););else{il.innerHTML=Ci(n==="svg"?`<svg>${e}</svg>`:n==="mathml"?`<math>${e}</math>`:e);const a=il.content;if(n==="svg"||n==="mathml"){const u=a.firstChild;for(;u.firstChild;)a.appendChild(u.firstChild);a.removeChild(u)}t.insertBefore(a,s)}return[r?r.nextSibling:t.firstChild,s?s.previousSibling:t.lastChild]}},Rr=Symbol("_vtc");function Mr(e,t,s){const n=e[Rr];n&&(t=(t?[t,...n]:[...n]).join(" ")),t==null?e.removeAttribute("class"):s?e.setAttribute("class",t):e.className=t}const ol=Symbol("_vod"),Ir=Symbol("_vsh"),Fr=Symbol(""),Dr=/(?:^|;)\s*display\s*:/;function Lr(e,t,s){const n=e.style,l=ae(s);let i=!1;if(s&&!l){if(t)if(ae(t))for(const r of t.split(";")){const a=r.slice(0,r.indexOf(":")).trim();s[a]==null&&zt(n,a,"")}else for(const r in t)s[r]==null&&zt(n,r,"");for(const r in s){r==="display"&&(i=!0);const a=s[r];a!=null?Nr(e,r,!ae(t)&&t?t[r]:void 0,a)||zt(n,r,a):zt(n,r,"")}}else if(l){if(t!==s){const r=n[Fr];r&&(s+=";"+r),n.cssText=s,i=Dr.test(s)}}else t&&e.removeAttribute("style");ol in e&&(e[ol]=i?n.display:"",e[Ir]&&(n.display="none"))}const rl=/\s*!important$/;function zt(e,t,s){if($(s))s.forEach(n=>zt(e,t,n));else if(s==null&&(s=""),t.startsWith("--"))e.setProperty(t,s);else{const n=$r(e,t);rl.test(s)?e.setProperty(Ot(n),s.replace(rl,""),"important"):e[n]=s}}const al=["Webkit","Moz","ms"],ln={};function $r(e,t){const s=ln[t];if(s)return s;let n=De(t);if(n!=="filter"&&n in e)return ln[t]=n;n=wl(n);for(let l=0;l<al.length;l++){const i=al[l]+n;if(i in e)return ln[t]=i}return t}function Nr(e,t,s,n){return e.tagName==="TEXTAREA"&&(t==="width"||t==="height")&&ae(n)&&s===n}const cl="http://www.w3.org/1999/xlink";function ul(e,t,s,n,l,i=Hi(t)){n&&t.startsWith("xlink:")?s==null?e.removeAttributeNS(cl,t.slice(6,t.length)):e.setAttributeNS(cl,t,s):s==null||i&&!Cl(s)?e.removeAttribute(t):e.setAttribute(t,i?"":Ye(s)?String(s):s)}function fl(e,t,s,n,l){if(t==="innerHTML"||t==="textContent"){s!=null&&(e[t]=t==="innerHTML"?Ci(s):s);return}const i=e.tagName;if(t==="value"&&i!=="PROGRESS"&&!i.includes("-")){const a=i==="OPTION"?e.getAttribute("value")||"":e.value,u=s==null?e.type==="checkbox"?"on":"":String(s);(a!==u||!("_value"in e))&&(e.value=u),s==null&&e.removeAttribute(t),e._value=s;return}let r=!1;if(s===""||s==null){const a=typeof e[t];a==="boolean"?s=Cl(s):s==null&&a==="string"?(s="",r=!0):a==="number"&&(s=0,r=!0)}try{e[t]=s}catch{}r&&e.removeAttribute(l||t)}function St(e,t,s,n){e.addEventListener(t,s,n)}function jr(e,t,s,n){e.removeEventListener(t,s,n)}const dl=Symbol("_vei");function Hr(e,t,s,n,l=null){const i=e[dl]||(e[dl]={}),r=i[t];if(n&&r)r.value=n;else{const[a,u]=Kr(t);if(n){const g=i[t]=zr(n,l);St(e,a,g,u)}else r&&(jr(e,a,r,u),i[t]=void 0)}}const Vr=/(Once|Passive|Capture)$/,Br=/^on:?(?:Once|Passive|Capture)$/;function Kr(e){let t,s;for(;(s=e.match(Vr))&&!Br.test(e);)t||(t={}),e=e.slice(0,e.length-s[1].length),t[s[1].toLowerCase()]=!0;return[e[2]===":"?e.slice(3):Ot(e.slice(2)),t]}let on=0;const Ur=Promise.resolve(),Wr=()=>on||(Ur.then(()=>on=0),on=Date.now());function zr(e,t){const s=n=>{if(!n._vts)n._vts=Date.now();else if(n._vts<=s.attached)return;const l=s.value;if($(l)){const i=n.stopImmediatePropagation;n.stopImmediatePropagation=()=>{i.call(n),n._stopped=!0};const r=l.slice(),a=[n];for(let u=0;u<r.length&&!n._stopped;u++){const g=r[u];g&&Ne(g,t,5,a)}}else Ne(l,t,5,[n])};return s.value=e,s.attached=Wr(),s}const pl=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,qr=(e,t,s,n,l,i)=>{const r=l==="svg";t==="class"?Mr(e,n,r):t==="style"?Lr(e,s,n):Ds(t)?Ls(t)||Hr(e,t,s,n,i):(t[0]==="."?(t=t.slice(1),!0):t[0]==="^"?(t=t.slice(1),!1):Yr(e,t,n,r))?(fl(e,t,n),!e.tagName.includes("-")&&(t==="value"||t==="checked"||t==="selected")&&ul(e,t,n,r,i,t!=="value")):e._isVueCE&&(Gr(e,t)||e._def.__asyncLoader&&(/[A-Z]/.test(t)||!ae(n)))?fl(e,De(t),n,i,t):(t==="true-value"?e._trueValue=n:t==="false-value"&&(e._fals
Line truncated
|
||||
`))),e[Ct]=Fs(l);const i=n||l.props&&l.props.type==="number";St(e,t?"change":"input",r=>{r.target.composing||e[Ct](rn(e.value,s,i))}),(s||i)&&St(e,"change",()=>{e.value=rn(e.value,s,i)}),t||(St(e,"compositionstart",Jr),St(e,"compositionend",hl),St(e,"change",hl))},mounted(e,{value:t,modifiers:{trim:s,number:n}}){const l=t??"",i=e[xs];delete e[xs],i!==void 0&&(e.type==="text"||e.type==="textarea")&&e.value!==i?e[Ct](rn(e.value,s,n)):e.value=l},beforeUpdate(e,{value:t,oldValue:s,modifiers:{lazy:n,trim:l,number:i}},r){if(e[Ct]=Fs(r),e.composing)return;const a=(i||e.type==="number")&&!/^0\d/.test(e.value)?xn(e.value):e.value,u=t??"";if(a===u)return;const g=e.getRootNode();(g instanceof Document||g instanceof ShadowRoot)&&g.activeElement===e&&e.type!=="range"&&(n&&t===s||l&&e.value.trim()===u)||(e.value=u)}},gl={deep:!0,created(e,t,s){e[Ct]=Fs(s),St(e,"change",()=>{const n=e._modelValue,l=Xr(e),i=e.checked,r=e[Ct];if($(n)){const a=kl(n,l),u=a!==-1;if(i&&!u)r(n.concat(l));else if(!i&&u){const g=[...n];g.splice(a,1),r(g)}}else if($s(n)){const a=new Set(n);i?a.add(l):a.delete(l),r(a)}else r(ki(e,i))})},mounted:vl,beforeUpdate(e,t,s){e[Ct]=Fs(s),vl(e,t,s)}};function vl(e,{value:t,oldValue:s},n){e._modelValue=t;let l;if($(t))l=kl(t,n.props.value)>-1;else if($s(t))l=t.has(n.props.value);else{if(t===s)return;l=os(t,ki(e,!0))}e.checked!==l&&(e.checked=l)}function Xr(e){return"_value"in e?e._value:e.value}function ki(e,t){const s=t?"_trueValue":"_falseValue";return s in e?e[s]:t}const Zr=["ctrl","shift","alt","meta"],Qr={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>"button"in e&&e.button!==0,middle:e=>"button"in e&&e.button!==1,right:e=>"button"in e&&e.button!==2,exact:(e,t)=>Zr.some(s=>e[`${s}Key`]&&!t.includes(s))},ea=(e,t)=>{if(!e)return e;const s=e._withMods||(e._withMods={}),n=t.join(".");return s[n]||(s[n]=((l,...i)=>{for(let r=0;r<t.length;r++){const a=Qr[t[r]];if(a&&a(l,t))return}return e(l,...i)}))},ta=be({patchProp:qr},Ar);let _l;function sa(){return _l||(_l=ar(ta))}const na=((...e)=>{const t=sa().createApp(...e),{mount:s}=t;return t.mount=n=>{const l=ia(n);if(!l)return;const i=t._component;!N(i)&&!i.render&&!i.template&&(i.template=l.innerHTML),l.nodeType===1&&(l.textContent="");const r=s(l,!1,la(l));return l instanceof Element&&(l.removeAttribute("v-cloak"),l.setAttribute("data-v-app","")),r},t});function la(e){if(e instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&e instanceof MathMLElement)return"mathml"}function ia(e){return ae(e)?document.querySelector(e):e}const oa={class:"app-shell"},ra={class:"content",id:"overview"},aa={class:"topbar"},ca={class:"topbar-meta"},ua={class:"as-of"},fa={key:0,class:"state-card"},da={key:1,class:"state-card error-state"},pa={class:"kpi-grid","aria-label":"Signal summary"},ha={class:"kpi-card accent-card"},ga={class:"kpi-value"},va={class:"kpi-foot"},_a={class:"long-count"},ma={class:"short-count"},ba={class:"neutral-count"},ya={class:"kpi-card"},xa={class:"kpi-value"},wa={class:"kpi-foot"},Sa={class:"panel theme-panel",id:"themes"},Ca={class:"panel-header signal-header"},ka={class:"status-tag"},Ta={class:"theme-grid"},Ea={class:"theme-card-head"},Oa={class:"theme-chip"},Pa={class:"theme-label-th"},Aa={class:"theme-surprise"},Ra={class:"theme-surprise-value"},Ma={class:"theme-read"},Ia={key:0,class:"theme-read-value"},Fa={key:1,class:"theme-read-value"},Da={key:2,class:"theme-read-value"},La={key:3,class:"theme-read-value"},$a={key:4,class:"theme-read-value"},Na={key:5,class:"theme-read-value"},ja={key:6,class:"theme-read-value"},Ha={key:7,class:"theme-read-value"},Va={key:8,class:"theme-read-value"},Ba={key:9,class:"theme-read-value"},Ka={key:10,class:"theme-read-value"},Ua={key:11,class:"theme-read-value"},Wa={key:12,class:"theme-read-value"},za={key:13,class:"theme-read-value"},qa={key:0,class:"theme-narrative"},Ya={key:0,class:"macro-panel"},Ga={class:"macro-chips"},Ja={class:"macro-chip"},Xa={class:"macro-chip"},Za={class:"macro-chip"},Qa={class:"macro-chip"},ec={class:"macro-chip"},tc={class:"panel stock-panel",id:"stocks"},sc={class:"panel-header signal-header"},nc={class:"stock-controls"},lc={class:"toggle-filter"},ic={key:0,class:"empty-research"},oc={key:1,class:"table-wrap"},rc={class:"factor-table"},ac=["onClick"],cc={key:1,class:"muted-cell"},uc={class:"combined-cell"},fc={class:"symbol-name"},dc={key:0,class:"muted-cell"},pc={class:"score-cell"},hc={key:0,class:"dividend-dot",title:"จ่ายปันผล"},gc={class:"panel lineage-panel",id:"lineage"},vc={class:"panel-header signal-header"},_c={class:"status-tag"},mc={class:"table-wrap"},bc={class:"source-table"},yc={class:"source-name"},xc={class:"muted-cell"},wc={class:"muted-cell"},Sc={class:"muted-cell"},Cc={class:"muted-cell"},kc={class:"panel sim-panel",id:"suggestion"},Tc={class:"panel-header signal-header"},Ec={class:"status-tag neutral-tag"},Oc
Line truncated
|
||||
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#0b1018" />
|
||||
<title>SET50 Signal Lab</title>
|
||||
<script type="module" crossorigin src="/assets/index-C2MF9WUu.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-BiR2h3Pv.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
+212
-113
@@ -12,14 +12,16 @@ const selectedSymbol = ref(null)
|
||||
const symbolDetail = ref(null)
|
||||
const symbolLoading = ref(false)
|
||||
// backtest
|
||||
const btStart = ref('2024-06-01')
|
||||
const btEnd = ref('2026-06-01')
|
||||
const btStart = ref('')
|
||||
const btEnd = ref('')
|
||||
const btCapital = ref(1000000)
|
||||
const btFreq = ref('monthly')
|
||||
const btFreq = ref('event')
|
||||
const btLoading = ref(false)
|
||||
const btResult = ref(null)
|
||||
const btRuns = ref([])
|
||||
const simMode = ref('backtest')
|
||||
// strict PIT backtest readiness (Task 1)
|
||||
const btReadiness = ref(null)
|
||||
const btUseLedger = ref(true)
|
||||
const simLoading = ref(false)
|
||||
const simResult = ref(null)
|
||||
const dividendOnly = ref(false)
|
||||
@@ -50,6 +52,9 @@ const factorRows = computed(() => factorData.value?.factors ?? [])
|
||||
// real multi-theme dashboard (3 themes + macro + sources)
|
||||
const dashboardThemes = computed(() => dashData.value?.themes ?? [])
|
||||
const dashboardSources = computed(() => dashData.value?.sources ?? [])
|
||||
// data scheduler source-health log (refresh cadence + failure diagnosis)
|
||||
const sourceHealth = ref([])
|
||||
const sourceHealthLoaded = ref(false)
|
||||
const dashboardMacro = computed(() => dashData.value?.macro ?? {})
|
||||
const sourceCount = computed(() => dashboardSources.value.length)
|
||||
const factorCount = computed(() => dashData.value?.source_summary?.factor_keys ?? sourceCount.value)
|
||||
@@ -149,6 +154,22 @@ function formatNumber(value, digits = 2) {
|
||||
return Number(value ?? 0).toFixed(digits)
|
||||
}
|
||||
|
||||
// Per-theme factor audit helpers: verify sum(contribution)/sum(|weight|) = surprise
|
||||
function themeContribSum(rows) {
|
||||
return (rows || []).reduce((s, r) => s + (r.contribution ?? 0), 0)
|
||||
}
|
||||
function themeWeightSum(rows) {
|
||||
return (rows || []).reduce((s, r) => s + Math.abs(r.weight ?? 0), 0)
|
||||
}
|
||||
function themeWeightedAvg(rows) {
|
||||
// only contributing (non-missing) factors count, matching compute_theme_surprises
|
||||
const used = (rows || []).filter((r) => !r.missing && r.normalized != null)
|
||||
const cs = themeContribSum(used)
|
||||
const ws = themeWeightSum(used)
|
||||
if (ws === 0) return null
|
||||
return Math.max(-1, Math.min(1, cs / ws))
|
||||
}
|
||||
|
||||
// map the backend's dividend_method to an honest Thai label/flag
|
||||
function dividendMethodLabel(method) {
|
||||
if (method === 'dated_ledger') return 'ปันผล (ตามวันจริง)'
|
||||
@@ -159,6 +180,23 @@ function dividendIsEstimate(method) {
|
||||
// only dated_ledger rows are real dated cash flows; everything else is an estimate/proxy
|
||||
return method !== 'dated_ledger'
|
||||
}
|
||||
function dividendIsDated(method) {
|
||||
// real dated cash-flow ledger (per-share x qty on actual ex/pay dates)
|
||||
return method === 'dated_ledger'
|
||||
}
|
||||
function dividendBadge(method) {
|
||||
// cls: use classes known to exist in this project (status-tag/neutral-tag/
|
||||
// warning-tag); dated gets an inline green style so "real cash flow" reads
|
||||
// as clearly better than "estimate".
|
||||
if (dividendIsDated(method)) return { label: 'ตามวันจริง', cls: 'status-tag', style: 'background:#1a7f37;color:#fff' }
|
||||
if (method === 'dps_annual_proxy') return { label: 'Proxy (ต่อหุ้น)', cls: 'status-tag warning-tag' }
|
||||
return { label: 'Proxy', cls: 'status-tag warning-tag' }
|
||||
}
|
||||
function dividendFootnote(method) {
|
||||
if (dividendIsDated(method)) return 'ปันผลตามวันจริงจาก ledger (ex-date × จำนวนหุ้น) — กระแสเงินสดจริง'
|
||||
if (method === 'dps_annual_proxy') return 'ประมาณการปันผลต่อหุ้น (DPS ล่าสุด × จำนวนหุ้น) ไม่ใช่กระแสเงินสดตามวันจริง'
|
||||
return 'ประมาณจาก dividend yield ของพอร์ตสุดท้าย ไม่ใช่กระแสเงินสดปันผลจริง'
|
||||
}
|
||||
|
||||
function formatDate(value) {
|
||||
if (!value) return '—'
|
||||
@@ -259,21 +297,11 @@ async function runSimulation() {
|
||||
simLoading.value = true
|
||||
simResult.value = null
|
||||
try {
|
||||
if (simMode.value === 'forward') {
|
||||
// REAL forward lifecycle (not cosmetic): freeze + execute a paper run.
|
||||
simResult.value = await fetchJson('/api/v1/forward', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ capital: Number(simCapital.value), use_pit: false }),
|
||||
})
|
||||
await loadForward()
|
||||
} else {
|
||||
simResult.value = await fetchJson('/api/v1/simulation', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ capital: Number(simCapital.value), mode: 'backtest' }),
|
||||
})
|
||||
}
|
||||
simResult.value = await fetchJson('/api/v1/suggestion', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ capital: Number(simCapital.value) }),
|
||||
})
|
||||
} catch (caught) {
|
||||
notice.value = caught.message
|
||||
} finally {
|
||||
@@ -281,38 +309,6 @@ async function runSimulation() {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- real forward-test lifecycle (durable paper runs) ----
|
||||
const fwdRuns = ref([])
|
||||
const fwdLoading = ref(false)
|
||||
|
||||
async function loadForward() {
|
||||
fwdLoading.value = true
|
||||
try {
|
||||
const body = await fetchJson('/api/v1/forward')
|
||||
fwdRuns.value = body.runs ?? []
|
||||
} catch (caught) {
|
||||
notice.value = caught.message
|
||||
} finally {
|
||||
fwdLoading.value = false
|
||||
}
|
||||
}
|
||||
async function markForward(id) {
|
||||
try {
|
||||
await fetchJson(`/api/v1/forward/${id}/mark`, { method: 'POST' })
|
||||
await loadForward()
|
||||
} catch (caught) {
|
||||
notice.value = caught.message
|
||||
}
|
||||
}
|
||||
async function matureForward(id) {
|
||||
try {
|
||||
await fetchJson(`/api/v1/forward/${id}/mature`, { method: 'POST' })
|
||||
await loadForward()
|
||||
} catch (caught) {
|
||||
notice.value = caught.message
|
||||
}
|
||||
}
|
||||
|
||||
async function loadDashboard() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
@@ -342,7 +338,6 @@ async function loadDashboard() {
|
||||
paperAuthWarning.value = sessionBody.warning || ''
|
||||
backtest.value = backtestBody
|
||||
researchRun.value = researchBody
|
||||
await loadForward() // load durable forward-test runs (not cosmetic)
|
||||
} catch (caught) {
|
||||
error.value = caught.message
|
||||
} finally {
|
||||
@@ -373,16 +368,54 @@ function closeSymbolDetail() {
|
||||
symbolDetail.value = null
|
||||
}
|
||||
|
||||
async function loadBacktestReadiness() {
|
||||
try {
|
||||
const body = await fetchJson('/api/v1/backtest/readiness')
|
||||
btReadiness.value = body
|
||||
// apply recommended defaults only when the user hasn't already picked dates
|
||||
if (!btStart.value && body.recommended_start) btStart.value = body.recommended_start
|
||||
if (!btEnd.value && body.recommended_end) btEnd.value = body.recommended_end
|
||||
} catch { btReadiness.value = null }
|
||||
}
|
||||
|
||||
async function loadSourceHealth() {
|
||||
try {
|
||||
const body = await fetchJson('/api/v1/scheduler/sources')
|
||||
sourceHealth.value = body.sources || []
|
||||
} catch { sourceHealth.value = [] }
|
||||
sourceHealthLoaded.value = true
|
||||
}
|
||||
|
||||
const healthCategoryLabel = (cat) => ({
|
||||
ok: 'ปกติ', network: 'เครือข่ายขัดข้อง', timeout: 'หมดเวลา',
|
||||
http: 'HTTP error', parse: 'รูปแบบข้อมูลผิด', structure: 'หน้าเว็บเปลี่ยนโครงสร้าง',
|
||||
auth: 'สิทธิ์/ยืนยันตัวตน', other: 'อื่น ๆ',
|
||||
})[cat] || cat
|
||||
|
||||
async function copyHealthLine(entry) {
|
||||
const line = `[${entry.at}] ${entry.label} (${entry.key}) — ${entry.ok ? 'OK' : 'FAIL: ' + healthCategoryLabel(entry.category)} ${entry.detail ? '| ' + entry.detail : ''}`
|
||||
try {
|
||||
await navigator.clipboard.writeText(line)
|
||||
notice.value = `คัดลอกสาเหตุของ ${entry.key} แล้ว`
|
||||
} catch {
|
||||
notice.value = line // fallback: show raw text as a notice
|
||||
}
|
||||
}
|
||||
|
||||
function appendHealthRationale(entry) {
|
||||
return entry.ok ? '' : ` (สาเหตุน่าจะ: ${healthCategoryLabel(entry.category)})`
|
||||
}
|
||||
|
||||
async function runBacktest() {
|
||||
btLoading.value = true
|
||||
btResult.value = null
|
||||
try {
|
||||
btResult.value = await fetchJson('/api/v1/backtest', {
|
||||
btResult.value = await fetchJson('/api/v1/backtest/run', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
start: btStart.value, end: btEnd.value,
|
||||
capital: Number(btCapital.value), freq: btFreq.value,
|
||||
capital: Number(btCapital.value), use_ledger: btUseLedger.value,
|
||||
}),
|
||||
})
|
||||
await loadBacktestRuns()
|
||||
@@ -393,7 +426,7 @@ async function runBacktest() {
|
||||
}
|
||||
}
|
||||
async function loadBacktestRuns() {
|
||||
try { btRuns.value = (await fetchJson('/api/v1/backtest/runs')).runs || [] }
|
||||
try { btRuns.value = (await fetchJson('/api/v1/backtest/run')).runs || [] }
|
||||
catch { btRuns.value = [] }
|
||||
}
|
||||
const pnlClass = (net) => net != null ? (net >= 0 ? 'positive-text' : 'negative-text') : ''
|
||||
@@ -459,7 +492,7 @@ async function recordPaperEntry() {
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => { await loadDashboard(); await loadBacktestRuns() })
|
||||
onMounted(async () => { await loadDashboard(); await Promise.all([loadBacktestRuns(), loadBacktestReadiness(), loadSourceHealth()]) })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -480,8 +513,9 @@ onMounted(async () => { await loadDashboard(); await loadBacktestRuns() })
|
||||
<a class="nav-item" href="#signals"><span class="nav-glyph">↗</span>สัญญาณ</a>
|
||||
<a class="nav-item" href="#factors"><span class="nav-glyph">∿</span>ปัจจัย</a>
|
||||
<a class="nav-item" href="#lineage"><span class="nav-glyph">⌁</span>ที่มาข้อมูล</a>
|
||||
<a class="nav-item" href="#health"><span class="nav-glyph">⛨</span>สถานะข้อมูล</a>
|
||||
<a class="nav-item" href="#research-run"><span class="nav-glyph">✓</span>งานวิจัย</a>
|
||||
<a class="nav-item" href="#simulation"><span class="nav-glyph">➛</span>จำลอง</a>
|
||||
<a class="nav-item" href="#suggestion"><span class="nav-glyph">➛</span>จัดสรร</a>
|
||||
</nav>
|
||||
|
||||
<div class="sidebar-footer">
|
||||
@@ -553,7 +587,17 @@ onMounted(async () => { await loadDashboard(); await loadBacktestRuns() })
|
||||
<div v-if="theme.id === 'auto_credit' && theme.read.new_car_sales_yoy != null" class="theme-read-value">{{ formatNumber(theme.read.new_car_sales_yoy) }}% YoY ยอดขายรถ</div>
|
||||
<div v-else-if="theme.id === 'auto_credit' && theme.read.auto_npl_pct != null" class="theme-read-value">NPL {{ formatNumber(theme.read.auto_npl_pct) }}%</div>
|
||||
<div v-else-if="theme.id === 'refining_energy' && (theme.read.quarterly || theme.read.net_profit)" class="theme-read-value">กำไรสุทธิ TOP (รายไตรมาส)</div>
|
||||
<div v-else-if="theme.id === 'refining_energy' && theme.read.irpc_net_margin_pct != null" class="theme-read-value">กำไรสุทธิ IRPC {{ formatNumber(theme.read.irpc_net_margin_pct) }}%</div>
|
||||
<div v-else-if="theme.id === 'tourism'" class="theme-read-value">signal tourism {{ theme.surprise != null ? formatNumber(theme.surprise,2) : '—' }}σ</div>
|
||||
<div v-else-if="theme.id === 'banks' && theme.read.interest_rate_pct != null" class="theme-read-value">ดอกเบี้ย {{ formatNumber(theme.read.interest_rate_pct) }}%</div>
|
||||
<div v-else-if="theme.id === 'banks' && theme.read.bank_npl_pct != null" class="theme-read-value">NPL ภาคการเงิน {{ formatNumber(theme.read.bank_npl_pct) }}%</div>
|
||||
<div v-else-if="(theme.id === 'retail' || theme.id === 'consumer_staples') && theme.read.retail_sales_yoy != null" class="theme-read-value">ยอดขายปลีก {{ formatNumber(theme.read.retail_sales_yoy) }}% YoY</div>
|
||||
<div v-else-if="(theme.id === 'retail' || theme.id === 'consumer_staples') && theme.read.consumer_confidence != null" class="theme-read-value">เชื่อมั่นผู้บริโภค {{ formatNumber(theme.read.consumer_confidence, 1) }}</div>
|
||||
<div v-else-if="theme.id === 'nonbank_finance' && theme.read.consumer_credit != null" class="theme-read-value">สินเชื่อผู้บริโภค {{ formatNumber(theme.read.consumer_credit / 1e6, 2) }} ล้านลบ.</div>
|
||||
<div v-else-if="theme.id === 'nonbank_finance' && theme.read.household_debt_gdp != null" class="theme-read-value">หนี้ครัวเรือน {{ formatNumber(theme.read.household_debt_gdp) }}% GDP</div>
|
||||
<div v-else-if="theme.id === 'property' && theme.read.property_prices_yoy != null" class="theme-read-value">ราคาอสังหา {{ formatNumber(theme.read.property_prices_yoy) }}% YoY</div>
|
||||
<div v-else-if="theme.id === 'telecom_it' && theme.read.business_confidence != null" class="theme-read-value">เชื่อมั่นธุรกิจ {{ formatNumber(theme.read.business_confidence, 1) }}</div>
|
||||
<div v-else-if="theme.id === 'healthcare' && theme.read.consumption_yoy != null" class="theme-read-value">บริโภค {{ formatNumber(theme.read.consumption_yoy) }}% YoY</div>
|
||||
</div>
|
||||
<div v-if="theme.narrative" class="theme-narrative">{{ theme.narrative }}</div>
|
||||
</article>
|
||||
@@ -655,12 +699,12 @@ onMounted(async () => { await loadDashboard(); await loadBacktestRuns() })
|
||||
</section>
|
||||
|
||||
<!-- Sections 01-04 (tourism-only surprise, provenance, signal table, frozen research) removed per user: superseded by the 3-theme panel + sources table above. -->
|
||||
<section class="panel sim-panel" id="simulation">
|
||||
<section class="panel sim-panel" id="suggestion">
|
||||
<div class="panel-header signal-header">
|
||||
<div>
|
||||
<div class="section-kicker">การจำลองการลงทุน</div>
|
||||
<h2>จัดสรรทุน (Simulation)</h2>
|
||||
<p class="panel-subtitle">กรอกทุน และระบบจัดสรรตามสัดส่วน 50 / 20 / 30 — หุ้นที่ทำกำไรได้มากสุดแล้วจ่ายปันผล, หุ้นทำกำไรแต่ไม่ปันผล, และหุ้นปันผลสูงสุด (ไม่ซ้ำ) — ขั้นต่ำ 100 หุ้นต่อตัว.</p>
|
||||
<div class="section-kicker">คำแนะนำการลงทุน</div>
|
||||
<h2>จัดสรรทุน (Suggestion)</h2>
|
||||
<p class="panel-subtitle">กรอกทุน และระบบแนะนำสัดส่วน 50 / 20 / 30 — หุ้นที่ทำกำไรได้มากสุดแล้วจ่ายปันผล, หุ้นทำกำไรแต่ไม่ปันผล, และหุ้นปันผลสูงสุด (ไม่ซ้ำ) — ขั้นต่ำ 100 หุ้นต่อตัว.</p>
|
||||
</div>
|
||||
<span class="status-tag neutral-tag">{{ simResult ? 'ใช้ได้' : 'รอใส่ทุน' }}</span>
|
||||
</div>
|
||||
@@ -669,13 +713,6 @@ onMounted(async () => { await loadDashboard(); await loadBacktestRuns() })
|
||||
<label>ทุน (บาท)</label>
|
||||
<input v-model="simCapital" type="number" min="1000" step="1000" />
|
||||
</div>
|
||||
<div class="sim-field">
|
||||
<label>โหมด</label>
|
||||
<select v-model="simMode">
|
||||
<option value="backtest">Backtest</option>
|
||||
<option value="forward">Forward test</option>
|
||||
</select>
|
||||
</div>
|
||||
<button class="primary-button" :disabled="simLoading" @click="runSimulation">{{ simLoading ? 'กำลังคำนวณ…' : 'คำนวณการจัดสรร' }}</button>
|
||||
</div>
|
||||
|
||||
@@ -722,34 +759,6 @@ onMounted(async () => { await loadDashboard(); await loadBacktestRuns() })
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="!simResult" class="empty-research">กด 'คำนวณการจัดสรร' เพื่อดูว่า 50/20/30 จัดสรรทุนของคุณไปที่หุ้นไหนบ้าง</div>
|
||||
|
||||
<!-- REAL forward-test lifecycle panel (not cosmetic) -->
|
||||
<div v-if="simMode === 'forward'" class="fwd-panel">
|
||||
<div class="section-kicker">Forward Test (Paper) — สัญญาณถูกตรึง ณ เวลาสร้าง</div>
|
||||
<p class="panel-subtitle">สร้าง forward run → สัญญาณ (คะแนน) ถูก freeze ทันทีที่สร้าง แล้ว execute ด้วยราคาหลัง freeze. กด Mark ตามราคาล่าสุด, Mature เพื่อปิด run. เป็น Paper เท่านั้น.</p>
|
||||
<div v-if="fwdRuns.length === 0" class="empty-research muted-cell">ยังไม่มี forward run — กด 'คำนวณการจัดสรร' ข้างบนเพื่อสร้าง</div>
|
||||
<table v-else class="source-table">
|
||||
<thead><tr><th>#</th><th>สถานะ</th><th>ทุน</th><th>ลงทุน</th><th>ถือ</th><th>ผลตอบแทน</th><th>ตรวจ</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="run in fwdRuns.slice().reverse()" :key="run.id">
|
||||
<td class="muted-cell">{{ run.id.slice(0, 12) }}</td>
|
||||
<td>
|
||||
<span class="status-tag" :class="run.status === 'matured' ? 'warning-tag' : (run.status === 'frozen' ? 'neutral-tag' : 'warning-tag')">{{ run.status }}</span>
|
||||
<span v-if="run.non_pit" class="status-tag warning-tag" title="ใช้คะแนนปัจจุบัน ไม่ใช่ PIT">non-PIT</span>
|
||||
</td>
|
||||
<td>{{ formatNumber(run.capital, 0) }}</td>
|
||||
<td class="positive-text">{{ formatNumber(run.invested, 0) }}</td>
|
||||
<td class="muted-cell">{{ Object.keys(run.holdings || {}).join(', ') || '—' }}</td>
|
||||
<td :class="pnlClass(run.net_return)">{{ run.net_return != null ? (run.net_return * 100).toFixed(2) + '%' : '—' }}</td>
|
||||
<td>
|
||||
<button v-if="run.status !== 'matured'" class="primary-btn" style="padding:2px 8px;margin-right:4px" @click="markForward(run.id)">Mark</button>
|
||||
<button v-if="run.status !== 'matured'" class="primary-btn" style="padding:2px 8px" @click="matureForward(run.id)">Mature</button>
|
||||
<span v-else class="muted-cell">ปิดแล้ว</span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel backtest-panel" id="backtest">
|
||||
@@ -757,36 +766,54 @@ onMounted(async () => { await loadDashboard(); await loadBacktestRuns() })
|
||||
<div>
|
||||
<div class="section-kicker">การย้อนทดสอบ</div>
|
||||
<h2>Backtest (ย้อนทดสอบ)</h2>
|
||||
<p class="panel-subtitle">กำหนดช่วงวัน แล้วระบบจัดสรร 50/20/30 ณ วันที่เริ่ม ลงทุนและถือจนถึงวันสิ้นสุด — สรุปกำไร/ขาดทุนจากราคา + เงินปันผล.</p>
|
||||
<p class="panel-subtitle">กำหนดช่วงวัน แล้วระบบจัดสรร 50/20/30 ณ วันที่เริ่ม ลงทุน และปรับพอร์ตตามข้อมูลที่เผยแพร่ใหม่ (event-driven) จนถึงวันสิ้นสุด — สรุปกำไร/ขาดทุนจากราคา + เงินปันผล. มีค่าธรรมเนียม 0.3% ต่อรายการ และปันผลเข้าบัญชีใน 30 วันหลัง ex-date.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="backtest-controls">
|
||||
<label>ตั้งแต่ <input type="date" v-model="btStart" /></label>
|
||||
<label>ถึง <input type="date" v-model="btEnd" /></label>
|
||||
<label>ทุน <input type="number" v-model.number="btCapital" step="100000" /></label>
|
||||
<label>ความถี่
|
||||
<select v-model="btFreq">
|
||||
<option value="monthly">รายเดือน</option>
|
||||
<option value="quarterly">รายไตรมาส</option>
|
||||
</select>
|
||||
<label class="checkbox-label" style="display:flex;align-items:center;gap:6px">
|
||||
<input type="checkbox" v-model="btUseLedger" /> ใช้ ledger ปันผลตามวันที่จริง
|
||||
</label>
|
||||
<button class="primary-btn" :disabled="btLoading" @click="runBacktest">{{ btLoading ? 'กำลังย้อนทดสอบ…' : 'รัน Backtest' }}</button>
|
||||
<button class="primary-btn" :disabled="btLoading || (btReadiness && !btReadiness.ready)" @click="runBacktest">{{ btLoading ? 'กำลังย้อนทดสอบ…' : 'รัน Backtest' }}</button>
|
||||
</div>
|
||||
|
||||
<div v-if="btReadiness && !btReadiness.ready" class="state-card warning-state">
|
||||
<strong>ยังรันย้อนทดสอบแบบ strict PIT ไม่ได้ — ขาดข้อมูล coverage:</strong>
|
||||
<div class="muted-cell" style="margin-top:4px">{{ (btReadiness.missing || []).slice(0, 8).join(', ') }}{{ (btReadiness.missing || []).length > 8 ? '…' : '' }}</div>
|
||||
<div class="muted-cell" style="margin-top:2px">วันเริ่มที่แนะนำ: {{ btReadiness.recommended_start || '—' }} · วันสิ้นสุด: {{ btReadiness.recommended_end || '—' }}</div>
|
||||
</div>
|
||||
|
||||
<div v-if="btResult?.error" class="state-card error-state">{{ btResult.error }}</div>
|
||||
<div v-else-if="btResult" class="backtest-results">
|
||||
<div v-else-if="btResult && !btResult.error" class="backtest-results">
|
||||
<div class="bt-kpi-grid">
|
||||
<div class="bt-kpi"><span>กำไรจากราคา</span><strong :class="pnlClass(btResult.price_pnl)">{{ formatNumber(btResult.price_pnl) }} บาท</strong></div>
|
||||
<div class="bt-kpi"><span>{{ dividendMethodLabel(btResult.dividend_method) }}<span v-if="dividendIsEstimate(btResult.dividend_method)" class="status-tag warning-tag" style="margin-left:6px">Proxy</span></span><strong class="positive-text">{{ formatNumber(btResult.dividend_income) }} บาท</strong></div>
|
||||
<div class="bt-kpi"><span>มูลค่าสุดท้าย</span><strong>{{ formatNumber(btResult.final_value) }} บาท</strong></div>
|
||||
<div class="bt-kpi"><span>กำไรจากราคา (realized)</span><strong :class="pnlClass(btResult.realized_trading_pnl)">{{ formatNumber(btResult.realized_trading_pnl) }} บาท</strong></div>
|
||||
<div class="bt-kpi"><span>กำไรจากราคา (unrealized)</span><strong :class="pnlClass(btResult.unrealized_trading_pnl)">{{ formatNumber(btResult.unrealized_trading_pnl) }} บาท</strong></div>
|
||||
<div class="bt-kpi"><span>เงินปันผลที่ได้รับ</span><strong class="positive-text">{{ formatNumber(btResult.dividend_cash_received) }} บาท</strong></div>
|
||||
<div class="bt-kpi"><span>ค่าธรรมเนียม (0.3%)</span><strong class="negative-text">–{{ formatNumber(btResult.transaction_costs) }} บาท</strong></div>
|
||||
<div class="bt-kpi"><span>เงินปันผลค้างรับ</span><strong>{{ formatNumber(btResult.dividend_receivable) }} บาท</strong></div>
|
||||
<div class="bt-kpi"><span>มูลค่าสุดท้าย (equity)</span><strong>{{ formatNumber(btResult.final_equity) }} บาท</strong></div>
|
||||
<div class="bt-kpi"><span>ผลตอบแทนสุทธิ</span><strong :class="pnlClass(btResult.net_return)">{{ (btResult.net_return * 100).toFixed(2) }}%</strong></div>
|
||||
</div>
|
||||
<div class="bt-meta muted-cell">Trades: {{ btResult.trades }} · ช่วง {{ btResult.start }} → {{ btResult.end }}</div>
|
||||
<div class="bt-meta muted-cell">*{{ dividendIsEstimate(btResult.dividend_method) ? 'ประมาณการปันผล ไม่ใช่กระแสเงินสดปันผลตามวันจริง' : 'ปันผลตามวันจริงจาก ledger (ex-date/per-share)' }}</div>
|
||||
<div v-if="!btResult.leakage_guard" class="bt-meta muted-cell">คำเตือน: ผลนี้ใช้คะแนนปัจจุบันย้อนหลัง จึงเป็น descriptive non-PIT และไม่ใช่หลักฐานประสิทธิภาพกลยุทธ์</div>
|
||||
<div v-if="Object.keys(btResult.holdings || {}).length" class="bt-holdings">
|
||||
<div class="bt-meta muted-cell">Rebalances: {{ btResult.rebalances }} · ปันผลตาม: {{ btResult.dividend_timing }} · ช่วง {{ btResult.start }} → {{ btResult.end }}</div>
|
||||
<div v-if="btResult.leakage_guard" class="bt-meta">✅ strict PIT (leakage guard active)</div>
|
||||
<div v-else class="bt-meta muted-cell">คำเตือน: ไม่ได้พิสูจน์ point-in-time (non-PIT)</div>
|
||||
<div v-if="btResult.holdings && btResult.holdings.length" class="bt-holdings">
|
||||
<strong>พอร์ตสุดท้าย:</strong>
|
||||
<span v-for="(qty, sym) in btResult.holdings" :key="sym" class="theme-tag">{{ sym }} {{ qty }} หุ้น</span>
|
||||
<table class="source-table" style="margin-top:6px">
|
||||
<thead><tr><th>หุ้น</th><th>จำนวน</th><th>ต้นทุนเฉลี่ย</th><th>ราคาล่าสุด</th><th>มูลค่า</th><th>กำไร unrealized</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="h in btResult.holdings" :key="h.symbol">
|
||||
<td class="muted-cell">{{ h.symbol }}</td>
|
||||
<td>{{ h.qty }}</td>
|
||||
<td>{{ formatNumber(h.average_cost, 2) }}</td>
|
||||
<td>{{ formatNumber(h.last_price, 2) }}</td>
|
||||
<td>{{ formatNumber(h.market_value) }}</td>
|
||||
<td :class="pnlClass(h.unrealized_pnl)">{{ formatNumber(h.unrealized_pnl) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="empty-research">กำหนดช่วงวันแล้วกด 'รัน Backtest' เพื่อดูผล (กำไร/ขาดทุนจากราคา + ปันผล)</div>
|
||||
@@ -800,7 +827,7 @@ onMounted(async () => { await loadDashboard(); await loadBacktestRuns() })
|
||||
<td>{{ r.id }}</td><td>{{ r.start }} → {{ r.end }} <span v-if="r.leakage_guard === false" class="status-tag warning-tag" title="ใช้คะแนนปัจจุบันย้อนหลัง ไม่ใช่ point-in-time">descriptive non-PIT</span></td>
|
||||
<td>{{ formatNumber(r.capital) }}</td>
|
||||
<td :class="pnlClass(r.price_pnl)">{{ formatNumber(r.price_pnl) }}</td>
|
||||
<td class="positive-text">{{ formatNumber(r.dividend_income) }}<span v-if="dividendIsEstimate(r.dividend_method)" class="status-tag warning-tag" title="ประมาณการ ไม่ใช่กระแสเงินสดจริง">Proxy</span></td>
|
||||
<td class="positive-text">{{ formatNumber(r.dividend_income) }}<span class="status-tag" :class="dividendBadge(r.dividend_method).cls" :style="dividendBadge(r.dividend_method).style || undefined" style="margin-left:4px" :title="dividendFootnote(r.dividend_method)">{{ dividendBadge(r.dividend_method).label }}</span></td>
|
||||
<td :class="pnlClass(r.net_return)">{{ (r.net_return * 100).toFixed(2) }}%</td>
|
||||
<td class="muted-cell">{{ r.ran_at ? formatDate(r.ran_at) : '—' }}</td>
|
||||
</tr>
|
||||
@@ -809,6 +836,45 @@ onMounted(async () => { await loadDashboard(); await loadBacktestRuns() })
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Health log moved to the very bottom of the page per owner (below
|
||||
Backtest): operational detail, not an investment view. The backend
|
||||
already returns ONE row per source (latest outcome only). -->
|
||||
<section class="panel health-panel" id="health">
|
||||
<div class="panel-header signal-header">
|
||||
<div>
|
||||
<div class="section-kicker">สถานะการดึงข้อมูล</div>
|
||||
<h2>Log — สถานะแหล่งข้อมูล</h2>
|
||||
<p class="panel-subtitle">ผลการดึงข้อมูลครั้งล่าสุดของแต่ละแหล่ง (1 แถวต่อแหล่ง) โดยระบบวิเคราะห์สาเหตุให้อัตโนมัติ (เครือข่าย / หมดเวลา / หน้าเว็บเปลี่ยนโครงสร้าง / รูปแบบข้อมูล เป็นต้น) — กดปุ่ม "คัดลอก" เพื่อ copy สาเหตุไปแจ้ง/ตรวจสอบได้ทันที.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="sourceHealth.length === 0" class="empty-research muted-cell">ยังไม่มี log — รอรอบ refresh ถัดไป (ปกติ ~ทุกวันสำหรับราคา, ~รายเดือน/ไตรมาสสำหรับปัจจัย).</div>
|
||||
<div v-else>
|
||||
<table class="source-table">
|
||||
<thead><tr><th>แหล่ง</th><th>ผลลัพธ์</th><th>สาเหตุ</th><th>เวลา</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="e in sourceHealth" :key="e.key">
|
||||
<td class="source-name">{{ e.label }}<div class="muted-cell" style="font-size:11px">{{ e.key }}</div></td>
|
||||
<td>
|
||||
<span v-if="e.ok" class="status-tag" style="background:#1a7f37;color:#fff">OK</span>
|
||||
<span v-else class="status-tag warning-tag">FAIL</span>
|
||||
</td>
|
||||
<td>
|
||||
<template v-if="e.ok">—</template>
|
||||
<template v-else>
|
||||
<div>{{ healthCategoryLabel(e.category) }}{{ appendHealthRationale(e) }}</div>
|
||||
<div v-if="e.detail" class="muted-cell" style="font-size:11px;word-break:break-word">{{ e.detail.slice(0, 160) }}</div>
|
||||
</template>
|
||||
</td>
|
||||
<td class="muted-cell">{{ e.at ? formatDate(e.at) : '—' }}</td>
|
||||
<td>
|
||||
<button v-if="!e.ok" class="primary-btn" style="padding:2px 8px" @click="copyHealthLine(e)">คัดลอกสาเหตุ</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 05 / บันทึกการวิเคราะห์ removed per user (redundant with theme-panel narratives) -->
|
||||
</template>
|
||||
</main>
|
||||
@@ -841,6 +907,39 @@ onMounted(async () => { await loadDashboard(); await loadBacktestRuns() })
|
||||
<div v-else class="muted-cell">หุ้นนี้ยังไม่ได้จัดอยู่ในธีมใด (จะอัปเดตเมื่อเพิ่มธีม)</div>
|
||||
</div>
|
||||
|
||||
<!-- Per-source factor-level audit: which source scored what, weight how -->
|
||||
<div class="modal-section">
|
||||
<div class="modal-section-title">คะแนนตามแหล่งข้อมูล (factor × weight)</div>
|
||||
<div v-if="symbolDetail.factor_sources && Object.keys(symbolDetail.factor_sources).length">
|
||||
<div v-for="(rows, tid) in symbolDetail.factor_sources" :key="tid" class="modal-sub" style="margin-top:10px">
|
||||
<strong style="color:var(--accent)">{{ themeLabelById[tid] || tid }}</strong>
|
||||
<table class="score-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ข้อมูล (source)</th><th>ค่า raw</th><th>normalized</th><th>weight</th><th>contribution</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="r in rows" :key="r.factor">
|
||||
<td><span :class="r.missing ? 'muted-cell' : ''">{{ r.name_th }}</span><div class="muted-cell" style="font-size:10px">{{ r.source }}</div></td>
|
||||
<td>{{ r.raw != null ? (r.normalized != null && Math.abs(r.normalized) <= 1 && Math.abs(r.raw) < 1000 ? formatNumber(r.raw, 2) : formatNumber(r.raw, 0)) : '—' }}</td>
|
||||
<td>{{ r.normalized != null ? formatNumber(r.normalized, 3) : '—' }}</td>
|
||||
<td>{{ formatNumber(r.weight) }}</td>
|
||||
<td :class="r.contribution != null && r.contribution < 0 ? 'negative-text' : 'positive-text'">{{ r.contribution != null ? formatNumber(r.contribution, 4) : '—' }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<!-- weighted-average verification: sum(contrib) / sum(|weight|) = theme surprise -->
|
||||
<div class="calc-z" style="margin-top:4px">
|
||||
<span v-if="themeWeightedAvg(rows) != null">Σcontrib {{ formatNumber(themeContribSum(rows), 4) }} ÷ Σ{{ '|w|' }} {{ formatNumber(themeWeightSum(rows), 2) }} = ธีม surprise <strong>{{ formatNumber(themeWeightedAvg(rows), 3) }}σ</strong></span>
|
||||
<span v-else class="muted-cell">ยังไม่มีข้อมูล factor</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-sub">normalized = ค่า raw ที่ปรับด้วย sign/center/span อยู่ในช่วง [-1,1]; contribution = weight × normalized; theme surprise = Σcontribution ÷ Σ{{ '|weight|' }}. แหล่งที่ไม่มีข้อมูลจะไม่ถูกนับ (drop source)</div>
|
||||
</div>
|
||||
<div v-else class="muted-cell">ไม่มีข้อมูลแยกตามแหล่ง</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-section">
|
||||
<div class="modal-section-title">มูลค่าพื้นฐาน (Siamchart)</div>
|
||||
<div class="fund-grid">
|
||||
|
||||
+68
-24
@@ -21,6 +21,18 @@
|
||||
--amber-soft: rgba(230, 185, 108, 0.12);
|
||||
--red: #ef8b8b;
|
||||
--red-soft: rgba(239, 139, 139, 0.12);
|
||||
/* aliases the theme/macro/sources/modal components reference — these were
|
||||
written against a design-system variable set that was never declared, so
|
||||
every var() below fell back to invalid and those elements lost their
|
||||
intended background/color. Map them onto the real palette here. */
|
||||
--card: #151f2d; /* card background = panel-soft */
|
||||
--foreground: #edf2f7; /* primary text = --text */
|
||||
--text-2: #a9b2c2; /* secondary text */
|
||||
--font: 'Manrope', ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
|
||||
--accent: #4da3ff; /* blue accent (distinct from mint) */
|
||||
--accent-soft: rgba(77, 163, 255, 0.12);
|
||||
--danger: #ef8b8b; /* = --red */
|
||||
--line-weak: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
@@ -47,7 +59,7 @@ button { cursor: pointer; }
|
||||
.mode-detail, .version-line { margin-top: 3px; color: var(--faint); font: 10px 'DM Mono', monospace; }
|
||||
.version-line { padding: 14px 3px 0; }
|
||||
|
||||
.content { width: min(100%, 1440px); margin: 0 auto; padding: 42px clamp(22px, 4vw, 64px) 70px; }
|
||||
.content { flex: 1 1 auto; min-width: 0; width: min(100%, 1440px); margin: 0 auto; padding: 42px clamp(22px, 4vw, 64px) 70px; }
|
||||
.topbar { display: flex; justify-content: space-between; gap: 24px; align-items: flex-start; padding-bottom: 35px; }
|
||||
.eyebrow, .section-kicker { color: var(--mint); font: 500 10px 'DM Mono', monospace; letter-spacing: .14em; text-transform: uppercase; }
|
||||
h1, h2, p { margin: 0; }
|
||||
@@ -60,19 +72,19 @@ h2 { margin-top: 7px; font-size: 17px; letter-spacing: -.025em; }
|
||||
.freshness-pill.pill-fixture .freshness-dot { background: var(--amber); box-shadow: 0 0 12px var(--amber); }
|
||||
.as-of { margin-top: 10px; }
|
||||
|
||||
.kpi-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin-bottom: 12px; }
|
||||
.kpi-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; margin-bottom: 12px; }
|
||||
.kpi-card, .panel, .state-card { border: 1px solid var(--line); background: linear-gradient(145deg, rgba(21,31,45,.86), rgba(14,21,31,.94)); box-shadow: 0 18px 42px rgba(0,0,0,.12); }
|
||||
.kpi-card { min-height: 132px; padding: 19px 19px 16px; border-radius: 10px; }
|
||||
.kpi-card { min-height: 132px; min-width: 0; padding: 19px 19px 16px; border-radius: 10px; }
|
||||
.accent-card { border-color: rgba(82,214,189,.3); background: linear-gradient(145deg, rgba(25,56,59,.8), rgba(14,31,38,.92)); }
|
||||
.kpi-label { color: var(--muted); font: 10px 'DM Mono', monospace; text-transform: uppercase; letter-spacing: .08em; }
|
||||
.kpi-value { margin-top: 12px; color: var(--text); font-size: 29px; font-weight: 700; letter-spacing: -.055em; }
|
||||
.kpi-label { color: var(--muted); font: 10px 'DM Mono', monospace; text-transform: uppercase; letter-spacing: .08em; overflow-wrap: anywhere; }
|
||||
.kpi-value { margin-top: 12px; color: var(--text); font-size: 29px; font-weight: 700; letter-spacing: -.055em; overflow-wrap: anywhere; }
|
||||
.kpi-unit { margin-left: 4px; color: var(--mint); font: 14px 'DM Mono', monospace; }
|
||||
.quality-value { font-size: 22px; text-transform: capitalize; }
|
||||
.kpi-foot { margin-top: 10px; color: var(--faint); font: 10px 'DM Mono', monospace; }
|
||||
.long-count, .positive-text { color: var(--mint); }
|
||||
.short-count, .negative-text { color: var(--red); }
|
||||
|
||||
.hero-grid, .bottom-grid { display: grid; grid-template-columns: 1.45fr 1fr; gap: 12px; margin-bottom: 12px; }
|
||||
.hero-grid, .bottom-grid { display: grid; grid-template-columns: minmax(0, 1.45fr) minmax(0, 1fr); gap: 12px; margin-bottom: 12px; }
|
||||
.panel { border-radius: 10px; padding: 22px; }
|
||||
.panel-header { display: flex; justify-content: space-between; align-items: flex-start; gap: 20px; }
|
||||
.confidence-tag, .status-tag { padding: 6px 8px; color: var(--mint); border: 1px solid rgba(82,214,189,.22); border-radius: 6px; background: var(--mint-soft); font: 10px 'DM Mono', monospace; white-space: nowrap; }
|
||||
@@ -101,7 +113,19 @@ h2 { margin-top: 7px; font-size: 17px; letter-spacing: -.025em; }
|
||||
.strategy-meta { color: var(--faint); font: 10px 'DM Mono', monospace; }
|
||||
.strategy-meta span { color: var(--line-bright); padding: 0 5px; }
|
||||
.table-wrap { overflow-x: auto; }
|
||||
table { width: 100%; border-collapse: collapse; min-width: 850px; }
|
||||
/* Tables shrink to their container by default (min-width 0) so nothing overflows
|
||||
the card/window. Only the wide stock board (inside .table-wrap) forces 850px
|
||||
and scrolls horizontally. Small tables (source/score) fit 100% width. */
|
||||
table { width: 100%; border-collapse: collapse; min-width: 0; }
|
||||
.factor-table { min-width: 850px; }
|
||||
|
||||
/* Small multi-column tables (source/score) must never push past their parent.
|
||||
min-width:0 on table lets them shrink; overflow-x:auto on the containers is a
|
||||
scroll safety net so long content scrolls instead of breaking the frame. */
|
||||
.modal-card { overflow-x: auto; }
|
||||
.lineage-panel, .sim-panel { min-width: 0; overflow-x: auto; }
|
||||
.source-table, .score-table td { overflow-wrap: anywhere; }
|
||||
|
||||
th { padding: 12px 16px; color: var(--faint); border-bottom: 1px solid var(--line); font: 10px 'DM Mono', monospace; font-weight: 400; text-align: left; text-transform: uppercase; letter-spacing: .06em; }
|
||||
td { padding: 14px 16px; border-bottom: 1px solid rgba(38,51,68,.72); color: var(--muted); font-size: 11px; vertical-align: middle; }
|
||||
tbody tr:last-child td { border-bottom: 0; }
|
||||
@@ -116,9 +140,16 @@ tbody tr:hover { background: rgba(255,255,255,.025); }
|
||||
.reason-code { display: inline-block; margin: 2px 3px 2px 0; padding: 4px 5px; border: 1px solid var(--line-bright); border-radius: 4px; color: var(--faint); font: 9px 'DM Mono', monospace; }
|
||||
|
||||
/* ---- Theme panel (multi-theme) ---- */
|
||||
/* These sections are `class="panel X-panel"` with an inner `.panel-header
|
||||
signal-header`. `.panel` applies 22px padding; `.signal-header` applies its
|
||||
own 22px + bottom border. Without padding:0 the header ends up inset 44px
|
||||
while the body stays at 22px -> header misaligned from content. Zero the
|
||||
panel padding and let the header carry the spacing (matches .stock-panel). */
|
||||
.theme-panel, .lineage-panel, .health-panel, .sim-panel, .backtest-panel,
|
||||
.research-panel { padding: 0; overflow: hidden; }
|
||||
.theme-panel { margin-top: 18px; }
|
||||
.theme-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; }
|
||||
.theme-card { border: 1px solid var(--line-bright); border-radius: 10px; padding: 14px; background: var(--card); }
|
||||
.theme-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; }
|
||||
.theme-card { border: 1px solid var(--line-bright); border-radius: 10px; padding: 14px; background: var(--card); min-width: 0; }
|
||||
.theme-card-head { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
|
||||
.theme-chip { background: var(--accent-soft, rgba(63,161,255,0.12)); color: var(--accent); font: 9px 'DM Mono', monospace; padding: 2px 6px; border-radius: 4px; text-transform: uppercase; }
|
||||
.theme-label-en { font: 600 12px/1.4 var(--font); color: var(--foreground); }
|
||||
@@ -173,7 +204,7 @@ tbody tr:hover { background: rgba(255,255,255,.025); }
|
||||
.contrib-calc em { font-style: normal; color: var(--accent); }
|
||||
.contrib-calc strong { color: var(--mint); font-family: 'DM Mono', monospace; }
|
||||
.contrib-calc { color: var(--text-2, #9aa); font-size: 12px; }
|
||||
.fund-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; font-size: 12px; }
|
||||
.fund-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; font-size: 12px; }
|
||||
.fund-grid span { background: rgba(255,255,255,.03); border-radius: 6px; padding: 6px 8px; }
|
||||
.fund-grid strong { color: var(--text); font-family: 'DM Mono', monospace; }
|
||||
.score-table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
||||
@@ -195,8 +226,8 @@ tbody tr:hover { background: rgba(255,255,255,.025); }
|
||||
.backtest-controls input, .backtest-controls select { background: #0a0e14; border: 1px solid var(--line-bright); color: var(--text); border-radius: 6px; padding: 7px 9px; font-size: 12px; }
|
||||
.primary-btn { background: var(--mint); color: #062a1f; border: none; border-radius: 7px; padding: 9px 16px; font-weight: 700; cursor: pointer; font-size: 12px; }
|
||||
.primary-btn:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.bt-kpi-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin: 12px 0; }
|
||||
.bt-kpi { background: rgba(255,255,255,.03); border: 1px solid var(--line-bright); border-radius: 8px; padding: 12px; }
|
||||
.bt-kpi-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; margin: 12px 0; }
|
||||
.bt-kpi { background: rgba(255,255,255,.03); border: 1px solid var(--line-bright); border-radius: 8px; padding: 12px; min-width: 0; }
|
||||
.bt-kpi span { display: block; font-size: 11px; color: var(--faint); margin-bottom: 6px; }
|
||||
.bt-kpi strong { font-size: 15px; font-family: 'DM Mono', monospace; }
|
||||
.bt-meta { margin: 4px 0 10px; font-size: 11px; }
|
||||
@@ -221,15 +252,17 @@ tbody tr:hover { background: rgba(255,255,255,.025); }
|
||||
.sim-sum span { display: block; font-size: 11px; color: var(--faint); }
|
||||
.sim-sum strong { font-size: 20px; }
|
||||
.sim-note { font-size: 11px; color: var(--amber); font-style: italic; }
|
||||
.sim-buckets { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; }
|
||||
.sim-bucket { border: 1px solid var(--line-bright); border-radius: 8px; padding: 10px; }
|
||||
.sim-buckets { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; min-width: 0; }
|
||||
.sim-bucket { border: 1px solid var(--line-bright); border-radius: 8px; padding: 10px; min-width: 0; overflow: hidden; }
|
||||
.sim-bucket-head { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
|
||||
.sim-bucket-tag { font: 700 10px 'DM Mono', monospace; padding: 2px 6px; border-radius: 4px; }
|
||||
.sim-bucket-tag { font: 700 10px 'DM Mono', monospace; padding: 2px 6px; border-radius: 4px; flex: none; }
|
||||
.sim-bucket-tag.b1 { background: var(--accent-soft, rgba(63,161,255,.15)); color: var(--accent); }
|
||||
.sim-bucket-tag.b2 { background: var(--amber-soft, rgba(245,158,11,.15)); color: var(--amber); }
|
||||
.sim-bucket-tag.b3 { background: var(--mint-soft, rgba(94,234,212,.15)); color: var(--mint); }
|
||||
.sim-order-table { width: 100%; border-collapse: collapse; }
|
||||
.sim-order-table td { padding: 3px 4px; font-size: 12px; }
|
||||
.sim-order-table { width: 100%; table-layout: fixed; border-collapse: collapse; }
|
||||
.sim-order-table td { padding: 3px 4px; font-size: 12px; overflow: hidden; text-overflow: ellipsis; }
|
||||
.sim-order-table td:first-child { text-align: left; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.sim-bucket-head strong { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
|
||||
@media (max-width: 720px) { .sim-buckets { grid-template-columns: 1fr; } }
|
||||
.row-action, .primary-button { padding: 8px 10px; border: 1px solid var(--line-bright); border-radius: 5px; color: var(--text); background: transparent; font-size: 10px; white-space: nowrap; transition: .2s ease; }
|
||||
@@ -249,7 +282,7 @@ th.sortable:hover { color: var(--text); }
|
||||
th.sortable.active { color: var(--mint); }
|
||||
|
||||
.research-panel { margin-bottom: 12px; }
|
||||
.research-grid { display: grid; grid-template-columns: 1fr 1.4fr; gap: 24px; align-items: center; margin-top: 22px; }
|
||||
.research-grid { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr); gap: 24px; align-items: center; margin-top: 22px; }
|
||||
.research-status { display: inline-block; padding: 7px 9px; border-radius: 5px; font: 11px 'DM Mono', monospace; text-transform: uppercase; }
|
||||
.status-ready { color: var(--mint); background: var(--mint-soft); }
|
||||
.status-blocked { color: var(--amber); background: var(--amber-soft); }
|
||||
@@ -259,12 +292,12 @@ th.sortable.active { color: var(--mint); }
|
||||
.gate-list { display: grid; gap: 0; border-top: 1px solid var(--line); }
|
||||
.gate-row { display: flex; justify-content: space-between; gap: 15px; padding: 12px 0; border-bottom: 1px solid var(--line); color: var(--muted); font-size: 11px; }
|
||||
.gate-row strong { color: var(--text); font: 10px 'DM Mono', monospace; text-align: right; }
|
||||
.research-results { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin-top: 18px; }
|
||||
.research-results { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; margin-top: 18px; }
|
||||
.research-result-row { display: grid; gap: 8px; padding: 12px; border: 1px solid var(--line); border-radius: 6px; color: var(--faint); font: 9px 'DM Mono', monospace; }
|
||||
.research-result-row strong { font-size: 14px; }
|
||||
.empty-research { margin-top: 18px; padding: 14px; border: 1px dashed var(--line-bright); border-radius: 6px; color: var(--faint); font: 10px 'DM Mono', monospace; }
|
||||
|
||||
.bottom-grid { grid-template-columns: 1fr 1fr; }
|
||||
.bottom-grid { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); }
|
||||
.thesis-panel { background: linear-gradient(145deg, rgba(36,48,64,.9), rgba(15,23,34,.95)); }
|
||||
.thesis-panel p, .ledger-panel p { margin-top: 14px; color: var(--muted); font-size: 12px; line-height: 1.8; }
|
||||
.thesis-rule { display: flex; align-items: center; gap: 9px; margin-top: 24px; color: var(--mint); font: 10px 'DM Mono', monospace; }
|
||||
@@ -290,7 +323,7 @@ input:focus { border-color: var(--mint); box-shadow: 0 0 0 3px rgba(82,214,189,.
|
||||
|
||||
@media (max-width: 1040px) {
|
||||
.sidebar { width: 208px; flex-basis: 208px; }
|
||||
.kpi-grid { grid-template-columns: repeat(2, 1fr); }
|
||||
.kpi-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
@@ -305,13 +338,24 @@ input:focus { border-color: var(--mint); box-shadow: 0 0 0 3px rgba(82,214,189,.
|
||||
.topbar { display: block; padding-bottom: 25px; }
|
||||
.topbar-meta { display: flex; justify-content: space-between; align-items: center; margin-top: 18px; text-align: left; }
|
||||
.hero-grid, .bottom-grid { grid-template-columns: 1fr; }
|
||||
.panel { padding: 18px; }
|
||||
/* .panel's default 18px must NOT re-pad the section panels (theme/stock/
|
||||
lineage/health/sim/backtest/research) — those keep padding:0 so their
|
||||
.signal-header stays the single source of top spacing; otherwise the
|
||||
header (#1a7f) would sit inset 18px further than the body. */
|
||||
.panel:not(.theme-panel):not(.stock-panel):not(.lineage-panel):not(.health-panel):not(.sim-panel):not(.backtest-panel):not(.research-panel):not(.signal-panel) { padding: 18px; }
|
||||
.signal-header { padding: 18px; }
|
||||
/* Force small multi-column tables (stock factor board is the exception — it
|
||||
intentionally keeps its 850px min-width inside .table-wrap) to fit their
|
||||
narrow container on mobile: fixed layout shrinks columns and wraps content
|
||||
instead of pushing the table past the frame. */
|
||||
.source-table, .score-table { table-layout: fixed; }
|
||||
.source-table th, .source-table td, .score-table th, .score-table td { overflow-wrap: anywhere; word-break: break-word; }
|
||||
.research-grid { grid-template-columns: 1fr; gap: 18px; }
|
||||
.research-results { grid-template-columns: repeat(2, 1fr); }
|
||||
.research-results { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
|
||||
@media (max-width: 500px) {
|
||||
.kpi-grid { grid-template-columns: 1fr 1fr; gap: 7px; }
|
||||
.kpi-grid { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 7px; }
|
||||
.kpi-card { min-height: 112px; padding: 14px; }
|
||||
.kpi-value { font-size: 22px; }
|
||||
.kpi-foot { font-size: 9px; }
|
||||
|
||||
Reference in new issue
Block a user