docs(strategy_pythagoras): spec + plan + summaries dei PDF
Base per l'esecuzione del sub-project strategy_pythagoras: - docs/superpowers/specs/2026-05-19-strategy-pythagoras-design.md (spec) - docs/superpowers/plans/2026-05-19-strategy-pythagoras.md (14 task, 72 step TDD) - src/strategy_pythagoras/Pythagoras/*.summary.md (riassunti numerici dei 2 PDF) - src/strategy_pythagoras/Pythagoras/_extracted/*.txt (estrazione testo grezzo via pypdf) I PDF stessi non vengono committati (vedi .gitignore).
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,343 @@
|
||||
# strategy_pythagoras — Design
|
||||
|
||||
**Data:** 2026-05-19
|
||||
**Autore design:** Adriano Dal Pastro (con Claude/brainstorming)
|
||||
**Stato:** Design approvato per parti 1-4, in attesa di review utente sulla spec consolidata
|
||||
**Audience:** implementatori (Claude executor o umano)
|
||||
|
||||
## 0. Riassunto esecutivo
|
||||
|
||||
Nuovo workspace member `strategy_pythagoras` parallelo a `strategy_crypto`. Replica il pattern coevolutivo GA del monorepo applicato a un dominio diverso: la **scoperta di pattern frattali ricorrenti** sui mercati crypto secondo il framework Pythagoras-Malanga (Fourier + frattali + geometria Evideon), descritto nei due PDF in `src/strategy_pythagoras/Pythagoras/`.
|
||||
|
||||
**Non cambia il genoma del core:** gli agenti restano `HypothesisAgentGenome` e producono `Strategy JSON` nella stessa DSL S-expression. Cambiano:
|
||||
- 7 stili cognitivi Pythagoras-themed (in `prompts.json`)
|
||||
- 3 nuovi indicatori candle (`candle_pattern`, `pythagorean_ratio`, `fractal_mirror`)
|
||||
- Fitness con bonus di asset-invariance BTC↔ETH
|
||||
- Output: strategie JSON freezate + dashboard NiceGUI + report markdown di analisi cross-book
|
||||
|
||||
**Deliverable di chiusura task:** scaffolding completo + 1 GA run short (smoke test) + `docs/analysis_first_run.md` con sintesi numerica e top winners.
|
||||
|
||||
---
|
||||
|
||||
## 1. Architettura
|
||||
|
||||
### Layout package
|
||||
|
||||
```
|
||||
src/strategy_pythagoras/
|
||||
├── pyproject.toml # workspace member, dipende da multi-swarm-core
|
||||
├── README.md
|
||||
├── tests/
|
||||
│ └── test_indicators.py # unit-test per i 3 nuovi indicatori
|
||||
└── strategy_pythagoras/
|
||||
├── __init__.py
|
||||
├── prompts.json # 7 stili Pythagoras-aligned (schema v3.2 di strategy_crypto)
|
||||
├── indicators.py # candle_pattern, pythagorean_ratio, fractal_mirror
|
||||
├── backend/
|
||||
│ ├── __init__.py
|
||||
│ ├── schema.py # tabelle paper_trading_*
|
||||
│ ├── executor.py # PaperExecutor (port da strategy_crypto)
|
||||
│ ├── portfolio.py # Portfolio (port da strategy_crypto)
|
||||
│ └── persistence.py # PaperRepository
|
||||
├── frontend/
|
||||
│ ├── __init__.py
|
||||
│ ├── nicegui_app.py # /strategy_pythagoras_gui
|
||||
│ └── data.py # dual-reader: GA db + paper db + invariance metrics
|
||||
└── strategies/ # JSON winners shippati col package
|
||||
└── (vuoto al t0)
|
||||
```
|
||||
|
||||
### Workspace registration
|
||||
|
||||
In `pyproject.toml` (root):
|
||||
```toml
|
||||
[tool.uv.workspace]
|
||||
members = ["src/multi_swarm_core", "src/strategy_crypto", "src/strategy_pythagoras"]
|
||||
|
||||
[tool.uv.sources]
|
||||
strategy-pythagoras = { workspace = true }
|
||||
```
|
||||
|
||||
Aggiungere `strategy-pythagoras` a `[project].dependencies` per il deployable root.
|
||||
|
||||
### Riuso
|
||||
|
||||
| Componente | Source | Note |
|
||||
|---|---|---|
|
||||
| GA loop, mutation, crossover | `multi_swarm_core.ga` | invariato |
|
||||
| Protocol parser/validator/compiler | `multi_swarm_core.protocol` | esteso con 3 indicatori (vedi §2) |
|
||||
| Backtest engine | `multi_swarm_core.backtest` | invariato |
|
||||
| LLM / OpenRouter / Anthropic clients | `multi_swarm_core.llm` | invariato |
|
||||
| PaperExecutor + Portfolio | `strategy_crypto.backend` | **port** (non import), per isolamento DB |
|
||||
| NiceGUI dashboard shell | `strategy_crypto.frontend` | **port** + adatta tabs |
|
||||
|
||||
### Persistence
|
||||
|
||||
```
|
||||
state/strategy_pythagoras.db # GA: genomi, generazioni, fitness history
|
||||
state/strategy_pythagoras_paper.db # paper-trading post-deploy
|
||||
strategy_pythagoras/strategies/ # JSON winners shippati
|
||||
docs/analysis_first_run.md # report cross-book
|
||||
docs/analysis_runs/<run-id>/ # per-run dump
|
||||
```
|
||||
|
||||
Env vars:
|
||||
- `STRATEGY_PYTHAGORAS_DB_PATH` (default `state/strategy_pythagoras.db`)
|
||||
- `STRATEGY_PYTHAGORAS_PAPER_DB_PATH` (default `state/strategy_pythagoras_paper.db`)
|
||||
- `GA_INVARIANCE_ALPHA` (default 0.3)
|
||||
- `GA_INVARIANCE_TOLERANCE_BARS` (default 36 = ±3h su 5m TF)
|
||||
|
||||
### Routing GUI
|
||||
|
||||
`/strategy_pythagoras_gui` (allinea a [[gui_subpath_routing]] in memory: ogni asset GUI su subpath, root dominio libera).
|
||||
|
||||
### Docker (Phase 2, fuori scope di questa spec)
|
||||
|
||||
Servizi paralleli a quelli di strategy_crypto:
|
||||
- `strategy-pythagoras-paper` (runner)
|
||||
- `strategy-pythagoras-gui` (dashboard)
|
||||
Rete Traefik external, bind mount uid 1000 (vedi [[production_deployment]]).
|
||||
|
||||
---
|
||||
|
||||
## 2. Genoma e DSL
|
||||
|
||||
### Il genoma non cambia
|
||||
|
||||
`HypothesisAgentGenome` di `multi_swarm_core.genome.hypothesis` resta identico:
|
||||
- `system_prompt: str`
|
||||
- `feature_access: list[str]`
|
||||
- `temperature: float`
|
||||
- `top_p: float`
|
||||
- `model_tier: ModelTier`
|
||||
- `lookback_window: int` — vincolo 12 ≤ lw ≤ 200
|
||||
- `cognitive_style: str` — uno dei 7 nuovi stili
|
||||
- `parent_ids, generation, id` — invariati
|
||||
|
||||
### 3 nuovi indicatori (`strategy_pythagoras/indicators.py`)
|
||||
|
||||
| Nome | Params (JSON) | Output | Semantica operativa |
|
||||
|---|---|---|---|
|
||||
| `candle_pattern` | `[seq_str]` es. `"UDU"`, `"UUD0U"` | 1.0 se le ultime k=len(seq_str) candele matchano la sequenza, 0.0 altrimenti | `"U"` = close>open; `"D"` = close<open; `"0"` = `abs(close-open)/open < 0.001` |
|
||||
| `pythagorean_ratio` | `[lookback: int]` | float = `max(close[-lookback:]) / min(close[-lookback:])` | Ratio prezzo, da confrontare con literal vicini a φ=1.618, π=3.1416, √2=1.414, e=2.718 |
|
||||
| `fractal_mirror` | `[k: int, axis: str]` axis ∈ `{"h","v"}` | float ∈ [-1, +1] | Correlazione di Pearson tra ultime k candele e loro mirror: `"h"` = mirror tempo (inversione sequenza); `"v"` = mirror prezzo (1 - close/max) |
|
||||
|
||||
Vincoli del compiler:
|
||||
- `candle_pattern`: `len(seq_str)` ∈ [3, 12], simboli ∈ `{U,D,0}`
|
||||
- `pythagorean_ratio`: `lookback` ∈ [12, 200]
|
||||
- `fractal_mirror`: `k` ∈ [3, 12], `axis` ∈ `{"h","v"}`
|
||||
|
||||
Tutti e 3 vanno aggiunti a `KNOWN_INDICATORS` in `multi_swarm_core.protocol.grammar`.
|
||||
|
||||
### Esempio strategy JSON tipica
|
||||
|
||||
```json
|
||||
{
|
||||
"rules": [
|
||||
{
|
||||
"condition": {
|
||||
"op": "and",
|
||||
"args": [
|
||||
{"op": "eq", "args": [
|
||||
{"kind": "indicator", "name": "candle_pattern", "params": ["UDDU"]},
|
||||
{"kind": "literal", "value": 1.0}
|
||||
]},
|
||||
{"op": "gt", "args": [
|
||||
{"kind": "indicator", "name": "pythagorean_ratio", "params": [89]},
|
||||
{"kind": "literal", "value": 1.618}
|
||||
]}
|
||||
]
|
||||
},
|
||||
"action": "entry-long"
|
||||
},
|
||||
{
|
||||
"condition": {
|
||||
"op": "or", "args": [
|
||||
{"op": "gt", "args": [
|
||||
{"kind": "indicator", "name": "pythagorean_ratio", "params": [89]},
|
||||
{"kind": "literal", "value": 2.618}
|
||||
]},
|
||||
{"op": "crossunder", "args": [
|
||||
{"kind": "indicator", "name": "fractal_mirror", "params": [12, "h"]},
|
||||
{"kind": "literal", "value": 0.0}
|
||||
]}
|
||||
]
|
||||
},
|
||||
"action": "exit"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Vincoli protettivi (anti-overfitting)
|
||||
|
||||
- `lookback_window ≤ 200`
|
||||
- `candle_pattern` seq length ∈ [3, 12] (range 1+2 del Libro dei Frattali)
|
||||
- `time_in_market` monitorato come metric (red flag [[selectivity_red_flag]]); non hard-gate al primo run
|
||||
- Letterali con `pythagorean_ratio`: max 4 decimali (no `1.6180339`)
|
||||
- Max 4 condizioni in AND per regola (eredita da prompts.json)
|
||||
|
||||
---
|
||||
|
||||
## 3. Stili cognitivi (`strategy_pythagoras/prompts.json`)
|
||||
|
||||
### Schema
|
||||
|
||||
Schema v3.2 identico a `strategy_crypto/prompts.json` (campi `_schema`, `_changelog`, `_design_invariants`, `agent_role`, `pattern_guidance`, `instruction`, `domain_warnings`, `anti_patterns`, `output_priorities`, `styles`).
|
||||
|
||||
### `agent_role`
|
||||
|
||||
> Sei un agente di un sistema swarm coevolutivo che cerca pattern frattali ricorrenti sui mercati crypto secondo il framework Pythagoras-Malanga (frattali H-C, trasformata di Fourier, geometria Evideon). Sei parte di una popolazione che esplora collettivamente lo spazio dei pattern: la diversità delle ipotesi è un asset critico. Preferisci esplorare strutture meno ovvie per la tua lente cognitiva. La strategia che produci deve essere riconoscibile come emanata dal tuo stile.
|
||||
|
||||
### `pattern_guidance` (specifico Pythagoras)
|
||||
|
||||
- Sequenze candle 3-12 lunghezza in alfabeto `{U,D,0}` via `candle_pattern`
|
||||
- Mirror H/V come operatori di proiezione via `fractal_mirror`
|
||||
- Ratios di prezzo vicini a φ=1.618, 1/φ=0.618, √2=1.414, π/2=1.571, e/2=1.359 entro tolleranza 0.5%
|
||||
- Pattern composti: pattern lunghi (6-12) come concatenazione di pattern corti (Pattern 13 = Pattern 3 + Pattern 11, p. 53 del paper)
|
||||
- Cicli ricorrenti: stesso pattern firato a distanze regolari (Poincaré)
|
||||
|
||||
### `domain_warnings`
|
||||
|
||||
- Crypto 24/7, no CME gap
|
||||
- I "numeri sacri" (Solfeggio 396-852 Hz, 137.0359, etc.) sono prior teorici, NON leggi: usali come scale candidate, non come dogma
|
||||
- Il paper Pythagoras è esplicitamente non-falsificabile (cita "consapevolezza del trader" come jolly per il fallimento): il backtest è l'unico arbitro
|
||||
- `time_in_market > 80%` red flag (leveraged B&H camuffato)
|
||||
- Tolleranza ±3h del paper → su 5m TF = ±36 barre
|
||||
|
||||
### `anti_patterns`
|
||||
|
||||
- Sequenza `candle_pattern` con `len > 7` simboli vincolati → overfitting
|
||||
- `pythagorean_ratio` con tolleranza > 2% sui literal → numerologia spuriosa
|
||||
- `fractal_mirror` con `k == lookback_window` → tautologico
|
||||
- Letterali con più di 4 decimali
|
||||
- Più di 4 condizioni in AND
|
||||
- Crossover tra indicatori dello stesso tipo con lookback vicini → chattering
|
||||
|
||||
### `output_priorities`
|
||||
|
||||
1. **Coerenza con lente cognitiva** (es. `pythagorean` usa ratios, `candle_grammarian` usa sequenze esplicite)
|
||||
2. **Asset-invariance** (segnali che attivano sia su BTC che su ETH entro ±36 barre)
|
||||
3. **Selettività** (poche entry forti)
|
||||
4. **Composizionalità** (pattern lunghi come somma di corti)
|
||||
5. **Robustezza vs random baseline** (3σ richiesto da `skeptic_quant`)
|
||||
|
||||
### I 7 stili (`styles`)
|
||||
|
||||
Ogni stile mantiene shape v3.2 (directive 800-950 char ASCII-safe, `focus_metrics` 4 voci, ultimo periodo = "Archetipo dominante: X.", lookback range esplicito):
|
||||
|
||||
| `cognitive_style` | Archetipo / Metafora ancorante | `focus_metrics` | Lookback consigliato |
|
||||
|---|---|---|---|
|
||||
| `pythagorean` | Armonia di ratios sacri (φ, π, √2) | `pythagorean_ratio`, `candle_pattern`, `sma_pct`, `realized_vol` | 89-144 |
|
||||
| `fractal_geometer` | Autosimilarità: pattern di 3 candele si ripetono dilatati a 6, 12 | `candle_pattern`, `fractal_mirror`, `atr_pct`, `pythagorean_ratio` | 48-144 |
|
||||
| `fourier_analyst` | Somma di seni: frequenze ricorrenti dominanti | `sma_pct`, `realized_vol`, `candle_pattern`, `atr` | 60-200 |
|
||||
| `evideonic_projector` | Presente = passato proiettato via mirror H+V e scale | `fractal_mirror`, `pythagorean_ratio`, `candle_pattern`, `sma_pct` | 24-96 |
|
||||
| `candle_grammarian` | Lingua di 3 simboli (U,D,0); parole 3-12 lettere | `candle_pattern`, `volume`, `atr`, `realized_vol` | 12-48 |
|
||||
| `recurrence_theorist` | Per Poincaré, eventi tornano: cerca pattern di oggi che firarono ieri | `candle_pattern`, `fractal_mirror`, `pythagorean_ratio`, `sma_pct` | 100-200 |
|
||||
| `skeptic_quant` | Anticorpo all'unfalsifiability: solo edge 3σ vs random | `realized_vol`, `atr_pct`, `sma_pct`, `candle_pattern` | 60-150 |
|
||||
|
||||
Lo `skeptic_quant` è importante: la sua directive richiede esplicitamente che la strategia sia testabile e che il fitness sia confrontato contro random baseline.
|
||||
|
||||
### `_design_invariants`
|
||||
|
||||
Stessa filosofia di v3.2 di strategy_crypto:
|
||||
- ASCII-safe (no Unicode oltre U+007F nelle directive)
|
||||
- Ogni directive chiude con `Archetipo dominante: <metafora>.`
|
||||
- Ogni directive ha range lookback numerico esplicito
|
||||
- Prima frase: `Il mercato e ...`
|
||||
- Lunghezza 800-950 char
|
||||
|
||||
---
|
||||
|
||||
## 4. Fitness, run GA short, deliverable analisi
|
||||
|
||||
### Fitness con bonus invariance
|
||||
|
||||
```
|
||||
fitness(genome) = mean(sharpe_BTC, sharpe_ETH) × (1 + α × invariance_score)
|
||||
|
||||
invariance_score = corr_signal(entries_BTC, entries_ETH, tolerance_bars=GA_INVARIANCE_TOLERANCE_BARS)
|
||||
∈ [0, 1]
|
||||
α = GA_INVARIANCE_ALPHA (default 0.3)
|
||||
```
|
||||
|
||||
`corr_signal` = frazione di entries su BTC che hanno una entry corrispondente su ETH entro ±36 barre (=±3h su 5m TF).
|
||||
|
||||
Implementazione come callback al GA in `multi_swarm_core.ga`, registrata da `strategy_pythagoras` al startup. Il core non sa nulla di Pythagoras: riceve solo la callback.
|
||||
|
||||
### GA run short (smoke test)
|
||||
|
||||
| Parametro | Valore | Note |
|
||||
|---|---|---|
|
||||
| `population_size` | 20 | minimo per 7 stili (~3 per stile) |
|
||||
| `generations` | 5 | smoke test, non training |
|
||||
| `elite_fraction` | 0.2 | top-4 sopravvivono |
|
||||
| `mutation_rate` | 0.3 | invariato vs strategy_crypto |
|
||||
| `crossover_rate` | 0.5 | invariato |
|
||||
| `model_tier` distribuzione | 70% C (qwen-2.5-72b), 30% B (sonnet) | rispetta [[model_qwen_dependency]] |
|
||||
| `dataset` | BTC 5m + ETH 5m da `strategy_crypto/series/` | riusa serie esistenti |
|
||||
| `train_window` | 2024-07 → 2024-12 | copre le date Pythagoras (lug-ago 2024) |
|
||||
| `test_window` | 2025-01 (1 mese) | hold-out per validare invariance |
|
||||
| `name` | `pythagoras-smoke-001` | run id |
|
||||
|
||||
Lo smoke test verifica:
|
||||
1. Workspace member installato in venv (`uv sync` + `uv run python -c "import strategy_pythagoras"`)
|
||||
2. I 3 nuovi indicatori registrati nel grammar e compilabili
|
||||
3. `prompts.json` caricato, 7 stili producono genomi distinti (no collisioni di id)
|
||||
4. Bonus invariance impatta fitness (verifica via log)
|
||||
5. JSON winners atterrano in `strategy_pythagoras/strategies/`
|
||||
6. Dashboard NiceGUI si avvia e legge i due DB
|
||||
|
||||
### Deliverable analisi cross-book
|
||||
|
||||
`docs/analysis_first_run.md` con:
|
||||
|
||||
1. **Sintesi numerica dei riassunti** — riferimenti a `src/strategy_pythagoras/Pythagoras/Pythagoras_Trading_Prediction.summary.md` e `Libro_frattali.summary.md`
|
||||
2. **Top-5 winners** — id, cognitive_style, fitness, sharpe_BTC, sharpe_ETH, invariance_score
|
||||
3. **Pattern frattali emersi** — dump dei `candle_pattern` seq usate, conteggio per stile, % sovrapposizione con spazio teorico dei 57 pattern del Libro
|
||||
4. **Ratios di prezzo emersi** — distribuzione literal usati con `pythagorean_ratio`, distanza dai numeri universali (φ/π/√2/Solfeggio)
|
||||
5. **Cross-asset invariance osservata** — istogramma di `corr_signal` per top genomi
|
||||
6. **Conclusione onesta** — confronto vs random baseline, quanti winners superano sharpe>1.0 su test + invariance>0.3, cosa il framework Pythagoras predice e cosa NON regge al backtest
|
||||
|
||||
Niente "consapevolezza" come jolly. Solo numeri.
|
||||
|
||||
### Dashboard NiceGUI
|
||||
|
||||
`/strategy_pythagoras_gui`:
|
||||
- Tab **Genomes** — winners con stile/sharpe/invariance, click per drill su rules
|
||||
- Tab **Patterns** — heatmap delle sequenze `candle_pattern` emerse, frequenza per stile
|
||||
- Tab **Ratios** — istogramma literal vicini a costanti universali, bins centrati su φ, π, √2, ecc.
|
||||
- Tab **Invariance** — scatter sharpe_BTC vs sharpe_ETH per ogni winner
|
||||
|
||||
---
|
||||
|
||||
## 5. Out-of-scope (esplicito)
|
||||
|
||||
- **Asset oltre BTC/ETH** (Oro/Argento del paper): non in primo run. Estensione futura.
|
||||
- **Range candele oltre 12**: range 3-5 del Libro (12-56 candele). Estensione futura quando lo smoke test conferma stabilità.
|
||||
- **Live trading reale**: solo paper-trading via stesso pattern di strategy_crypto.
|
||||
- **OCR/Vision sulle figure del Libro dei Frattali**: esplicitamente ESCLUSO da request utente ("senza passare alle immagini").
|
||||
- **Modifica del genoma del core**: nessuna modifica a `HypothesisAgentGenome`. Solo extension del grammar (3 indicatori).
|
||||
- **Riferimenti pseudoscientifici operativizzati come legge**: i numeri sacri/Solfeggio sono prior teorici per literal candidati, non vincoli rigidi.
|
||||
|
||||
---
|
||||
|
||||
## 6. Criteri di accettazione
|
||||
|
||||
- [ ] `uv sync` riesce dalla root con `strategy_pythagoras` come member
|
||||
- [ ] `uv run python -c "from strategy_pythagoras.indicators import candle_pattern, pythagorean_ratio, fractal_mirror"` non solleva
|
||||
- [ ] `pytest src/strategy_pythagoras/tests/` verde (almeno unit-test per i 3 indicatori)
|
||||
- [ ] GA short run `pythagoras-smoke-001` completa 5 generazioni senza errori
|
||||
- [ ] Almeno 1 winner con fitness > 0 e `cognitive_style` ∈ {7 stili Pythagoras}
|
||||
- [ ] Dashboard avvia su `http://localhost:PORT/strategy_pythagoras_gui` e mostra winners
|
||||
- [ ] `docs/analysis_first_run.md` esiste e contiene tutte le sezioni elencate in §4
|
||||
|
||||
---
|
||||
|
||||
## 7. Riferimenti
|
||||
|
||||
- [Pythagoras Trading Prediction — riassunto](../../../src/strategy_pythagoras/Pythagoras/Pythagoras_Trading_Prediction.summary.md)
|
||||
- [Libro dei Frattali — riassunto](../../../src/strategy_pythagoras/Pythagoras/Libro_frattali.summary.md)
|
||||
- Memory: [[monorepo_uv_workspace]], [[gui_subpath_routing]], [[ownership_per_modulo]], [[production_deployment]], [[model_qwen_dependency]], [[selectivity_red_flag]]
|
||||
- Template: `src/strategy_crypto/` (paper-trading + GUI), `src/strategy_crypto/strategy_crypto/prompts.json` (schema v3.2)
|
||||
- Core: `src/multi_swarm_core/multi_swarm_core/genome/hypothesis.py`, `multi_swarm_core/protocol/grammar.py`
|
||||
Reference in New Issue
Block a user