mirror of
https://github.com/db9979/wibosim.git
synced 2026-12-05 21:14:09 +01:00
- Instrument GAS (Erdgas, 1 MWh): Heizsaison, Speicherfüllstand als Makrogröße, Gasmarkt-Ereignisse, schwache Ölkopplung - Nachrichtenthema gas (Regeln und LLM-Schema), Gaspreis nicht mehr beim Öl - Wirkung auf Inflation, BIP, Branchen und Bevölkerung (Heizkosten) - Gesetze Gaspreisbremse und Gasspeicherpflicht, Szenario Energiekrise mit Gas - Client: Kurs- und Makroansicht, Hilfe, Glossar, Handbuchkapitel Energie, Admin-Ereignis - Alte Spielstände laden ohne GAS sauber, Tests in gas.test.js - Balancing-Bericht mit GAS und Saisonkurve, Doku in BALANCING.md, API.md, README Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018i4GUhQVoPUusUzxgxLWkK
734 lines
50 KiB
JavaScript
734 lines
50 KiB
JavaScript
// Balancing-Simulation: spielt ganze Saisons mit künstlicher Uhr durch (ohne Netzwerk) und wertet aus:
|
||
// – Kurse aller Instrumente (Spannen, Abstand zum inneren Wert, Volatilität, Spreads, Umsatz, Index)
|
||
// – typische Spielerstrategien (Endvermögen je Strategie über mehrere Seeds)
|
||
// – Ereignishäufigkeiten je Saison (Zentralbank, Zahlen, Übernahmen, Gesetze, Wahlen …)
|
||
// – Wirkung einzelner Schlagzeilen und der Szenarien, Haushalt/Rating über viele Spieljahre
|
||
// – Dauer eines Spieltakts (Ziel: Raspberry Pi, deutlich unter 50 ms)
|
||
//
|
||
// Aufruf (im Ordner server):
|
||
// node scripts/balance.mjs Standard: 4 Echtzeit-Hybrid-Saisons + Schnelltests (~10 min auf 4 Kernen)
|
||
// node scripts/balance.mjs --quick nur Schnelltests (hybride Wirtschaft mit Zeitraffer-Uhr, ~1 min)
|
||
// node scripts/balance.mjs --seeds 8 mehr Echtzeit-Saisons (je ~4–6 min CPU)
|
||
// node scripts/balance.mjs --json out.json Rohdaten zusätzlich als JSON speichern
|
||
// Weitere Schalter: --fast-seeds N (Schnellsaisons je Szenario), --years N (Langlauf Haushalt), --jobs N (Prozesse)
|
||
// --only season,fast,long,effects nur diese Teile · --tage N Echtzeit-Saison nach N Kalendertagen abbrechen
|
||
// --sim-news F simulierte Ticker-Meldungen ×F (0 = aus) · --set '{"pullHalfLifeDays":5}' Spieleinstellungen überschreiben
|
||
// Ergebnisse und Methode: docs/BALANCING.md
|
||
//
|
||
// Technik: Jeder Lauf ist ein eigener Kindprozess mit festem Zufallsstartwert (Math.random wird ersetzt) und
|
||
// künstlicher Uhr (Date.now wird ersetzt, damit Saison, Wahl und Drehbuch der Spieluhr folgen).
|
||
import { fork } from 'node:child_process';
|
||
import fs from 'node:fs';
|
||
import os from 'node:os';
|
||
import path from 'node:path';
|
||
import { fileURLToPath } from 'node:url';
|
||
|
||
const SELF = fileURLToPath(import.meta.url);
|
||
const DAY = 86_400_000;
|
||
|
||
// ====================================================================== Hilfen
|
||
function mulberry32(a) {
|
||
return function () {
|
||
a |= 0; a = (a + 0x6d2b79f5) | 0;
|
||
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||
};
|
||
}
|
||
const mean = (a) => (a.length ? a.reduce((x, y) => x + y, 0) / a.length : NaN);
|
||
const sd = (a) => { if (a.length < 2) return NaN; const m = mean(a); return Math.sqrt(a.reduce((x, y) => x + (y - m) ** 2, 0) / (a.length - 1)); };
|
||
const quant = (a, q) => { if (!a.length) return NaN; const s = [...a].sort((x, y) => x - y); const i = (s.length - 1) * q; const lo = Math.floor(i); return s[lo] + (s[Math.min(s.length - 1, lo + 1)] - s[lo]) * (i - lo); };
|
||
const f = (x, d = 1) => (Number.isFinite(x) ? x.toLocaleString('de-DE', { minimumFractionDigits: d, maximumFractionDigits: d }) : '–');
|
||
const pct = (x, d = 1) => (Number.isFinite(x) ? `${x >= 0 ? '+' : ''}${f(x * 100, d)} %` : '–');
|
||
const pad = (s, n) => String(s).padEnd(n);
|
||
const lpad = (s, n) => String(s).padStart(n);
|
||
|
||
// ====================================================================== Kindprozess: ein Lauf
|
||
async function runJob(job) {
|
||
const rand = mulberry32(job.seed * 7919 + 17);
|
||
Math.random = rand;
|
||
process.env.TIME_MODE = job.mode;
|
||
process.env.NODE_ENV = 'test';
|
||
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'wibosim-bal-'));
|
||
const clock = { t: job.t0 };
|
||
Date.now = () => clock.t;
|
||
|
||
const { settings } = await import('../src/settings.js');
|
||
settings.news.enabled = false;
|
||
if (job.fast) {
|
||
// Hybrid-Voreinstellungen (Quartal, Zentralbank, Konjunkturdaten, Spieljahr, Ticker-Meldungen), aber Zeitraffer-Kalender:
|
||
// ein Handelstag dauert dayMs. Eine Vorlage durchläuft das Verfahren im Hybrid in ~1,4 Kalendertagen ≈ 1 Handelstag.
|
||
const hybridNewsMin = settings.news.simulatedEveryMin;
|
||
Object.assign(settings.game, {
|
||
timeMode: 'turbo', dayMs: job.dayMs, tickMs: 1000, candleMs: 2000, volAuctionSec: 3,
|
||
billVoteMin: job.dayMs / 60_000 / 1.4, seasonDays: (job.seasonTradingDays * job.dayMs) / DAY,
|
||
});
|
||
// Ticker-Meldungen: gleich viele je Handelstag wie im Hybrid (dort rund um die Uhr, ein Handelstag ≈ 1,4 Kalendertage)
|
||
settings.news.simulatedEveryMin = hybridNewsMin > 0 ? (job.dayMs / 60_000) / (((24 * 60) / hybridNewsMin) * 1.4) : 0;
|
||
}
|
||
if (job.simNews !== undefined) settings.news.simulatedEveryMin = job.simNews > 0 ? settings.news.simulatedEveryMin / job.simNews : 0;
|
||
for (const [k, v] of Object.entries(job.overrides ?? {})) settings.game[k] = v;
|
||
const { Store } = await import('../src/store.js');
|
||
const { Game } = await import('../src/game.js');
|
||
const { simulatedNews } = await import('../src/news.js');
|
||
const { analyze } = await import('../src/newsanalysis.js');
|
||
const { applyScenario } = await import('../src/scenarios.js');
|
||
const { COMPANIES } = await import('../src/world.js');
|
||
|
||
const store = new Store(process.env.DATA_DIR);
|
||
if (job.fast) store.backup = () => null; // Zeitraffer: tägliche Sicherung (VACUUM INTO) würde den Lauf nur bremsen
|
||
const g = new Game({ store, now: () => clock.t });
|
||
if (job.scenario && job.scenario !== 'normal') applyScenario(g, job.scenario);
|
||
|
||
try {
|
||
if (job.kind === 'effects') return await effectsJob(job, g, clock, { analyze });
|
||
return await seasonJob(job, g, clock, { simulatedNews, COMPANIES, settings });
|
||
} finally {
|
||
try { store.close(); } catch { /* egal */ }
|
||
fs.rmSync(process.env.DATA_DIR, { recursive: true, force: true });
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------------- Ereignisse zählen
|
||
function classify(n) {
|
||
const id = String(n.id ?? ''), t = n.title ?? '';
|
||
if (id.startsWith('sim-')) return 'Simulierte Meldung';
|
||
if (id.startsWith('halt-')) return null;
|
||
if (id.startsWith('cb-')) return 'Zinsentscheid';
|
||
if (id.startsWith('fg-')) return 'Forward Guidance';
|
||
if (id.startsWith('macro-')) return 'Konjunkturdaten';
|
||
if (id.startsWith('pmi-')) return 'Frühindikatoren';
|
||
if (id.startsWith('earn-')) return 'Quartalszahlen';
|
||
if (id.startsWith('warn-')) return 'Gewinnwarnung';
|
||
if (id.startsWith('oil-')) return t.includes('Petrolia') ? 'Ölkartell' : 'Szenario-Ereignis';
|
||
if (id.startsWith('gasrep-')) return null;
|
||
if (id.startsWith('gas-')) return 'Gasmarkt-Ereignis';
|
||
if (id.startsWith('chain-')) return 'Lieferketten-Kaskade';
|
||
if (id.startsWith('wahl-')) return 'Wahl';
|
||
if (id.startsWith('mv-end-')) return t.includes('erfolgreich') ? 'Misstrauensvotum erfolgreich' : 'Misstrauensvotum gescheitert';
|
||
if (id.startsWith('mv-')) return 'Misstrauensvotum beantragt';
|
||
if (id.startsWith('rating-')) return t.includes(' hebt ') ? 'Rating hoch' : 'Rating runter';
|
||
if (id.startsWith('budget-')) return t.includes('überwunden') ? 'Haushaltskrise vorbei' : 'Haushaltskrise';
|
||
if (id.startsWith('scn-')) return 'Szenario-Ereignis';
|
||
if (id.startsWith('bill-')) return t.includes(' beschließt') ? 'Gesetz: Parlament ja' : 'Gesetz: Parlament nein';
|
||
if (id.startsWith('pol-')) {
|
||
if (t.startsWith('Ausschuss einigt sich')) return 'Gesetz: Kompromiss im Ausschuss';
|
||
if (t.includes('Einspruch')) return 'Gesetz: Länderkammer nein';
|
||
if (t.includes('Normenkontrollklage')) return 'Gesetz: Klage beim Gericht';
|
||
if (t.includes('kippt')) return 'Gesetz: Gericht kippt';
|
||
if (t.includes('weist die Klage ab')) return 'Gesetz: Gericht bestätigt';
|
||
if (t.includes('stimmt zu')) return 'Gesetz: Länderkammer ja';
|
||
return 'Gesetz: sonstiges';
|
||
}
|
||
if (id.startsWith('corp-')) {
|
||
if (t.includes('Kapitalerhöhung')) return 'Kapitalerhöhung';
|
||
if (t.includes('Aktienrückkauf')) return 'Aktienrückkauf';
|
||
if (t.startsWith('Übernahmeangebot')) return 'Übernahmeangebot';
|
||
if (t.startsWith('Übernahme vollzogen')) return 'Übernahme vollzogen';
|
||
if (t.startsWith('Übernahme gescheitert')) return 'Übernahme gescheitert';
|
||
if (t.includes('Ergebnisse der Phase-III')) return 'Studie angekündigt';
|
||
if (t.includes('Studie zu')) return 'Studienergebnis';
|
||
return 'Unternehmen: sonstiges';
|
||
}
|
||
return 'Sonstige Meldung';
|
||
}
|
||
// „Bemerkenswert“: alles, was Spieler als Ereignis wahrnehmen (ohne Ticker-Meldungen, Ankündigungen und Unterbrechungen)
|
||
const RATING_ORDER = ['AAA', 'AA', 'A', 'BBB', 'BB', 'B'];
|
||
const worstRating = (list) => list.reduce((w, r) => (RATING_ORDER.indexOf(r) > RATING_ORDER.indexOf(w) ? r : w), 'AAA');
|
||
const NOT_NOTABLE = new Set(['Simulierte Meldung', 'Forward Guidance', 'Sonstige Meldung', 'Studie angekündigt', 'Gesetz: Kompromiss im Ausschuss', 'Gesetz: Klage beim Gericht', 'Gesetz: sonstiges', 'Unternehmen: sonstiges', 'Misstrauensvotum beantragt']);
|
||
|
||
// ---------------------------------------------------------------------- Strategien
|
||
const STRATS = {
|
||
cash: 'Nur Bargeld (Referenz)',
|
||
buyhold: 'Kaufen & Halten (Index)',
|
||
momentum: 'Trendfolger (Top 3, 5 Tage)',
|
||
news: 'Nachrichtenhändler (nach Requote)',
|
||
news0: 'Nachrichtenhändler (ohne Verzögerung)',
|
||
carry10: 'Anleihen-Carry WIB10',
|
||
carry2: 'Anleihen-Carry WIB2',
|
||
short: 'Leerverkäufer (Index, 1× Kapital)',
|
||
mm: 'Market Maker (Limits beidseitig)',
|
||
arb: 'Übernahme-Arbitrage (Andienung)',
|
||
insider: 'Politik-Insider (3 Spieler, stimmen ab)',
|
||
insider0: 'Politik-Positionierung ohne Stimme',
|
||
random: 'Zufallshändler',
|
||
};
|
||
|
||
function makeStrategies(g, players, ctx) {
|
||
const P = (k) => players.filter((x) => x.strat === k);
|
||
const S = (sym) => g.stocks.get(sym);
|
||
const eq = (p) => g.equity(p);
|
||
const pos = (p, sym) => p.positions[sym]?.qty ?? 0;
|
||
const errors = {};
|
||
const tryOrder = (p, o) => {
|
||
try { return g.placeOrder(p, o); } catch (e) { const k = `${p.strat}: ${e.message.slice(0, 50)}`; errors[k] = (errors[k] ?? 0) + 1; return null; }
|
||
};
|
||
const market = (p, sym, side, qty) => (qty >= 1 ? tryOrder(p, { symbol: sym, side, type: 'market', qty: Math.floor(qty) }) : null);
|
||
const flatten = (p, sym) => { const q = pos(p, sym); if (q > 0) market(p, sym, 'sell', q); else if (q < 0) market(p, sym, 'buy', -q); };
|
||
const cancelSym = (p, sym) => { for (const o of S(sym).book.openOrdersOf(p.id)) try { g.cancelOrder(p, o.id); } catch { /* weg */ } };
|
||
const stocks = COMPANIES_SYMS(g);
|
||
const weights = Object.fromEntries(stocks.map((sym) => [sym, S(sym).price * S(sym).baseShares]));
|
||
const wsum = Object.values(weights).reduce((a, b) => a + b, 0);
|
||
const st = { boughtIndex: new Set(), mmLast: 0, momDay: 0, newsQ: [], newsOpen: [], arbDone: new Set(), insider: null, insider0: null };
|
||
|
||
// Nachrichtenhändler: Wirkung (Richtung des fairen Werts) wird direkt nach der Meldung erkannt
|
||
const origAdd = g.addNews.bind(g);
|
||
g.addNews = (n, apply = true) => {
|
||
const before = new Map([...g.stocks.values()].map((s) => [s.symbol, s.fair]));
|
||
origAdd(n, apply);
|
||
if (!apply || g.market.phase !== 'continuous') return;
|
||
const moves = [];
|
||
for (const s of g.stocks.values()) {
|
||
if (!before.has(s.symbol)) continue;
|
||
const r = s.fair / before.get(s.symbol) - 1;
|
||
if (Math.abs(r) >= 0.004) moves.push({ sym: s.symbol, dir: Math.sign(r), r });
|
||
}
|
||
if (!moves.length) return;
|
||
moves.sort((a, b) => Math.abs(b.r) - Math.abs(a.r));
|
||
const sig = { moves: moves.slice(0, 2), t: ctx.clock.t };
|
||
for (const p of P('news0')) enterNews(p, sig); // ohne Verzögerung: trifft noch die alten Quotes
|
||
st.newsQ.push(sig);
|
||
};
|
||
function enterNews(p, sig) {
|
||
for (const m of sig.moves) {
|
||
if (g.ex.status(S(m.sym)) !== 'continuous') continue;
|
||
const open = st.newsOpen.filter((x) => x.p === p).length;
|
||
if (open >= 4) return;
|
||
const qty = Math.floor((0.2 * eq(p)) / S(m.sym).last);
|
||
if (m.dir < 0 && pos(p, m.sym) > 0) continue;
|
||
const o = market(p, m.sym, m.dir > 0 ? 'buy' : 'sell', qty);
|
||
if (o) st.newsOpen.push({ p, sym: m.sym, until: ctx.clock.t + ctx.newsHoldMs });
|
||
}
|
||
}
|
||
|
||
return {
|
||
errors,
|
||
step() {
|
||
const now = ctx.clock.t;
|
||
const cont = g.market.phase === 'continuous';
|
||
const info = g.phaseInfo;
|
||
const sinceOpen = info ? now - info.openAt : 0;
|
||
const toClose = info ? info.closeAt - now : Infinity;
|
||
if (!cont) return;
|
||
|
||
// --- Kaufen & Halten
|
||
for (const p of P('buyhold')) {
|
||
if (st.boughtIndex.has(p.id)) continue;
|
||
st.boughtIndex.add(p.id);
|
||
const cash = p.cash * 0.97;
|
||
for (const sym of stocks) market(p, sym, 'buy', (cash * weights[sym]) / wsum / S(sym).last);
|
||
}
|
||
// --- Anleihen-Carry
|
||
for (const p of [...P('carry10'), ...P('carry2')]) {
|
||
if (st.boughtIndex.has(p.id)) continue;
|
||
st.boughtIndex.add(p.id);
|
||
const sym = p.strat === 'carry10' ? 'WIB10' : 'WIB2';
|
||
// in Tranchen, damit die Order nicht durch den Korridor fällt
|
||
for (let i = 0; i < 4; i++) market(p, sym, 'buy', (p.cash * 0.97 / (4 - i)) / S(sym).last / 1.01);
|
||
}
|
||
// --- Leerverkäufer
|
||
for (const p of P('short')) {
|
||
if (st.boughtIndex.has(p.id)) continue;
|
||
st.boughtIndex.add(p.id);
|
||
const e0 = eq(p);
|
||
for (const sym of stocks) market(p, sym, 'sell', (e0 * 0.95 * weights[sym]) / wsum / S(sym).last);
|
||
}
|
||
// --- Trendfolger: einmal täglich ~1 h nach Eröffnung, Top 3 nach 5-Tage-Rendite
|
||
if (sinceOpen > ctx.hourMs && st.momDay !== g.day && ctx.closes.length >= 6) {
|
||
st.momDay = g.day;
|
||
const last = ctx.closes.at(-1), prev = ctx.closes.at(-6);
|
||
const ranked = stocks.map((sym) => [sym, last.px[sym] / prev.px[sym] - 1]).sort((a, b) => b[1] - a[1]);
|
||
const top = ranked.slice(0, 3).filter(([, r]) => r > 0).map(([sym]) => sym);
|
||
for (const p of P('momentum')) {
|
||
for (const sym of stocks) if (!top.includes(sym) && pos(p, sym) > 0) market(p, sym, 'sell', pos(p, sym));
|
||
const e = eq(p);
|
||
for (const sym of top) {
|
||
const want = Math.floor((e * 0.95 / 3) / S(sym).last);
|
||
const d = want - pos(p, sym);
|
||
if (d > 0 && d * S(sym).last > 0.02 * e) market(p, sym, 'buy', Math.min(d, Math.floor(p.cash * 0.98 / S(sym).last)));
|
||
else if (d < 0 && -d * S(sym).last > 0.02 * e) market(p, sym, 'sell', -d);
|
||
}
|
||
}
|
||
}
|
||
// --- Nachrichtenhändler (reagiert im nächsten Takt, Quotes sind dann schon angepasst)
|
||
for (const sig of st.newsQ.splice(0)) for (const p of P('news')) enterNews(p, sig);
|
||
for (const x of [...st.newsOpen]) {
|
||
if (now < x.until && toClose > 5 * 60_000 * ctx.timeScale) continue;
|
||
if (g.ex.status(S(x.sym)) !== 'continuous') continue;
|
||
flatten(x.p, x.sym);
|
||
st.newsOpen = st.newsOpen.filter((y) => !(y.p === x.p && y.sym === x.sym));
|
||
}
|
||
// --- Market Maker: alle ~30 s Quotes am besten Geld/Brief, Bestand begrenzt, abends glattstellen
|
||
if (now - st.mmLast >= ctx.mmEveryMs) {
|
||
st.mmLast = now;
|
||
for (const p of P('mm')) {
|
||
const e = eq(p);
|
||
for (const sym of ['RHBK', 'KRMA', 'HLIO', 'STHL']) {
|
||
const s = S(sym);
|
||
cancelSym(p, sym);
|
||
if (g.ex.status(s) !== 'continuous') continue;
|
||
if (toClose < 15 * 60_000 * ctx.timeScale) { flatten(p, sym); continue; }
|
||
const bid = s.book.bestBid(), ask = s.book.bestAsk();
|
||
if (!bid || !ask) continue;
|
||
const q = Math.max(1, Math.floor((0.03 * e) / s.last));
|
||
const inv = pos(p, sym) * s.last;
|
||
if (inv < 0.1 * e) tryOrder(p, { symbol: sym, side: 'buy', type: 'limit', price: bid, qty: q });
|
||
if (inv > -0.1 * e) tryOrder(p, { symbol: sym, side: 'sell', type: 'limit', price: ask, qty: q });
|
||
}
|
||
}
|
||
}
|
||
// --- Übernahme-Arbitrage: Ziel kaufen und andienen
|
||
for (const o of g.corp.offers) {
|
||
if (st.arbDone.has(o.id) || g.ex.status(S(o.target)) !== 'continuous') continue;
|
||
st.arbDone.add(o.id);
|
||
for (const p of P('arb')) {
|
||
const qty = Math.floor(Math.min(0.5 * eq(p), p.cash * 0.97) / S(o.target).last / 1.01);
|
||
market(p, o.target, 'buy', qty);
|
||
const have = pos(p, o.target);
|
||
if (have > 0) try { g.corp.tender(p, o.target, have); } catch { /* egal */ }
|
||
}
|
||
}
|
||
for (const p of P('arb')) for (const sym of stocks) if (pos(p, sym) > 0 && !g.corp.offers.some((o) => o.target === sym) && g.ex.status(S(sym)) === 'continuous') flatten(p, sym);
|
||
// --- Politik-Insider: vor der eigenen Stimme in die begünstigten Branchen, dann geschlossen mit Ja stimmen
|
||
for (const [key, voters] of [['insider', P('insider')], ['insider0', P('insider0')]]) {
|
||
if (!voters.length) continue;
|
||
const cur = g.pol.cur;
|
||
let h = st[key];
|
||
if (h && !g.pol.pipeline.some((e) => e.id === h.id)) {
|
||
// Verfahren beendet (Gesetz oder gescheitert) → alles glattstellen
|
||
for (const p of voters) for (const sym of h.syms) flatten(p, sym);
|
||
if (voters.every((p) => h.syms.every((sym) => pos(p, sym) === 0))) { ctx.insiderLog.push({ key, title: h.title, p0: h.p0, pVote: h.pVote }); st[key] = null; }
|
||
continue;
|
||
}
|
||
if (h || !cur || g.pol.isSecret()) continue;
|
||
const effs = Object.entries(cur.bill.effects).filter(([, v]) => Math.abs(v) >= 0.02);
|
||
if (!effs.length) { st[key] = { id: cur.id, syms: [], title: cur.bill.title, p0: cur.p }; continue; }
|
||
const syms = stocks.filter((sym) => effs.some(([sec]) => S(sym).sector === sec));
|
||
h = st[key] = { id: cur.id, syms, title: cur.bill.title, p0: cur.p };
|
||
for (const p of voters) {
|
||
const e = eq(p);
|
||
for (const sym of syms) {
|
||
const eff = cur.bill.effects[S(sym).sector];
|
||
const qty = (0.8 * e / syms.length) / S(sym).last;
|
||
market(p, sym, eff > 0 ? 'buy' : 'sell', eff > 0 ? Math.min(qty, p.cash * 0.97 / S(sym).last) : qty * 0.6);
|
||
}
|
||
}
|
||
if (key === 'insider') { for (const p of voters) try { g.pol.vote(p, cur.id, true); } catch { /* egal */ } h.pVote = cur.p; }
|
||
}
|
||
// --- Zufallshändler: ~10 Orders je Handelstag, 5–15 % des Depots, auch short
|
||
for (const p of P('random')) {
|
||
if (Math.random() > ctx.randomPerTick) continue;
|
||
const sym = Math.random() < 0.8 ? stocks[Math.floor(Math.random() * stocks.length)] : ['WIB2', 'WIB10', 'OEL', 'GAS', 'GOLD', 'USD'][Math.floor(Math.random() * 6)];
|
||
const s = S(sym);
|
||
if (g.ex.status(s) !== 'continuous') continue;
|
||
const qty = (eq(p) * (0.05 + Math.random() * 0.1)) / s.last;
|
||
const q0 = pos(p, sym);
|
||
if (q0 !== 0 && Math.random() < 0.5) flatten(p, sym);
|
||
else market(p, sym, Math.random() < 0.5 ? 'buy' : 'sell', qty);
|
||
}
|
||
},
|
||
};
|
||
}
|
||
const COMPANIES_SYMS = (g) => [...g.stocks.values()].filter((s) => s.kind === 'stock').map((s) => s.symbol);
|
||
|
||
// ---------------------------------------------------------------------- Saison-Lauf
|
||
async function seasonJob(job, g, clock, { simulatedNews, settings }) {
|
||
const cfg = settings.game;
|
||
const timeScale = job.fast ? job.dayMs / (8.5 * 3_600_000) : 1; // Zeitraffer: Minuten des Handelstags skalieren
|
||
const ctx = {
|
||
clock, closes: [], timeScale, hourMs: 3_600_000 * timeScale, newsHoldMs: 30 * 60_000 * timeScale, mmEveryMs: Math.max(cfg.tickMs, 30_000 * timeScale),
|
||
randomPerTick: 10 / ((job.fast ? job.dayMs * 0.9 : 8.5 * 3_600_000) / cfg.tickMs), insiderLog: [],
|
||
};
|
||
// Spieler
|
||
const players = [];
|
||
if (job.strategies) {
|
||
const plan = { cash: 1, buyhold: 1, momentum: 1, news: 1, news0: 1, carry10: 1, carry2: 1, short: 1, mm: 1, arb: 1, insider: 3, insider0: 1, random: 5 };
|
||
let i = 0;
|
||
for (const [k, n] of Object.entries(plan)) for (let j = 0; j < n; j++) {
|
||
const p = (await g.register({ name: `${k}_${j}_${i++}`.slice(0, 20), password: 'geheim123' })).player;
|
||
p.strat = k;
|
||
players.push(p);
|
||
}
|
||
}
|
||
for (let i = 0; i < (job.idlePlayers ?? 0); i++) await g.register({ name: `idle_${i}`, password: 'geheim123' });
|
||
const strat = job.strategies ? makeStrategies(g, players, ctx) : null;
|
||
// Umsatz je Spieler (für den Ertrag vor Gebühren je Umsatz, z. B. beim Market Maker)
|
||
const turnover = {};
|
||
const origRec = g.recordFill.bind(g);
|
||
g.recordFill = (fl) => { if (fl.qty && fl.price) turnover[fl.owner] = (turnover[fl.owner] ?? 0) + fl.qty * fl.price; return origRec(fl); };
|
||
|
||
// Ereignisse mitschneiden
|
||
const events = {};
|
||
const earnDays = [];
|
||
const origAdd = g.addNews.bind(g);
|
||
g.addNews = (n, apply = true) => {
|
||
const k = classify(n);
|
||
if (k) events[k] = (events[k] ?? 0) + 1;
|
||
if (k === 'Quartalszahlen' && n.symbol) earnDays.push({ sym: n.symbol, day: g.day });
|
||
return origAdd(n, apply);
|
||
};
|
||
const origLog = g.log.bind(g);
|
||
let halts = 0, marketHalts = 0;
|
||
const lawStats = { lesung: 0, enacted: 0, inForce: 0 };
|
||
g.log = (kind, text, extra) => {
|
||
if (kind === 'halt' && text.startsWith('Volatilitätsunterbrechung')) halts++;
|
||
if (kind === 'halt' && text.startsWith('Marktweite')) marketHalts++;
|
||
if (kind === 'policy' && text.includes('Erste Lesung')) lawStats.lesung++;
|
||
if (kind === 'policy' && text.startsWith('Gesetz verkündet')) lawStats.enacted++;
|
||
if (kind === 'policy' && text.startsWith('In Kraft getreten')) lawStats.inForce++;
|
||
return origLog(kind, text, extra);
|
||
};
|
||
// Strategien müssen die eigene Ereignis-Hülle sehen (zuerst gewickelt = innen)
|
||
if (strat) { /* bereits gewickelt */ }
|
||
|
||
// Ausgewertet werden die Instrumente vom Saisonstart; Börsengänge während des Laufs (ipo.js) bleiben außen vor
|
||
const syms = [...g.stocks.keys()];
|
||
const idxSyms = COMPANIES_SYMS(g);
|
||
const insts = () => syms.map((k) => g.stocks.get(k));
|
||
// Startpunkt = erste Eröffnungsauktion (ein Szenario-Sprung vor Saisonbeginn ist für Spieler nicht handelbar)
|
||
let start = null, startFv = null;
|
||
const path_ = Object.fromEntries(syms.map((k) => [k, { min: Infinity, max: 0 }]));
|
||
const devs = Object.fromEntries(syms.map((k) => [k, []]));
|
||
const spreads = Object.fromEntries(syms.map((k) => [k, []]));
|
||
const noQuote = Object.fromEntries(syms.map((k) => [k, 0]));
|
||
const volume = Object.fromEntries(syms.map((k) => [k, []]));
|
||
const yields = { WIB2: [], WIB10: [] };
|
||
const macroPath = [];
|
||
const budgetPath = [];
|
||
// Erdgas: Saisonkurve je Spielmonat (Kurs, innerer Wert, Speicherfüllstand)
|
||
const gasByMonth = Array.from({ length: 12 }, () => ({ n: 0, lnPx: 0, lnFv: 0, fill: 0, norm: 0 }));
|
||
const tickMs = { open: [], closed: [] };
|
||
const closes = ctx.closes;
|
||
let lastDay = g.day;
|
||
let lastSim = clock.t;
|
||
let ticks = 0;
|
||
const simEvery = settings.news.simulatedEveryMin * 60_000;
|
||
const endAt = job.fast ? g.season.startedAt + job.seasons * (g.season.endsAt - g.season.startedAt) - 1000
|
||
: job.calDays ? job.t0 + job.calDays * DAY : g.season.endsAt - 60_000;
|
||
const seasonsSeen = [];
|
||
let seasonN = g.season.n;
|
||
const prevVol = {};
|
||
const recordDay = () => {
|
||
const px = Object.fromEntries(insts().map((s) => [s.symbol, s.prevClose]));
|
||
const idx = idxSyms.reduce((a, sym) => a + px[sym] * g.stocks.get(sym).baseShares, 0);
|
||
closes.push({ day: g.day - 1, px, idx, fv: Object.fromEntries(insts().map((s) => [s.symbol, s.fv])) });
|
||
for (const s of insts()) volume[s.symbol].push(prevVol[s.symbol] ?? 0);
|
||
recordMacro();
|
||
};
|
||
const recordMacro = () => {
|
||
for (const sym of ['WIB2', 'WIB10']) yields[sym].push(g.assets.info(g.stocks.get(sym)).yield);
|
||
const m = g.macro, b = g.gov.budget;
|
||
macroPath.push({ day: g.day, rate: m.rate, infl: m.inflation, gdp: m.gdp, u: m.unemployment, regime: m.regime, sent: m.sentiment, oilFv: g.stocks.get('OEL').fv });
|
||
budgetPath.push({ day: g.day, debt: b.debt, deficit: b.deficit, rating: b.rating, crisis: b.crisis, rp: g.gov.riskPremium() });
|
||
const gs = g.stocks.get('GAS');
|
||
if (gs) {
|
||
const gi = g.assets.gasInfo(0), mi = MONTH_IDX[gi.month], x = gasByMonth[mi];
|
||
x.n++; x.lnPx += Math.log(gs.last); x.lnFv += Math.log(gs.fv); x.fill += gi.storage; x.norm += gi.norm;
|
||
}
|
||
};
|
||
|
||
while (clock.t < endAt) {
|
||
const ph = g.market.phase;
|
||
const open = ['preopen', 'opening', 'continuous', 'closing'].includes(ph) || (g.phaseInfo && g.phaseInfo.phase !== 'closed');
|
||
const dt = open || job.fast ? cfg.tickMs : 30_000;
|
||
clock.t += dt;
|
||
if (simEvery > 0 && clock.t - lastSim >= simEvery) { lastSim = clock.t; g.addNews(simulatedNews()); }
|
||
const t0 = performance.now();
|
||
g.tick();
|
||
const el = performance.now() - t0;
|
||
g.ex.pendingTrades.length = 0; // wie das Gateway (index.js): verteilte Trades und geänderte Depots abholen
|
||
g.drainChanged();
|
||
ticks++;
|
||
(g.market.phase === 'continuous' ? tickMs.open : tickMs.closed).push(el);
|
||
if (g.season.n !== seasonN) { seasonsSeen.push({ n: seasonN }); seasonN = g.season.n; }
|
||
if (!start && g.market.phase === 'continuous') {
|
||
start = Object.fromEntries(insts().map((s) => [s.symbol, s.last]));
|
||
startFv = Object.fromEntries(insts().map((s) => [s.symbol, s.fv]));
|
||
closes.push({ day: g.day, px: { ...start }, idx: idxSyms.reduce((a, sym) => a + start[sym] * g.stocks.get(sym).baseShares, 0), fv: { ...startFv } });
|
||
recordMacro();
|
||
}
|
||
if (g.day !== lastDay) { lastDay = g.day; if (start) recordDay(); }
|
||
for (const s of insts()) prevVol[s.symbol] = s.volume;
|
||
strat?.step();
|
||
if (g.market.phase === 'continuous' && ticks % (job.fast ? 5 : 150) === 0) {
|
||
for (const s of insts()) {
|
||
const b = s.book.bestBid(), a = s.book.bestAsk();
|
||
if (b && a) spreads[s.symbol].push((a - b) / ((a + b) / 2)); else noQuote[s.symbol]++;
|
||
devs[s.symbol].push(Math.log(s.last / s.fv));
|
||
path_[s.symbol].min = Math.min(path_[s.symbol].min, s.last / start[s.symbol]);
|
||
path_[s.symbol].max = Math.max(path_[s.symbol].max, s.last / start[s.symbol]);
|
||
}
|
||
}
|
||
}
|
||
// letzter Schluss
|
||
{ const px = Object.fromEntries(insts().map((s) => [s.symbol, s.close ?? s.last])); closes.push({ day: g.day, px, idx: idxSyms.reduce((a, sym) => a + px[sym] * g.stocks.get(sym).baseShares, 0), fv: Object.fromEntries(insts().map((s) => [s.symbol, s.fv])) }); }
|
||
|
||
// Kennzahlen je Instrument
|
||
const inst = {};
|
||
for (const s of insts()) {
|
||
const px = closes.map((c) => c.px[s.symbol]);
|
||
const rets = px.slice(1).map((p, i) => Math.log(p / px[i]));
|
||
const earnSet = new Set(earnDays.filter((e) => e.sym === s.symbol).map((e) => e.day));
|
||
const earnRets = [], normRets = [];
|
||
closes.slice(1).forEach((c, i) => { (earnSet.has(c.day) ? earnRets : normRets).push(Math.abs(rets[i])); });
|
||
inst[s.symbol] = {
|
||
kind: s.kind, vol: s.vol, start: start[s.symbol], end: s.last, ret: s.last / start[s.symbol] - 1, fvRet: s.fv / startFv[s.symbol] - 1,
|
||
min: path_[s.symbol].min, max: path_[s.symbol].max, realVol: sd(rets) * Math.sqrt(252), maxAbsDay: Math.max(...rets.map(Math.abs)),
|
||
devMean: mean(devs[s.symbol]), devAbs: mean(devs[s.symbol].map(Math.abs)), devMax: devs[s.symbol].reduce((x, y) => Math.max(x, Math.abs(y)), 0),
|
||
endDev: Math.log(s.last / s.fv), spreadBp: mean(spreads[s.symbol]) * 1e4, spreadP95Bp: quant(spreads[s.symbol], 0.95) * 1e4,
|
||
noQuoteShare: noQuote[s.symbol] / Math.max(1, noQuote[s.symbol] + spreads[s.symbol].length), volPerDay: mean(volume[s.symbol]),
|
||
zeroVolDays: volume[s.symbol].filter((v) => v === 0).length, earnAbs: mean(earnRets), normAbs: mean(normRets),
|
||
};
|
||
}
|
||
const idxPath = closes.map((c) => c.idx);
|
||
const idxRets = idxPath.slice(1).map((p, i) => Math.log(p / idxPath[i]));
|
||
let peak = 0, mdd = 0;
|
||
for (const v of idxPath) { peak = Math.max(peak, v); mdd = Math.max(mdd, 1 - v / peak); }
|
||
const strategies = players.map((p) => ({ strat: p.strat, ret: g.equity(p) / settings.game.startCash - 1, trades: p.trades ?? 0, fees: p.fees ?? 0, fines: p.compliance?.finedTotal ?? 0, turnover: turnover[p.id] ?? 0, cash0: settings.game.startCash }));
|
||
const sortT = (a) => [...a].sort((x, y) => x - y);
|
||
const tickStats = (a) => ({ n: a.length, mean: mean(a), p50: quant(a, 0.5), p99: quant(a, 0.99), max: a.reduce((x, y) => Math.max(x, y), 0) });
|
||
return {
|
||
kind: job.kind, seed: job.seed, scenario: job.scenario ?? 'normal', fast: !!job.fast, stratRun: !!job.stratRun, long: !!job.long,
|
||
tradingDays: closes.length - 1, calendarDays: (clock.t - job.t0) / DAY, ticks,
|
||
index: { ret: idxPath.at(-1) / idxPath[0] - 1, dailySd: sd(idxRets), maxAbsDay: Math.max(...idxRets.map(Math.abs)), mdd },
|
||
inst, yields: { WIB2: { start: yields.WIB2[0], end: yields.WIB2.at(-1), min: Math.min(...yields.WIB2), max: Math.max(...yields.WIB2) }, WIB10: { start: yields.WIB10[0], end: yields.WIB10.at(-1), min: Math.min(...yields.WIB10), max: Math.max(...yields.WIB10) } },
|
||
events, lawStats, halts, marketHalts, strategies, errors: strat?.errors ?? {}, insiderLog: ctx.insiderLog,
|
||
macro: { first: macroPath[0], last: macroPath.at(-1), rateMin: Math.min(...macroPath.map((x) => x.rate)), rateMax: Math.max(...macroPath.map((x) => x.rate)), inflMax: Math.max(...macroPath.map((x) => x.infl)), inflMin: Math.min(...macroPath.map((x) => x.infl)), gdpMin: Math.min(...macroPath.map((x) => x.gdp)), gdpMax: Math.max(...macroPath.map((x) => x.gdp)), recessionDays: macroPath.filter((x) => x.regime === 'recession').length },
|
||
budget: { first: budgetPath[0], last: budgetPath.at(-1), debtMax: Math.max(...budgetPath.map((x) => x.debt)), crisisDays: budgetPath.filter((x) => x.crisis).length, ratings: [...new Set(budgetPath.map((x) => x.rating))], worst: worstRating(budgetPath.map((x) => x.rating)), days: budgetPath.length },
|
||
seasons: seasonsSeen.length + 1, gasByMonth,
|
||
tick: { open: tickStats(sortT(tickMs.open)), closed: tickStats(sortT(tickMs.closed)) },
|
||
players: g.players.size,
|
||
};
|
||
}
|
||
|
||
// ---------------------------------------------------------------------- Wirkung einzelner Schlagzeilen
|
||
async function effectsJob(job, g, clock, { analyze }) {
|
||
const step = (n) => { for (let i = 0; i < n; i++) { clock.t += 1000; g.tick(); g.ex.pendingTrades.length = 0; g.drainChanged(); } };
|
||
for (let i = 0; i < 400 && g.market.phase !== 'continuous'; i++) step(1);
|
||
step(5);
|
||
const out = [];
|
||
const watch = ['OEL', 'GAS', 'GOLD', 'USD', 'WIB10', 'WIB2', 'AEGS', 'HLIO', 'VOLT', 'RHBK', 'NVLT', 'STHL', 'KRMA'];
|
||
for (const h of job.headlines) {
|
||
const a = analyze(h.title);
|
||
const mk = (real, k) => ({ id: `eff-${k}-${Math.random()}`, title: h.title, source: 'Test', real, sentiment: a.sentiment, sectors: a.sectors, ts: clock.t, analysis: { by: 'regeln', topics: a.topics, sectorImpact: a.sectorImpact, strength: a.strength, reasons: a.reasons } });
|
||
const snap = () => Object.fromEntries(watch.map((s) => [s, { fair: g.stocks.get(s).fair, fv: g.stocks.get(s).fv }]));
|
||
const b0 = snap();
|
||
g.addNews(mk(true, 1));
|
||
const b1 = snap();
|
||
clock.t += 60_000; // eine Minute später dieselbe Geschichte aus anderer Quelle
|
||
g.addNews(mk(true, 2));
|
||
const b2 = snap();
|
||
const first = {}, follow = {}, fvMove = {};
|
||
for (const s of watch) { first[s] = b1[s].fair / b0[s].fair - 1; follow[s] = b2[s].fair / b1[s].fair - 1; g.econ.refreshFv(); fvMove[s] = g.stocks.get(s).fv / b0[s].fv - 1; }
|
||
out.push({ title: h.title, analysis: { sentiment: a.sentiment, topics: a.topics, strength: a.strength, sectors: a.sectors }, first, follow, fvMove });
|
||
clock.t += 1000; g.tick();
|
||
}
|
||
return { kind: 'effects', seed: job.seed, out };
|
||
}
|
||
|
||
// ====================================================================== Hauptprozess
|
||
function parseArgs() {
|
||
const a = process.argv.slice(2);
|
||
const get = (k, d) => { const i = a.indexOf(k); return i >= 0 ? a[i + 1] : d; };
|
||
return {
|
||
quick: a.includes('--quick'), seeds: Number(get('--seeds', a.includes('--quick') ? 0 : 4)), fastSeeds: Number(get('--fast-seeds', 8)),
|
||
years: Number(get('--years', 12)), jobs: Number(get('--jobs', Math.max(1, os.cpus().length))), json: get('--json', null),
|
||
only: get('--only', null), overrides: JSON.parse(get('--set', '{}')), simNews: a.includes('--sim-news') ? Number(get('--sim-news')) : undefined, calDays: a.includes('--tage') ? Number(get('--tage')) : undefined,
|
||
};
|
||
}
|
||
|
||
function runPool(jobs, n, onDone) {
|
||
return new Promise((resolve) => {
|
||
const results = [];
|
||
let next = 0, running = 0;
|
||
const launch = () => {
|
||
if (next >= jobs.length && running === 0) return resolve(results);
|
||
while (running < n && next < jobs.length) {
|
||
const job = jobs[next++];
|
||
running++;
|
||
const child = fork(SELF, [], { env: { ...process.env, BAL_JOB: JSON.stringify(job) }, execArgv: ['--disable-warning=ExperimentalWarning'], stdio: ['ignore', 'ignore', 'inherit', 'ipc'] });
|
||
let got = false;
|
||
child.on('message', (m) => { got = true; results.push(m); onDone?.(m, results.length, jobs.length); });
|
||
child.on('exit', (code) => { if (!got) { console.error(` Lauf fehlgeschlagen (${job.kind}/${job.scenario ?? ''}/Seed ${job.seed}, Code ${code})`); results.push({ ...job, failed: true }); } running--; launch(); });
|
||
}
|
||
};
|
||
launch();
|
||
});
|
||
}
|
||
|
||
const MONTH_NAMES = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];
|
||
const MONTH_IDX = Object.fromEntries(MONTH_NAMES.map((m, i) => [m, i]));
|
||
const HEADLINES = [
|
||
{ title: 'Ölpreis springt nach OPEC-Förderkürzung auf Jahreshoch', note: 'starke Öl-Meldung' },
|
||
{ title: 'Krieg im Nahen Osten eskaliert – Ölpreis steigt drastisch', note: 'Krieg + Öl' },
|
||
{ title: 'OPEC weitet Fördermenge deutlich aus – Ölpreis fällt', note: 'Öl billiger' },
|
||
{ title: 'Gasspeicher leeren sich schneller als erwartet – Gaspreis steigt kräftig', note: 'Gas teurer' },
|
||
{ title: 'LNG-Lieferungen steigen deutlich – Erdgas wird billiger', note: 'Gas billiger' },
|
||
{ title: 'Friedensabkommen unterzeichnet: Waffenstillstand in Osteuropa', note: 'Frieden' },
|
||
{ title: 'EZB erhöht Leitzins überraschend um 0,5 Prozentpunkte', note: 'Zinsschock' },
|
||
{ title: 'Inflation steigt auf höchsten Stand seit 30 Jahren', note: 'Inflation' },
|
||
{ title: 'Dollar legt kräftig zu', note: 'Dollar' },
|
||
{ title: 'Goldpreis klettert auf Rekordhoch', note: 'Gold' },
|
||
{ title: 'USA verhängen neue Strafzölle auf Autos aus Europa', note: 'Zölle' },
|
||
{ title: 'Arbeitslosigkeit sinkt unerwartet deutlich', note: 'Arbeitsmarkt' },
|
||
{ title: 'Bundesregierung beschließt Haushalt für 2027', note: 'Routinemeldung' },
|
||
];
|
||
|
||
async function main() {
|
||
const A = parseArgs();
|
||
const t0 = Date.now();
|
||
// Montag, 4. Januar 2027, 07:00 Uhr Berlin (keine Feiertage im Januar nach Neujahr)
|
||
const MON = Date.UTC(2027, 0, 4, 6, 0);
|
||
const jobs = [];
|
||
const want = (k) => !A.only || A.only.split(',').includes(k);
|
||
for (let s = 1; s <= A.seeds && want('season'); s++) jobs.push({ kind: 'season', mode: 'hybrid', seed: s, t0: MON, strategies: true, overrides: A.overrides, simNews: A.simNews, calDays: A.calDays });
|
||
const fastBase = { kind: 'season', mode: 'hybrid', fast: true, simNews: A.simNews, dayMs: 60_000, seasonTradingDays: 20, seasons: 1, overrides: A.overrides };
|
||
const SCEN = ['normal', 'zinswende', 'kiblase', 'energiekrise', 'rezession', 'schuldenkrise'];
|
||
if (want('fast')) for (const sc of SCEN) for (let s = 1; s <= A.fastSeeds; s++) jobs.push({ ...fastBase, seed: 100 + s, t0: MON, scenario: sc, strategies: false });
|
||
if (want('fast')) for (let s = 1; s <= A.fastSeeds; s++) jobs.push({ ...fastBase, seed: 300 + s, t0: MON, scenario: 'normal', strategies: true, stratRun: true });
|
||
const yearsSeasons = Math.round((A.years * 84) / 20);
|
||
if (want('long')) for (let s = 1; s <= Math.max(2, Math.round(A.fastSeeds / 2)); s++) jobs.push({ ...fastBase, seed: 500 + s, t0: MON, scenario: 'normal', seasons: yearsSeasons, long: true, overrides: { ...A.overrides, scenario: 'normal' } });
|
||
if (want('long')) for (let s = 1; s <= 2; s++) jobs.push({ ...fastBase, seed: 600 + s, t0: MON, scenario: 'schuldenkrise', seasons: Math.round(yearsSeasons / 2), long: true, overrides: { ...A.overrides, scenario: 'normal' } });
|
||
if (want('effects')) for (let s = 1; s <= 6; s++) jobs.push({ kind: 'effects', mode: 'hybrid', seed: 900 + s, t0: Date.UTC(2027, 0, 5, 9, 0), headlines: HEADLINES });
|
||
|
||
console.log(`WiBoSim-Balancing: ${jobs.length} Läufe auf ${A.jobs} Prozessen …`);
|
||
const res = await runPool(jobs, A.jobs, (m, n, tot) => { if (m.kind === 'season' && !m.fast) console.log(` [${n}/${tot}] Echtzeit-Saison Seed ${m.seed} fertig (${m.ticks.toLocaleString('de-DE')} Takte)`); });
|
||
const ok = res.filter((r) => !r.failed);
|
||
report(ok, A);
|
||
console.log(`\nGesamtdauer ${f((Date.now() - t0) / 60_000, 1)} min`);
|
||
if (A.json) fs.writeFileSync(A.json, JSON.stringify(ok, null, 1));
|
||
}
|
||
|
||
// ---------------------------------------------------------------------- Bericht
|
||
function report(res, A) {
|
||
const hy = res.filter((r) => r.kind === 'season' && !r.fast);
|
||
const fastN = res.filter((r) => r.kind === 'season' && r.fast && !r.long && !r.stratRun && r.scenario === 'normal');
|
||
const fastS = res.filter((r) => r.stratRun);
|
||
const scen = res.filter((r) => r.kind === 'season' && r.fast && !r.long && !r.stratRun);
|
||
const long = res.filter((r) => r.long);
|
||
const eff = res.filter((r) => r.kind === 'effects');
|
||
const H = (t) => console.log(`\n${'='.repeat(100)}\n${t}\n${'='.repeat(100)}`);
|
||
|
||
// ---------------- 1. Kurse
|
||
for (const [label, runs] of [['Echtzeit-Hybrid (echter Kalender, 2-s-Takt)', hy], ['Hybride Wirtschaft im Zeitraffer (60-s-Handelstag)', fastN]]) {
|
||
if (!runs.length) continue;
|
||
H(`1. KURSE – ${label}: ${runs.length} Saison(s) à ${f(mean(runs.map((r) => r.tradingDays)), 0)} Handelstage`);
|
||
console.log(`${pad('Instrument', 8)}${lpad('Ziel-Vol', 9)}${lpad('Ist-Vol', 9)}${lpad('Saison Ø', 10)}${lpad('Min', 8)}${lpad('Max', 8)}${lpad('|Kurs/iW|', 10)}${lpad('max', 7)}${lpad('Spread', 9)}${lpad('ohne Quote', 11)}${lpad('Stück/Tag', 11)}${lpad('Zahlen-Tag', 11)}${lpad('sonst', 7)}`);
|
||
for (const sym of Object.keys(runs[0].inst)) {
|
||
const xs = runs.map((r) => r.inst[sym]);
|
||
console.log(`${pad(sym, 8)}${lpad(pct(xs[0].vol, 0).replace('+', ''), 9)}${lpad(pct(mean(xs.map((x) => x.realVol)), 0).replace('+', ''), 9)}${lpad(pct(mean(xs.map((x) => x.ret))), 10)}${lpad(f(Math.min(...xs.map((x) => x.min)), 2), 8)}${lpad(f(Math.max(...xs.map((x) => x.max)), 2), 8)}${lpad(pct(mean(xs.map((x) => x.devAbs))).replace('+', ''), 10)}${lpad(pct(Math.max(...xs.map((x) => x.devMax)), 0).replace('+', ''), 7)}${lpad(`${f(mean(xs.map((x) => x.spreadBp)), 0)} bp`, 9)}${lpad(pct(mean(xs.map((x) => x.noQuoteShare))).replace('+', ''), 11)}${lpad(f(mean(xs.map((x) => x.volPerDay)), 0), 11)}${lpad(xs[0].kind === 'stock' ? pct(mean(xs.map((x) => x.earnAbs))).replace('+', '') : '', 11)}${lpad(xs[0].kind === 'stock' ? pct(mean(xs.map((x) => x.normAbs))).replace('+', '') : '', 7)}`);
|
||
}
|
||
console.log('Spalten: Ziel-Vol = eingestellte Jahresvolatilität · Ist-Vol = aus Tagesschlusskursen (×√252) · Min/Max = Kurs relativ zum Saisonstart');
|
||
console.log('|Kurs/iW| = mittlere Abweichung des Kurses vom inneren Wert · Spread = mittlerer Geld-Brief-Abstand · Zahlen-Tag/sonst = mittlere |Tagesrendite|');
|
||
const ix = runs.map((r) => r.index);
|
||
console.log(`\nIndex WIBO-10: Saisonrendite Ø ${pct(mean(ix.map((x) => x.ret)))} (Spanne ${pct(Math.min(...ix.map((x) => x.ret)))} … ${pct(Math.max(...ix.map((x) => x.ret)))}), Tages-SD ${pct(mean(ix.map((x) => x.dailySd)), 2).replace('+', '')}, größter Tag ${pct(Math.max(...ix.map((x) => x.maxAbsDay)), 1).replace('+', '')}, max. Rückgang Ø ${pct(mean(ix.map((x) => x.mdd))).replace('+', '')}`);
|
||
for (const sym of ['WIB2', 'WIB10']) {
|
||
const ys = runs.map((r) => r.yields[sym]);
|
||
console.log(`Rendite ${sym}: Start ${f(mean(ys.map((y) => y.start)), 2)} %, Ende Ø ${f(mean(ys.map((y) => y.end)), 2)} %, Spanne ${f(Math.min(...ys.map((y) => y.min)), 2)} … ${f(Math.max(...ys.map((y) => y.max)), 2)} %`);
|
||
}
|
||
console.log(`Volatilitätsunterbrechungen je Saison Ø ${f(mean(runs.map((r) => r.halts)), 1)}, marktweit Ø ${f(mean(runs.map((r) => r.marketHalts)), 2)}`);
|
||
const m = runs.map((r) => r.macro);
|
||
console.log(`Makro: Leitzins ${f(mean(m.map((x) => x.first.rate)), 2)} → ${f(mean(m.map((x) => x.last.rate)), 2)} % (Spanne ${f(Math.min(...m.map((x) => x.rateMin)), 2)} … ${f(Math.max(...m.map((x) => x.rateMax)), 2)}), Inflation ${f(Math.min(...m.map((x) => x.inflMin)), 1)} … ${f(Math.max(...m.map((x) => x.inflMax)), 1)} %, BIP ${f(Math.min(...m.map((x) => x.gdpMin)), 1)} … ${f(Math.max(...m.map((x) => x.gdpMax)), 1)} %, Rezessionstage Ø ${f(mean(m.map((x) => x.recessionDays)), 1)}`);
|
||
}
|
||
|
||
// ---------------- 2. Strategien
|
||
const stratRuns = [...hy.map((r) => ({ r, src: 'hy' })), ...fastS.map((r) => ({ r, src: 'fast' }))];
|
||
for (const [label, src] of [['Echtzeit-Hybrid', 'hy'], ['Zeitraffer (Mikrostruktur grob, nur Richtwert)', 'fast']]) {
|
||
const runs = stratRuns.filter((x) => x.src === src && x.r.strategies.length).map((x) => x.r);
|
||
if (!runs.length) continue;
|
||
H(`2. STRATEGIEN – ${label}: Endvermögen nach einer Saison (${runs.length} Seeds)`);
|
||
console.log(`${pad('Strategie', 40)}${lpad('n', 4)}${lpad('Mittel', 9)}${lpad('Median', 9)}${lpad('Min', 9)}${lpad('Max', 9)}${lpad('SD', 8)}${lpad('>0', 6)}${lpad('Trades', 8)}${lpad('Gebühren', 10)}${lpad('vor Geb.', 10)}${lpad('Bp/Ums.', 9)}`);
|
||
for (const [k, name] of Object.entries(STRATS)) {
|
||
const xs = runs.flatMap((r) => r.strategies.filter((s) => s.strat === k));
|
||
if (!xs.length) continue;
|
||
const r = xs.map((x) => x.ret);
|
||
console.log(`${pad(name, 40)}${lpad(xs.length, 4)}${lpad(pct(mean(r)), 9)}${lpad(pct(quant(r, 0.5)), 9)}${lpad(pct(Math.min(...r)), 9)}${lpad(pct(Math.max(...r)), 9)}${lpad(f(sd(r) * 100, 1), 8)}${lpad(f(r.filter((x) => x > 0).length / r.length * 100, 0) + '%', 6)}${lpad(f(mean(xs.map((x) => x.trades)), 0), 8)}${lpad(f(mean(xs.map((x) => x.fees)), 0) + ' €', 10)}${lpad(pct(mean(xs.map((x) => x.ret + x.fees / x.cash0))), 10)}${lpad(f(mean(xs.filter((x) => x.turnover > 0).map((x) => ((x.ret * x.cash0 + x.fees) / x.turnover) * 1e4)), 1), 9)}`);
|
||
}
|
||
const il = runs.flatMap((r) => r.insiderLog.filter((x) => x.key === 'insider' && x.pVote !== undefined));
|
||
if (il.length) console.log(`Politik-Insider: ${il.length} Vorlagen; Inkrafttretens-Wahrscheinlichkeit vor der Stimme Ø ${pct(mean(il.map((x) => x.p0))).replace('+', '')}, direkt nach den 3 Ja-Stimmen Ø ${pct(mean(il.map((x) => x.pVote))).replace('+', '')}`);
|
||
const errs = {};
|
||
for (const r of runs) for (const [k, v] of Object.entries(r.errors)) errs[k] = (errs[k] ?? 0) + v;
|
||
const top = Object.entries(errs).sort((a, b) => b[1] - a[1]).slice(0, 6);
|
||
if (top.length) console.log(`Abgelehnte Orders (Auswahl): ${top.map(([k, v]) => `${k} ×${v}`).join(' · ')}`);
|
||
}
|
||
|
||
// ---------------- 3. Ereignisse
|
||
for (const [label, runs] of [['Echtzeit-Hybrid', hy], ['Zeitraffer, Szenario „normal“', fastN]]) {
|
||
if (!runs.length) continue;
|
||
H(`3. EREIGNISSE JE SAISON – ${label} (${runs.length} Saisons, Ø ${f(mean(runs.map((r) => r.tradingDays)), 0)} Handelstage)`);
|
||
const keys = [...new Set(runs.flatMap((r) => Object.keys(r.events)))].sort();
|
||
const rows = keys.map((k) => [k, mean(runs.map((r) => r.events[k] ?? 0)), Math.min(...runs.map((r) => r.events[k] ?? 0)), Math.max(...runs.map((r) => r.events[k] ?? 0))]);
|
||
for (let i = 0; i < rows.length; i += 2) {
|
||
const cell = ([k, m, lo, hi]) => `${pad(k, 34)}${lpad(f(m, 1), 6)} (${lo}–${hi})`;
|
||
console.log(`${cell(rows[i])}${rows[i + 1] ? ` ${cell(rows[i + 1])}` : ''}`);
|
||
}
|
||
const notable = runs.map((r) => Object.entries(r.events).filter(([k]) => !NOT_NOTABLE.has(k)).reduce((a, [, v]) => a + v, 0));
|
||
const days = mean(runs.map((r) => r.tradingDays));
|
||
console.log(`Gesetze: Erste Lesung Ø ${f(mean(runs.map((r) => r.lawStats.lesung)), 1)}, verkündet Ø ${f(mean(runs.map((r) => r.lawStats.enacted)), 1)}, in Kraft getreten Ø ${f(mean(runs.map((r) => r.lawStats.inForce)), 1)}`);
|
||
console.log(`Bemerkenswerte Ereignisse: Ø ${f(mean(notable), 0)} je Saison = ${f(mean(notable) / days, 1)} je Handelstag = eines alle ${f((days * 8.5) / mean(notable), 1)} Handelsstunden (ohne Ticker-Meldungen, Ankündigungen und Unterbrechungen)`);
|
||
}
|
||
|
||
// ---------------- 4. Wirkung
|
||
if (eff.length) {
|
||
H(`4a. WIRKUNG EINZELNER SCHLAGZEILEN auf den fairen Wert (Sofortsprung, Mittel aus ${eff.length} Läufen; Folgemeldung = dieselbe Meldung 1 min später aus anderer Quelle)`);
|
||
const cols = ['OEL', 'GAS', 'GOLD', 'USD', 'WIB10', 'AEGS', 'HLIO', 'STHL', 'VOLT', 'RHBK', 'NVLT', 'KRMA'];
|
||
console.log(`${pad('Schlagzeile', 58)}${cols.map((c) => lpad(c, 7)).join('')}${lpad('Folge OEL', 10)}${lpad('iW OEL', 8)}`);
|
||
for (let i = 0; i < eff[0].out.length; i++) {
|
||
const xs = eff.map((e) => e.out[i]);
|
||
const m = (k, s) => mean(xs.map((x) => x[k][s]));
|
||
console.log(`${pad(xs[0].title.slice(0, 57), 58)}${cols.map((c) => lpad(f(m('first', c) * 100, 1), 7)).join('')}${lpad(f(m('follow', 'OEL') * 100, 2), 10)}${lpad(f(m('fvMove', 'OEL') * 100, 1), 8)}`);
|
||
}
|
||
console.log('Werte in %. „iW OEL“ = dauerhafte Änderung des inneren Werts von Öl (Angebotsschock), der Rest klingt über die Rückkehr zum inneren Wert ab.');
|
||
console.log(`Folgemeldungen (Mittel über alle Schlagzeilen und Werte): |Erstwirkung| ${f(mean(eff.flatMap((e) => e.out.flatMap((o) => Object.values(o.first).map(Math.abs)))) * 100, 2)} %, |Folgewirkung| ${f(mean(eff.flatMap((e) => e.out.flatMap((o) => Object.values(o.follow).map(Math.abs)))) * 100, 2)} %`);
|
||
}
|
||
if (scen.length) {
|
||
H(`4b. SZENARIEN (hybride Wirtschaft im Zeitraffer, je ${A.fastSeeds} Saisons à 20 Handelstage)`);
|
||
console.log(`${pad('Szenario', 14)}${lpad('Index', 9)}${lpad('max. DD', 9)}${lpad('Tech', 9)}${lpad('Banken', 9)}${lpad('Energie', 9)}${lpad('Rüstung', 9)}${lpad('OEL', 9)}${lpad('GAS', 9)}${lpad('GOLD', 9)}${lpad('WIB10', 9)}${lpad('Zins Ende', 10)}${lpad('Infl. max', 10)}${lpad('Rend.10J', 10)}${lpad('Rating', 8)}${lpad('Krise', 7)}`);
|
||
for (const sc of [...new Set(scen.map((r) => r.scenario))]) {
|
||
const rs = scen.filter((r) => r.scenario === sc);
|
||
const sec = (syms) => mean(rs.map((r) => mean(syms.map((s) => r.inst[s].ret))));
|
||
const worst = worstRating(rs.map((r) => r.budget.worst));
|
||
console.log(`${pad(sc, 14)}${lpad(pct(mean(rs.map((r) => r.index.ret))), 9)}${lpad(pct(mean(rs.map((r) => r.index.mdd))).replace('+', ''), 9)}${lpad(pct(sec(['NVLT', 'QBIT'])), 9)}${lpad(pct(sec(['RHBK'])), 9)}${lpad(pct(sec(['HLIO', 'GRNH'])), 9)}${lpad(pct(sec(['AEGS'])), 9)}${lpad(pct(sec(['OEL'])), 9)}${lpad(pct(sec(['GAS'])), 9)}${lpad(pct(sec(['GOLD'])), 9)}${lpad(pct(sec(['WIB10'])), 9)}${lpad(f(mean(rs.map((r) => r.macro.last.rate)), 2), 10)}${lpad(f(mean(rs.map((r) => r.macro.inflMax)), 1), 10)}${lpad(f(mean(rs.map((r) => r.yields.WIB10.end)), 2), 10)}${lpad(worst, 8)}${lpad(f(mean(rs.map((r) => r.budget.crisisDays / r.budget.days)) * 100, 0) + '%', 7)}`);
|
||
}
|
||
console.log('Renditen = Saison Ø · Rating = schlechtestes Rating der Saison · Krise = Anteil der Tage mit Haushaltskrise');
|
||
}
|
||
if (long.length) {
|
||
H('4c. HAUSHALT & RATING ÜBER VIELE SPIELJAHRE (Saisons hintereinander, Gesetze und Wahlen laufen mit)');
|
||
for (const r of long) {
|
||
const b = r.budget;
|
||
console.log(`${pad(`Seed ${r.seed} (${r.scenario === 'schuldenkrise' ? 'Start Schuldenkrise' : 'Start normal'})`, 30)} ${lpad(r.seasons, 3)} Saisons ≈ ${f(r.tradingDays / 84, 1)} Spieljahre: Schulden ${f(b.first.debt, 1)} → ${f(b.last.debt, 1)} % BIP (max ${f(b.debtMax, 1)}), Defizit Ende ${f(b.last.deficit, 1)} %, Rating ${b.first.rating} → ${b.last.rating} (schlechtestes ${b.worst}), Krisentage ${f(b.crisisDays / b.days * 100, 0)} %, Zins Ende ${f(r.macro.last.rate, 2)} %, Index ${pct(r.index.ret)}, OEL ${pct(r.inst.OEL.ret)}, GAS ${pct(r.inst.GAS?.ret)}, GOLD ${pct(r.inst.GOLD.ret)}, USD ${pct(r.inst.USD.ret)}`);
|
||
}
|
||
}
|
||
|
||
// ---------------- 4d. Erdgas: Saisonkurve
|
||
const gasRuns = [...long, ...fastN].filter((r) => r.gasByMonth);
|
||
if (gasRuns.length) {
|
||
H(`4d. ERDGAS – SAISONKURVE je Spielmonat (${long.length ? 'Langläufe über viele Spieljahre' : 'Zeitraffer-Saisons'}, ${gasRuns.length} Läufe)`);
|
||
const tot = Array.from({ length: 12 }, (_, i) => gasRuns.reduce((a, r) => { const x = r.gasByMonth[i]; return { n: a.n + x.n, lnPx: a.lnPx + x.lnPx, lnFv: a.lnFv + x.lnFv, fill: a.fill + x.fill, norm: a.norm + x.norm }; }, { n: 0, lnPx: 0, lnFv: 0, fill: 0, norm: 0 }));
|
||
const all = tot.reduce((a, x) => a + x.lnPx, 0) / Math.max(1, tot.reduce((a, x) => a + x.n, 0));
|
||
console.log(`${pad('Monat', 12)}${lpad('Tage', 7)}${lpad('Kurs Ø', 9)}${lpad('ggü. Jahr', 11)}${lpad('innerer W.', 12)}${lpad('Speicher', 10)}${lpad('üblich', 9)}`);
|
||
tot.forEach((x, i) => {
|
||
if (!x.n) return;
|
||
console.log(`${pad(MONTH_NAMES[i], 12)}${lpad(x.n, 7)}${lpad(f(Math.exp(x.lnPx / x.n), 2), 9)}${lpad(pct(Math.exp(x.lnPx / x.n - all) - 1), 11)}${lpad(f(Math.exp(x.lnFv / x.n), 2), 12)}${lpad(pct(x.fill / x.n, 0).replace('+', ''), 10)}${lpad(pct(x.norm / x.n, 0).replace('+', ''), 9)}`);
|
||
});
|
||
const gv = gasRuns.map((r) => r.inst.GAS?.realVol).filter(Number.isFinite);
|
||
console.log(`Ist-Volatilität GAS Ø ${pct(mean(gv), 0).replace('+', '')} (Ziel 60 %) · Kurs ggü. Jahresmittel: Saisonaufschlag + Speicher + Ereignisse + Zufall`);
|
||
}
|
||
|
||
// ---------------- 5. Leistung
|
||
if (hy.length) {
|
||
H('5. LEISTUNG (Echtzeit-Hybrid, alle Funktionen, Spieler handeln, SQLite schreibt jeden Takt)');
|
||
const o = hy.map((r) => r.tick.open), c = hy.map((r) => r.tick.closed);
|
||
console.log(`Takt im Handel: Ø ${f(mean(o.map((x) => x.mean)), 2)} ms, Median ${f(mean(o.map((x) => x.p50)), 2)} ms, p99 ${f(mean(o.map((x) => x.p99)), 2)} ms, Maximum ${f(Math.max(...o.map((x) => x.max)), 1)} ms (${hy[0].players} Spieler)`);
|
||
console.log(`Takt außerhalb: Ø ${f(mean(c.map((x) => x.mean)), 2)} ms, p99 ${f(mean(c.map((x) => x.p99)), 2)} ms, Maximum ${f(Math.max(...c.map((x) => x.max)), 1)} ms (enthält Tagesschluss mit Sicherung)`);
|
||
console.log(`Rechner: ${os.cpus()[0]?.model ?? '?'} – ein Raspberry Pi 4 ist grob 3–5× langsamer.`);
|
||
}
|
||
}
|
||
|
||
// ====================================================================== Einstieg
|
||
if (process.env.BAL_JOB) {
|
||
runJob(JSON.parse(process.env.BAL_JOB)).then((r) => { process.send(r, () => process.exit(0)); }).catch((e) => { console.error(e); process.exit(1); });
|
||
} else {
|
||
main();
|
||
}
|