diff --git a/README.md b/README.md index 2a4c3a8..a5c0450 100644 --- a/README.md +++ b/README.md @@ -32,8 +32,11 @@ Standardmäßig läuft das Spiel **in Echtzeit zu echten Börsenzeiten**: Man ka - **WiboCoin**: fiktive Kryptowährung, rund um die Uhr handelbar (auch nachts und am Wochenende), getrieben von Hype, Krypto-Meldungen, Risikoappetit und Zinsen. Keine Leerverkäufe. - **Weitere Anlageklassen**: Staatsanleihen mit 2 und 10 Jahren Laufzeit (Zinskurve, Kupon, Rendite, Duration), - Rohöl, Gold und US-Dollar – alle im selben Orderbuch, auch leerverkaufbar. Öl und Dollar wirken auf Inflation, - Wachstum und die Gewinne der Branchen; der Risikoaufschlag aus dem Staatshaushalt verteuert Kredite. + Rohöl, Erdgas, Gold und US-Dollar – alle im selben Orderbuch, auch leerverkaufbar. Öl, Gas und Dollar wirken auf + Inflation, Wachstum und die Gewinne der Branchen; der Risikoaufschlag aus dem Staatshaushalt verteuert Kredite. +- **Erdgas** (`GAS`, je MWh): im Winter teurer als im Sommer (Spielmonate), dazu der **Füllstand der Gasspeicher** + (im Sommer gefüllt, im Winter geleert; knapp vor oder im Winter → teuer). Teures Gas treibt die Inflation, drückt + Stimmung und Konsum, hilft Versorgern und belastet Stahl und Industrie. Gesetze: Gaspreisbremse, Speicherpflicht. - **Frühindikatoren** (Einkaufsmanagerindex, Klimaindex) und **Lieferketten**: Schocks bei Zulieferern erreichen die Abnehmerbranchen gedämpft ein bis zwei Tage später. - **Unternehmensereignisse**: Kapitalerhöhung, Aktienrückkauf, Übernahmeangebote mit Andienung durch die Spieler @@ -77,9 +80,9 @@ Standardmäßig läuft das Spiel **in Echtzeit zu echten Börsenzeiten**: Man ka **Echte Nachrichten** - RSS-Feeds (Standard: Tagesschau, DW) werden alle paar Minuten abgerufen und ausgewertet. Die Auswertung erkennt ganze Wörter auch in Komposita („Strafzölle“, „Stahlwerke“), **Verneinungen** („keine Rezession“), Verstärker - („drastisch“) und **Themen mit Richtung**: Ölpreis, Zinsen, Inflation, Dollar, Gold, Krisenrisiko, Zölle, + („drastisch“) und **Themen mit Richtung**: Ölpreis, Gaspreis/Gasspeicher, Zinsen, Inflation, Dollar, Gold, Krisenrisiko, Zölle, Arbeitsmarkt, Konjunktur („Ölpreis steigt“, „EZB senkt Leitzins“, „Arbeitslosigkeit sinkt“). -- Themen wirken direkt auf die passenden Märkte: Öl, Gold, Dollar und Anleihen sowie die abhängigen Branchen +- Themen wirken direkt auf die passenden Märkte: Öl, Gas, Gold, Dollar und Anleihen sowie die abhängigen Branchen (Rüstung profitiert von Krisen, Energie von teurem Öl, Banken von steigenden Zinsen). Dieselbe Geschichte aus mehreren Quellen wirkt als **Folgemeldung** schwächer; starke Meldungen erscheinen als **Eilmeldung**. - Unter jeder Meldung erklärt „Warum?“ die Bewertung und welche Werte sie bewegt hat. @@ -271,7 +274,7 @@ veröffentlichte Konjunkturdaten, Analystenziele, Gesetzgebung –, nie den inne | Nina Newsflash | Die Nachrichtenhändlerin | handelt Eilmeldungen sofort, hält nur kurz | | Kurt Kontra | Der Querdenker | kauft Panik, hält gegen Euphorie | | Stefan Strippe | Der Strippenzieher | gründet eine Partei, Vorlagen, Lobby; handelt die Gesetzgebung | -| Rita Rohstoff | Die Makro-Strategin | Anleihen, Gold, Öl, Dollar nach Konjunktur und Nachrichtenlage | +| Rita Rohstoff | Die Makro-Strategin | Anleihen, Gold, Öl, Gas, Dollar nach Konjunktur und Nachrichtenlage | | Viktor Value | Der Bewerter | Kurs gegen Analystenziel | | Ingrid Index | Die Gelassene | breit gestreut, gelegentlich rebalancieren | diff --git a/docs/API.md b/docs/API.md index 8610eeb..289ff48 100644 --- a/docs/API.md +++ b/docs/API.md @@ -174,7 +174,7 @@ Schlüssel `__proto__`, `constructor` oder `prototype` (in jeder Tiefe) und mehr | `curve` | – | `{curve}` | | `company` | `symbol` | `{company}` – bei Anleihen/Rohstoffen/Devisen die Instrumentansicht (siehe unten) | -`order` funktioniert für alle Instrumente (Aktien, `WIB2`, `WIB10`, `OEL`, `GOLD`, `USD`); Leerverkauf ist überall möglich. +`order` funktioniert für alle Instrumente (Aktien, `WIB2`, `WIB10`, `OEL`, `GAS`, `GOLD`, `USD`); Leerverkauf ist überall möglich. Wer ein Ministerium leitet, darf Aktien der zugeordneten Sektoren nur abbauen (Fehler „Interessenkonflikt“). ### Server → Client (zusätzlich) @@ -190,13 +190,15 @@ Wer ein Ministerium leitet, darf Aktien der zugeordneten Sektoren nur abbauen (F ### Datenstrukturen **ticker** (zusätzlich): `kind ('stock'|'bond'|'commodity'|'fx'), corp ('offer'|'trial'|null)`; für Anleihen `yield` (in %), `duration`, `exDivIn` = Handelstage bis zum Kupon, `divYield` = laufende Verzinsung (Kupon/Kurs); `sector` = `kind` bei Nicht-Aktien; `mcap`, `pe`, `earningsIn` sind bei Nicht-Aktien `null`. -Preiseinheiten: Anleihen in € je 100 € Nennwert, `OEL` je Barrel, `GOLD` je 10 g, `USD` je 100 $. +Preiseinheiten: Anleihen in € je 100 € Nennwert, `OEL` je Barrel, `GAS` je MWh, `GOLD` je 10 g, `USD` je 100 $. -**market** (zusätzlich): `season.scenario {id, title, desc}`, `politics {coalition[] (Kürzel), rating, electionAt, noConfidence}`; `macro.indicators {pmi, climate, consensus, surprise, ts, history[]}`, `macro.curve` (siehe curve). +**market** (zusätzlich): `season.scenario {id, title, desc}`, `politics {coalition[] (Kürzel), rating, electionAt, noConfidence}`; `macro.indicators {pmi, climate, consensus, surprise, ts, history[]}`, `macro.curve` (siehe curve), `macro.gas` (siehe gas). **curve**: `{points[{T (Jahre), y (%)}], y2, y10, spread, inverted, foreignRate, riskPremium, longNeutral}` -**company (Aktie, zusätzlich)**: `kind: 'stock', corporate {offer {target, targetName, bidder, bidderName, price, premium, probability, daysLeft, authority, tenderedTotal, myTender, role ('target'|'bidder')}|null, trial {drug, phase, daysLeft, probability, up, down}|null, control {by, floor, daysLeft}|null, history[]}, oilSens, fxSens, ministry` +**gas** (Erdgas, `macro.gas` und `company.gas` bei `GAS`): `{storage (Füllstand 0…1), norm (üblicher Füllstand), gap, month (Spielmonat), heating (Heizsaison), filling (Speicher werden gefüllt), winterWeight, season (Saisonaufschlag, Anteil), storagePremium (Speicheraufschlag, Anteil), duty (Speicherpflicht gilt), brake (Gaspreisbremse gilt), history[{day, fill, norm}]}` – `macro.gas.history` die letzten 30, `company.gas.history` die letzten 60 Handelstage. + +**company (Aktie, zusätzlich)**: `kind: 'stock', corporate {offer {target, targetName, bidder, bidderName, price, premium, probability, daysLeft, authority, tenderedTotal, myTender, role ('target'|'bidder')}|null, trial {drug, phase, daysLeft, probability, up, down}|null, control {by, floor, daysLeft}|null, history[]}, oilSens, gasSens, fxSens, ministry` **company (Instrument)**: `{symbol, name, kind, kindName, desc, last, prevClose, vol, baseVol, info, curve (Anleihen), budget {debt, deficit, rating, riskPremium} (Anleihen), foreignRate (USD), rate, holders[], shortInterest, lending, flowPrev, status, volaEndsAt, indicative, lastAuction, news[], dailyBars[]}`; `info` bei Anleihen `{kind, maturity, coupon, yield, accrued, cleanPrice, duration, nextCouponIn}`, sonst `{kind, base, changeFromStart}`. `holders[].pct` ist bei Instrumenten `null`; es gibt keine Analysten-, Quartals- und Dividendenfelder. @@ -210,12 +212,12 @@ Hinweise: Ohne laufende Abstimmung ist `source` der Name des Parlaments, sonst d **briefing** (zusätzlich): `curve, assets[{symbol, name, kind, last, change, yield}], government {coalition, rating, election (Zeitpunkt oder null)}, scenario`. -**calendar.items.kind** (zusätzlich): `'corporate'` (Annahmefrist, Studienergebnis; mit `symbol`), `'election'`; Kuponzahlungen der Anleihen erscheinen als `'exdiv'`. +**calendar.items.kind** (zusätzlich): `'corporate'` (Annahmefrist, Studienergebnis; mit `symbol`), `'election'`; Kuponzahlungen der Anleihen erscheinen als `'exdiv'`, der Gasspeicher-Bericht als `'macro'` mit `symbol: 'GAS'`. **profile** (zusätzlich): `party, office`. ### Admin-Aktionen (zusätzlich) -`scenario` (value: Szenario-ID, sofort anwenden), `takeover` (value: `{target, bidder?}` oder Symbol), `capitalIncrease`, `buyback`, `trial` (value: Symbol), `oilShock` (value: −0,5…0,5, log. Größe), `election` (Wahl sofort abhalten). +`scenario` (value: Szenario-ID, sofort anwenden), `takeover` (value: `{target, bidder?}` oder Symbol), `capitalIncrease`, `buyback`, `trial` (value: Symbol), `oilShock` (value: −0,5…0,5, log. Größe), `gasEvent` (zufälliges fiktives Gasmarkt-Ereignis), `election` (Wahl sofort abhalten). ### Einstellungen (zusätzlich) `billCosigners` (Politik), `corporateEvents`, `scenario` (Gruppe „Wirtschaft & Szenarien“; `zufall` wählt bei Saisonstart zufällig). @@ -242,9 +244,9 @@ Hinweise: Ohne laufende Abstimmung ist `source` der Name des Parlaments, sonst d | `restart` | `{reason: 'update'|'error'}` – der Server beendet sich gleich (Spielstand ist gespeichert). Danach neu verbinden; meldet `hello` einen anderen `version.build`, die Seite neu laden. | ### news (zusätzlich) -`analysis {by ('regeln'|'llm'), topics {oil, rates, inflation, usd, gold, risk, tariffs, labor, growth} (je −1…1, + = steigt/mehr), +`analysis {by ('regeln'|'llm'), topics {oil, gas, rates, inflation, usd, gold, risk, tariffs, labor, growth, crypto} (je −1…1, + = steigt/mehr), sectorImpact {Branche: −1…1}, strength (0…1), reasons[] (kurze Begründungen), followUp (dieselbe Geschichte schon gemeldet), relevant}`. -`affected` enthält jetzt auch `OEL`, `GOLD`, `USD`, `WIB2`, `WIB10`, wenn die Meldung sie bewegt hat. +`affected` enthält jetzt auch `OEL`, `GAS`, `GOLD`, `USD`, `WIB2`, `WIB10`, wenn die Meldung sie bewegt hat. ### Einstellungen (zusätzlich) Gruppe „KI-Auswertung“: `news.llmEnabled`, `news.llmUrl` (OpenAI-kompatibel, endet meist auf `/v1`), `news.llmModel`, diff --git a/docs/BALANCING.md b/docs/BALANCING.md index ad8329e..0e731d3 100644 --- a/docs/BALANCING.md +++ b/docs/BALANCING.md @@ -1,7 +1,7 @@ # Balancing – Messung und Abstimmung Stand: Dezember 2026 (Version 0.9.0, Logikkorrekturen in Abschnitt 6 mit Version 0.13, Langfrist-Drift in -Abschnitt 7). Diese Datei beschreibt, wie die Spielbalance gemessen wird, was die Messung ergeben hat, welche Zahlen +Abschnitt 7, Erdgas in Abschnitt 8). Diese Datei beschreibt, wie die Spielbalance gemessen wird, was die Messung ergeben hat, welche Zahlen deshalb geändert wurden und welche Probleme noch offen sind. ## 1. Methode @@ -581,3 +581,76 @@ Tests in `balancing.test.js`: viele Jahre weit auseinanderlaufen. Das ist gewollt, macht aber auch den Index je Seed unterschiedlich. - **Rezessionsanteil:** Der Markov-Wechsel in `world.js` erzeugt je Seed 0–40 % Rezessionstage. Das wirkt jetzt nur noch vorübergehend auf die Kurse. + +## 8. Erdgas (GAS) + +### Modell + +`GAS` („Erdgas (1 MWh)“, Rohstoff, Startpreis 35 €, Ziel-Vol 60 %, `pullDays` 2, `misSd` 0,05) hat einen eigenen +Preistreiber in `assets.js`: + +- **Saison:** Aufschlag `0,14 · cos(2π(Phase − 0,04))` im Logarithmus. Höchststand ist Mitte Januar, Tiefststand + Mitte Juli. Die Phase kommt aus dem Spieltag: `daysPerYear` Handelstage sind ein Spieljahr, Spieltag 1 liegt + Anfang April. +- **Gasspeicher:** Der Füllstand ist der übliche Füllstand je Jahreszeit plus eine Abweichung `gap`. Üblich sind + ≈ 34 % im April (Tief) und ≈ 90 % im Oktober (Hoch). + - Die Abweichung folgt einem Ornstein-Uhlenbeck-Prozess mit einer Halbwertszeit von ¼ Spieljahr. + - Ein Speicher unter dem Üblichen treibt den Preis (`−1,2 · gap`). + - Dieser Effekt ist mit der Nähe zum Winter gewichtet und im Sommer fast 0. +- **Kopplung:** 20 % der Öl-Abweichung vom Basispreis, 5 % der Konjunkturlücke. +- **Ereignisse:** + - Sechs erfundene Gasmarkt-Ereignisse, im Mittel drei je Spieljahr: Kältewelle, milder Winter, Leitungswartung, + LNG-Terminal, Lieferdrohung, Verträge verlängert. + - Dazu alle `macroEveryDays` ein Speicherbericht der Netzagentur. +- **Gesetze:** + - Die Gaspreisbremse halbiert die Weitergabe teurer Gaspreise an Inflation und Haushalte. + - Die Speicherpflicht hebt das Ziel des Speichers um 4 Punkte, verkürzt die Rückkehr und dämpft negative + Speicherschocks um 40 %. + +Nach außen wirkt nur die Abweichung **ohne** Saison (`ext.gas`). Das betrifft Inflation, BIP, Branchen und Stimmung. +Ein normaler Winter verschiebt also weder die Inflation noch die Aktien. + +Teures Gas wirkt so: + +- Inflation `+0,8 · gas`, BIP-Druck `−0,4 · gas` +- Energie profitiert, Industrie, Konsum und Auto leiden. +- Die Bevölkerung wird über „Heizkosten“ unzufriedener, vor allem Rentner und Landbevölkerung. + +### Messung (`npm run balance -- --quick`, vorher → nachher) + +| Kennzahl | vorher | nachher | +|---|---|---| +| Inflation max.: normal / Zinswende / Energiekrise | 2,5 / 4,7 / 4,0 | 2,4 / 4,7 / 4,0 | +| Index Saison Ø normal | +1,6 % | +3,9 % | +| Index Langlauf 4 × normal (≈ 12 Spieljahre) | +181 / +53 / +93 / +115 % | +103 / +103 / +141 / +40 % | +| Energiekrise: Index / Energie | +1,7 / +22,5 % | +1,1 / +15,8 % | +| Rezession: Index / max. Rückgang | −3,5 % / 10,0 % | −4,7 % / 10,2 % | +| Schuldenkrise: Rating / Krisentage | BBB / 66 % | BBB / 66 % | +| Ist-Vol GAS (Zeitraffer / Langlauf) | – | 82 % / 92 % (Ziel 60 %) | +| Ist-Vol OEL zum Vergleich (Ziel 34 %) | 89 % | 80 % | + +Die Unterschiede bei Index und Szenarien liegen im Rauschen, denn mit dem neuen Instrument verbrauchen die Läufe +andere Zufallszahlen. Die Ist-Vol von GAS liegt bei ≈ 1,4 × Ziel und damit im gewollten Rahmen (OEL ≈ 2,4 ×). + +Saisonkurve (Abschnitt 4d des Berichts, 14 Langläufe): + +| Monat | Jan | Feb | Mär | Apr | Mai | Jun | Jul | Aug | Sep | Okt | Nov | Dez | +|---|---|---|---|---|---|---|---|---|---|---|---|---| +| Kurs ggü. Jahresmittel | +12 % | +11 % | +11 % | +4 % | −4 % | −9 % | −9 % | −10 % | −8 % | −5 % | +3 % | +11 % | +| Speicher Ø | 67 % | 52 % | 41 % | 37 % | 41 % | 51 % | 66 % | 80 % | 89 % | 93 % | 90 % | 80 % | + +Schlagzeilen: + +- „Gasspeicher leeren sich schneller als erwartet“: GAS +3,8 %, OEL +0,4 %, HLIO +0,8 %, STHL −0,4 % +- „LNG-Lieferungen steigen deutlich“: GAS −3,7 % + +Gasmeldungen bewegen WiboCoin nicht. + +### Restrisiken + +- **Vorhersehbare Saison:** Ein neues Spiel beginnt im April. GAS fällt dann in der ersten Saison im Mittel um rund + 10 %; mit Zufall liegt der Saison-Ø im Zeitraffer bei −19 %. + - Wer das weiß, kann GAS im Frühjahr leer verkaufen und im Herbst kaufen. + - Bei 80 % Vol ist das Verhältnis von Ertrag zu Risiko je Saison aber klein (≈ 0,3). +- **Volatilitätsunterbrechungen:** Je Saison stiegen sie von 52 auf 62. Ein Teil davon kommt von GAS. +- **Strompreis:** `strompreis` zählt jetzt zum Thema Gas statt Öl. diff --git a/server/public/js/admin.js b/server/public/js/admin.js index d67a1e7..551e3fe 100644 --- a/server/public/js/admin.js +++ b/server/public/js/admin.js @@ -15,7 +15,7 @@ const T_STATUS = { signup: 'Anmeldung', running: 'läuft', done: 'beendet', canc const SECTIONS = { game: 'Spiel', news: 'Nachrichten', smtp: 'E-Mail' }; const PHASE = { closed: 'Börse geschlossen', preopen: 'Vorbörse', opening: 'Eröffnungsauktion', continuous: 'Fortlaufender Handel', closing: 'Schlussauktion' }; -const TOPIC_NAMES = { oil: 'Ölpreis', rates: 'Zinsen', inflation: 'Inflation', usd: 'Dollar', gold: 'Gold', risk: 'Krisenrisiko', tariffs: 'Zölle', labor: 'Arbeitsmarkt', growth: 'Konjunktur' }; +const TOPIC_NAMES = { oil: 'Ölpreis', gas: 'Gaspreis', rates: 'Zinsen', inflation: 'Inflation', usd: 'Dollar', gold: 'Gold', risk: 'Krisenrisiko', tariffs: 'Zölle', labor: 'Arbeitsmarkt', growth: 'Konjunktur' }; function updateHtml(u) { if (!u) return ''; let txt; @@ -336,6 +336,7 @@ function econHtml() {
2 J. ${num(cv.y2, 2)}\u00a0% · 10 J. ${num(cv.y10, 2)}\u00a0% · Abstand ${num(cv.spread * 100, 0)}\u00a0Bp. ${cv.inverted ? 'invertiert – Rezessionssignal' : 'normal'}
${gl('Risikoaufschlag')} ${num(cv.riskPremium, 2)}\u00a0Pp. · Auslandszins ${num(cv.foreignRate, 2)}\u00a0% · langfristiges Niveau ${num(cv.longNeutral, 2)}\u00a0%. ·
` : 'Keine Daten.
'} + ${gasHtml(m.gas, { link: true, id: 'macroGasChart' })}Lade Daten …
'); return; } if (stab === 'company') { - if (c.kind && c.kind !== 'stock') { patch(el, causesHtml(c) + instrumentHtml(c)); paint($('#instCurve'), curveChart(c.curve)); } + if (c.kind && c.kind !== 'stock') { patch(el, causesHtml(c) + instrumentHtml(c)); paint($('#instCurve'), curveChart(c.curve)); paintGas(c.gas); } else patch(el, causesHtml(c) + companyHtml(c)); } else if (stab === 'lending') patch(el, lendingHtml(c)); @@ -392,6 +393,7 @@ function companyHtml(c) { ${c.lastAuction?.price ? `Steigt der Kurs, bekommst du für 100 $ mehr Euro – der Euro ist schwächer geworden.
' : ''} - `; + ${c.gas ? gasHtml(c.gas) : ''}`; +} + +/** Erdgas: Heizsaison und Gasspeicher (auch in der Wirtschaftslage) */ +export function gasHtml(g, { link = false, id = 'gasChart' } = {}) { + if (!g) return ''; + const p = (x) => num(x * 100, 0); + const gap = g.storage - g.norm; + return `Im Sommer werden die Speicher gefüllt, im Winter geleert. Fehlt vor oder im Winter Gas im Speicher, steigt der Preis; im Hochsommer spielt der Füllstand kaum eine Rolle.${g.duty ? ' Die Speicherpflicht gilt: Betreiber lagern mehr ein, Lücken schließen sich schneller.' : ''}${g.brake ? ' Die Gaspreisbremse gilt: Haushalte und Inflation spüren nur die Hälfte teurer Gaspreise.' : ''}
`; +} +/** Verlauf des Füllstands zeichnen (nach dem Einfügen von gasHtml) */ +export function paintGas(g, id = 'gasChart') { + const el = document.getElementById(id); + if (!el || !g) return; + const h = g.history ?? []; + paint(el, lineChart([ + { name: 'Füllstand', points: h.map((x) => ({ x: x.day, y: x.fill * 100 })) }, + { name: 'üblich', points: h.map((x) => ({ x: x.day, y: x.norm * 100 })) }, + ], { legend: true, yMin: 0, yMax: 100, yFmt: (v) => `${num(v, 0)} %`, xFmt: (d) => `Tag ${d}`, empty: 'Noch kein Verlauf', hoverFmt: (pt) => `Tag ${pt.x}: ${num(pt.y, 0)} %` })); } function lendingHtml(c) { @@ -569,7 +598,7 @@ function holdersHtml(c) { } /** Nachrichtenliste (auch für andere Ansichten) */ -const TOPIC_NAMES = { oil: 'Öl', rates: 'Zinsen', inflation: 'Inflation', usd: 'Dollar', gold: 'Gold', risk: 'Krisenrisiko', tariffs: 'Zölle', labor: 'Arbeitsmarkt', growth: 'Konjunktur' }; +const TOPIC_NAMES = { oil: 'Öl', gas: 'Gas', rates: 'Zinsen', inflation: 'Inflation', usd: 'Dollar', gold: 'Gold', risk: 'Krisenrisiko', tariffs: 'Zölle', labor: 'Arbeitsmarkt', growth: 'Konjunktur' }; /** Kurzbegründungen der Auswertung („„rekordumsatz“ +“) in verständliche Sätze übersetzen */ function reasonText(r) { const m = /^„(.+)“ ([+−-])( \(verneint\))?$/.exec(String(r)); diff --git a/server/scripts/balance.mjs b/server/scripts/balance.mjs index eaf2f06..2a94c48 100644 --- a/server/scripts/balance.mjs +++ b/server/scripts/balance.mjs @@ -101,6 +101,8 @@ function classify(n) { 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'; @@ -316,7 +318,7 @@ function makeStrategies(g, players, ctx) { // --- 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', 'GOLD', 'USD'][Math.floor(Math.random() * 5)]; + 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; @@ -393,6 +395,8 @@ async function seasonJob(job, g, clock, { simulatedNews, settings }) { 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; @@ -416,6 +420,11 @@ async function seasonJob(job, g, clock, { simulatedNews, settings }) { 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) { @@ -486,7 +495,7 @@ async function seasonJob(job, g, clock, { simulatedNews, settings }) { 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, + seasons: seasonsSeen.length + 1, gasByMonth, tick: { open: tickStats(sortT(tickMs.open)), closed: tickStats(sortT(tickMs.closed)) }, players: g.players.size, }; @@ -498,7 +507,7 @@ async function effectsJob(job, g, clock, { analyze }) { for (let i = 0; i < 400 && g.market.phase !== 'continuous'; i++) step(1); step(5); const out = []; - const watch = ['OEL', 'GOLD', 'USD', 'WIB10', 'WIB2', 'AEGS', 'HLIO', 'VOLT', 'RHBK', 'NVLT', 'STHL', 'KRMA']; + 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 } }); @@ -547,10 +556,14 @@ function runPool(jobs, n, onDone) { }); } +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' }, @@ -658,7 +671,7 @@ function report(res, A) { // ---------------- 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', 'GOLD', 'USD', 'WIB10', 'AEGS', 'HLIO', 'VOLT', 'RHBK', 'NVLT', 'KRMA']; + 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]); @@ -670,12 +683,12 @@ function report(res, A) { } 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('GOLD', 9)}${lpad('WIB10', 9)}${lpad('Zins Ende', 10)}${lpad('Infl. max', 10)}${lpad('Rend.10J', 10)}${lpad('Rating', 8)}${lpad('Krise', 7)}`); + 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(['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(`${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'); } @@ -683,10 +696,25 @@ function report(res, A) { 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)}, GOLD ${pct(r.inst.GOLD.ret)}, USD ${pct(r.inst.USD.ret)}`); + 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)'); diff --git a/server/src/assets.js b/server/src/assets.js index 99e52b3..863d889 100644 --- a/server/src/assets.js +++ b/server/src/assets.js @@ -1,8 +1,9 @@ // Weitere Anlageklassen: Staatsanleihen mit konstanter Laufzeit (Zinskurve), Rohstoffe und US-Dollar. // Alle Instrumente werden über dasselbe Orderbuch gehandelt wie Aktien (Market Maker, Auktionen, Leerverkauf). // Ihr „innerer Wert“ folgt der Makrolage: Anleihen der Zinskurve, Öl der Konjunktur und Angebotsschocks, -// Gold Realzins und Angst, der Dollar der Zinsdifferenz. Umgekehrt wirken Öl und Dollar auf Inflation, -// Wachstum und Unternehmensgewinne; der Risikoaufschlag aus dem Staatshaushalt verteuert Kredite. +// Erdgas der Heizsaison und dem Füllstand der Gasspeicher, Gold Realzins und Angst, der Dollar der Zinsdifferenz. +// Umgekehrt wirken Öl, Gas und Dollar auf Inflation, Wachstum und Unternehmensgewinne; der Risikoaufschlag aus dem +// Staatshaushalt verteuert Kredite. import { INFL_TARGET, TREND_GDP } from './world.js'; import { gauss, clamp, rnd, fmt } from './util.js'; @@ -17,6 +18,8 @@ export const INSTRUMENTS = [ desc: 'Staatsanleihe der Republik Wiborien mit konstanter Restlaufzeit von 10 Jahren. Kurs in € je 100 € Nennwert, Kupon 3,0 % p. a. (vierteljährlich).' }, { symbol: 'OEL', kind: 'commodity', name: 'Rohöl (1 Barrel)', price: 72.4, shares: 4e8, vol: 0.34, pullDays: 2, misSd: 0.04, desc: 'Rohöl-Kontrakt, Preis in € je Barrel. Folgt der Weltkonjunktur und Förderentscheidungen des (fiktiven) Petrolia-Kartells. Teures Öl treibt die Inflation und belastet Auto, Industrie und Handel.' }, + { symbol: 'GAS', kind: 'commodity', name: 'Erdgas (1 MWh)', price: 35.0, shares: 3e8, vol: 0.6, pullDays: 2, misSd: 0.05, + desc: 'Erdgas-Kontrakt, Preis in € je Megawattstunde. Im Winter teurer als im Sommer, dazu entscheidet der Füllstand der Gasspeicher: Sind sie vor oder im Winter knapp gefüllt, steigt der Preis. Teures Gas treibt die Inflation, belastet Haushalte, Industrie und Handel – Versorger profitieren.' }, { symbol: 'GOLD', kind: 'commodity', name: 'Gold (10 g)', price: 742.0, shares: 6e7, vol: 0.16, pullDays: 3, misSd: 0.03, desc: 'Gold, Preis in € je 10 Gramm. Sicherer Hafen: steigt bei Angst, fallenden Realzinsen und Zweifeln an den Staatsfinanzen.' }, { symbol: 'USD', kind: 'fx', name: 'US-Dollar (100 $)', price: 92.5, shares: 5e8, vol: 0.08, pullDays: 3, misSd: 0.015, @@ -39,9 +42,40 @@ const CRYPTO_EVENTS = [ { title: 'Großer WiboCoin-Fonds muss Anteile zurücknehmen – Notverkäufe', size: -0.28 }, { title: 'Zentralbank warnt vor Spekulation mit Kryptowährungen', size: -0.12 }, ]; +// fiktive Ereignisse am Gasmarkt (supply: log. Angebotsschock, + = knapper/teurer · gap: Änderung des Speicherfüllstands +// gegenüber dem Üblichen · winter: nur in der Heizsaison) +const GAS_EVENTS = [ + { title: 'Kältewelle über Wiborien: Gasverbrauch auf Rekordniveau, die Speicher leeren sich schneller', supply: 0.08, gap: -0.06, winter: true }, + { title: 'Ungewöhnlich milder Winter: Gasspeicher bleiben voller als erwartet', supply: -0.07, gap: 0.05, winter: true }, + { title: 'Wartung an der Nordmeer-Leitung verlängert – weniger Erdgas für Wiborien', supply: 0.1, gap: -0.04 }, + { title: 'Neues Flüssiggas-Terminal in Nordhafen nimmt den Betrieb auf', supply: -0.08, gap: 0.03 }, + { title: 'Lieferland Karvanien droht mit gekürzten Gaslieferungen', supply: 0.1, gap: -0.02 }, + { title: 'Gaslieferverträge mit Karvanien verlängert – Versorgung für zwei Jahre gesichert', supply: -0.1, gap: 0.02 }, +]; export const FOREIGN_RATE = 3.5; // Zinsniveau im Ausland (langfristiger Mittelwert) const CURVE_POINTS = [0.25, 1, 2, 3, 5, 7, 10, 20, 30]; +// ---------------------------------------------------------------- Erdgas: Heizsaison und Gasspeicher +// Das Spieljahr (daysPerYear Handelstage) hat Jahreszeiten. Spieltag 1 liegt Anfang April: Die Speicher sind nach dem +// Winter fast leer und werden über den Sommer gefüllt, im Winter wieder geleert. +const GAS_PHASE0 = 0.25; +export const MONTHS = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember']; +const TAU = 2 * Math.PI; +/** Stelle im Spieljahr (0 = 1. Januar … 1) für einen Handelstag */ +export function yearPhase(day, daysPerYear) { + const y = Math.max(1, daysPerYear); + return ((((day - 1) % y) + y) % y / y + GAS_PHASE0) % 1; +} +/** Saisonaufschlag auf den Gaspreis (log.): Höchststand Mitte Januar (≈ +15 %), Tiefststand Mitte Juli (≈ −13 %) */ +export function gasSeason(phase) { return 0.14 * Math.cos(TAU * (phase - 0.04)); } +/** üblicher Füllstand der Gasspeicher (0…1): voll Mitte Oktober (≈ 90 %), fast leer Mitte April (≈ 34 %) */ +export function storageNorm(phase) { return 0.62 + 0.28 * Math.cos(TAU * (phase - 0.79)); } +/** Wie stark der Füllstand den Preis bewegt: vor und im Winter voll, im Hochsommer kaum */ +export function winterWeight(phase) { return 0.5 + 0.5 * Math.cos(TAU * (phase - 0.97)); } +const STORE_K = 1.2; // log. Preisaufschlag je fehlendem Füllstand (1 = 100 %) bei vollem Wintergewicht +const GAP_SD = 0.05; // typische Abweichung des Füllstands vom Üblichen +const r3 = (x) => Math.round(x * 1000) / 1000; + /** Startzustand je Instrument (wird mit dem Spielstand gespeichert) */ export function initAsset(s, day) { if (s.kind === 'bond') return { couponStart: day }; @@ -95,6 +129,11 @@ export class Assets { const realRate = c.rateEff - c.inflation; let ln = Math.log(BASE[s.symbol]) + (a.drift ?? 0); if (s.symbol === 'OEL') ln += 0.1 * (m.gdp - TREND_GDP) + 0.06 * m.sentiment + (a.supply ?? 0); + else if (s.symbol === 'GAS') { + // Heizsaison und knappe Speicher vor/im Winter; schwach an Konjunktur und (Ölpreisbindung alter Lieferverträge) an Öl gekoppelt + const o = this.get('OEL'); + ln += this.gasTerm() + 0.05 * (m.gdp - TREND_GDP) + 0.2 * (o?.fv ? clamp(Math.log(o.fv / BASE.OEL), -1, 1) : 0) + (a.supply ?? 0); + } else if (s.symbol === 'GOLD') ln += -0.08 * (realRate - 0.5) - 0.05 * m.sentiment + 0.1 * c.risk; else if (s.symbol === 'USD') ln += 0.04 * (this.foreignRate - c.rateEff - (FOREIGN_RATE - 2.5)) + 0.05 * c.risk; else if (s.kind === 'crypto') ln += (a.hype ?? 0) + 0.3 * m.sentiment - 0.06 * (c.rateEff - 2.5) + 0.15 * c.risk; @@ -103,9 +142,13 @@ export class Assets { /** Außenwirtschaftliche Größen für Makro und Unternehmensgewinne (log. Abweichung vom Startniveau, geglättet über den inneren Wert) */ ext() { - const o = this.get('OEL'), u = this.get('USD'); + const o = this.get('OEL'), u = this.get('USD'), gs = this.get('GAS'); + // Gas: nur die Abweichung vom saisonüblichen Preis wirkt (ein normaler Winter ist eingeplant); die Gaspreisbremse + // halbiert, was von teurem Gas bei Verbrauchern und in der Inflation ankommt + const gas = gs?.fv ? clamp(Math.log(gs.fv / BASE.GAS) - gasSeason(this.gasPhase()), -1, 1) : 0; return { oil: o?.fv ? clamp(Math.log(o.fv / BASE.OEL), -1, 1) : 0, + gas, gasCpi: gas > 0 && this.lawActive('gasbrake') ? gas * 0.5 : gas, usd: u?.fv ? clamp(Math.log(u.fv / BASE.USD), -0.5, 0.5) : 0, risk: this.g.gov?.riskPremium() ?? 0, }; @@ -128,7 +171,7 @@ export class Assets { { if (s.kind === 'bond') return; const a = (s.asset ??= initAsset(s, this.g.day)); - const sd = { OEL: 0.12, GOLD: 0.08, USD: 0.04 }[s.symbol] ?? (s.kind === 'crypto' ? 0.35 : 0.05); + const sd = { OEL: 0.12, GAS: 0.16, GOLD: 0.08, USD: 0.04 }[s.symbol] ?? (s.kind === 'crypto' ? 0.35 : 0.05); a.drift = ou(a.drift ?? 0, s.kind === 'crypto' ? 40 : 60, sd); if (a.supply) a.supply *= Math.exp((-Math.LN2 * dtDays) / 30); if (a.hype) a.hype *= Math.exp((-Math.LN2 * dtDays) / 6); // Hype verfliegt (Halbwertszeit ~6 Handelstage) @@ -147,6 +190,13 @@ export class Assets { g.ex.exDividend(s, Math.round((s.coupon / 4) * 100) / 100, 'Kupon'); } } + // Erdgas: Heizsaison und Speicher rücken einen Tag weiter; zu jedem Konjunkturtermin ein Speicherbericht + g.causes?.set('Erdgas: Heizsaison & Gasspeicher'); + g.econ.revalue(() => this.stepGas()); + if (g.day % cfg.macroEveryDays === 0) this.gasReport(); + // Gasmarkt: etwa drei größere Ereignisse je Spieljahr + if (Math.random() < 3 / cfg.daysPerYear) this.gasEvent(); + g.causes?.set('Rohstoffe & Devisen: Marktlage'); // Ölkartell: im Mittel etwa zwei Entscheidungen je Spieljahr if (Math.random() < 2 / cfg.daysPerYear) this.oilShock(rnd(0.08, 0.22) * (Math.random() < 0.55 ? 1 : -1)); // Krypto: etwa sechs große Ereignisse je Spieljahr @@ -184,6 +234,84 @@ export class Assets { g.econ.cascade('energy', size > 0 ? -size * 0.25 : -size * 0.15, 'Energiepreise'); } + // ---------------------------------------------------------------- Erdgas + /** Gilt ein Gesetz (nach Inkrafttreten)? */ + lawActive(key) { + const r = this.g.pol?.inForce?.[key]; + return !!r && this.g.day >= (r.day ?? 0); + } + /** Zustand des Gasmarkts (im Makrozustand gespeichert; ältere Spielstände bekommen ihn beim ersten Zugriff) */ + gasState() { return (this.g.macro.gas ??= { gap: 0, day: this.g.day, history: [] }); } + /** Stelle im Spieljahr, für die der Gaspreis zuletzt bewertet wurde */ + gasPhase() { return yearPhase(this.gasState().day, this.cfg.daysPerYear); } + /** Füllstand der Gasspeicher (0…1) */ + storage() { return clamp(storageNorm(this.gasPhase()) + this.gasState().gap, 0.02, 1); } + /** Saison- und Speicheranteil des Gaspreises (log.) */ + gasTerm() { + const ph = this.gasPhase(); + return gasSeason(ph) - STORE_K * (this.storage() - storageNorm(ph)) * winterWeight(ph); + } + + /** Ein Handelstag weiter: Jahreszeit fortschreiben; die Abweichung vom üblichen Füllstand schwankt und baut sich ab */ + stepGas() { + const g = this.g, st = this.gasState(), Y = this.cfg.daysPerYear; + const dt = Math.min(Y, Math.max(0, g.day - st.day)); + if (!dt) return; + // Speicherpflicht: Betreiber lagern vor dem Winter etwas mehr ein, Lücken werden schneller geschlossen + const duty = this.lawActive('gasstore'); + const target = duty ? 0.04 : 0; + const k = Math.LN2 / (Y * (duty ? 0.12 : 0.25)); + const e = Math.exp(-k * dt); + st.gap = clamp(target + (st.gap - target) * e + GAP_SD * Math.sqrt(1 - e * e) * gauss(), -0.3, 0.2); + st.day = g.day; + st.history.push({ day: g.day, fill: r3(this.storage()), norm: r3(storageNorm(this.gasPhase())) }); + if (st.history.length > 120) st.history.splice(0, st.history.length - 120); + } + + /** Lage am Gasmarkt für Anzeige und Hilfe */ + gasInfo(hist = 60) { + const st = this.gasState(), ph = this.gasPhase(), norm = storageNorm(ph), fill = this.storage(), w = winterWeight(ph); + return { + storage: fill, norm, gap: fill - norm, month: MONTHS[Math.floor(ph * 12) % 12], heating: ph >= 0.75 || ph < 0.25, + filling: storageNorm((ph + 0.01) % 1) > norm, winterWeight: w, + season: Math.exp(gasSeason(ph)) - 1, storagePremium: Math.exp(-STORE_K * (fill - norm) * w) - 1, + duty: this.lawActive('gasstore'), brake: this.lawActive('gasbrake'), history: hist ? st.history.slice(-hist) : [], + }; + } + + /** Speicherbericht der (fiktiven) Netzagentur – reine Information, der Füllstand ist bereits eingepreist */ + gasReport() { + const i = this.gasInfo(), p = (x) => Math.round(x * 100); + const txt = `Gasspeicher-Bericht: Füllstand ${p(i.storage)} % (üblich im ${i.month}: ${p(i.norm)} %) – die Speicher werden ${i.filling ? 'gefüllt' : 'geleert'}`; + this.g.addNews({ id: `gasrep-${Date.now()}`, title: txt, source: 'Netzagentur Wiborien', real: false, sentiment: 0, sectors: [], symbol: 'GAS', affected: ['GAS'], ts: Date.now() }, false); + } + + /** Ereignis am Gasmarkt (fiktiv): Angebotsschock und veränderter Speicherfüllstand */ + gasEvent(ev = null) { + if (!this.get('GAS')) return null; + const heating = this.gasInfo().heating; + ev ??= pick(GAS_EVENTS.filter((e) => !e.winter || heating)); + this.g.causes?.set(`Erdgas: ${ev.title}`); + this.gasShock(ev.supply * rnd(0.7, 1.3), ev.title, ev.gap ?? 0); + return ev; + } + + /** Angebotsschock beim Gas (log. Größe, + = knapper/teurer); gap verschiebt den Speicherfüllstand; news = false: ohne eigene Meldung */ + gasShock(size, reason, gap = 0, news = true) { + const g = this.g, s = this.get('GAS'); + if (!s) return; + g.econ.revalue(() => { + s.asset.supply = (s.asset.supply ?? 0) + size; + // mit Speicherpflicht fallen Lücken kleiner aus + if (gap) { const st = this.gasState(); st.gap = clamp(st.gap + gap * (gap < 0 && this.lawActive('gasstore') ? 0.6 : 1), -0.3, 0.2); } + }); + g.econ.bumpVol(s, 2); + const txt = reason ?? (size > 0 ? 'Gasmarkt: Lieferengpässe – Gaspreis steigt kräftig' : 'Gasmarkt: reichlich Angebot – Gaspreis gibt nach'); + if (!news) return; + g.addNews({ id: `gas-${Date.now()}-${Math.floor(Math.random() * 1e4)}`, title: txt, source: 'Rohstoffmärkte', real: false, sentiment: 0, sectors: ['energy'], symbol: 'GAS', affected: ['GAS'], ts: Date.now() }, false); + g.log('macro', txt); + } + /** Zinskurve für die Anzeige */ curve() { const c = this.curveCtx(this.g.econ.ctx()); @@ -217,10 +345,11 @@ export class Assets { return { kind: s.kind, base: BASE[s.symbol], changeFromStart: (s.last / BASE[s.symbol] - 1) * 100 }; } - /** Startkurse der Anleihen aus der Zinskurve (nur beim allerersten Start) */ + /** Startkurse der Anleihen aus der Zinskurve und des Gases aus Saison und Speicher – nur beim allerersten Start + * bzw. wenn ein älterer Spielstand den Wert noch nicht kennt */ seed() { for (const s of this.list()) { - if (s.kind !== 'bond' || s.seeded) continue; + if ((s.kind !== 'bond' && s.symbol !== 'GAS') || s.seeded) continue; const v = Math.round(this.value(s, this.g.econ.ctx()) * 100) / 100; Object.assign(s, { fair: v, last: v, prevClose: v, close: v, open: v, high: v, low: v, refAuction: v, seeded: true }); } diff --git a/server/src/balancing.test.js b/server/src/balancing.test.js index 37cb8fe..16f0629 100644 --- a/server/src/balancing.test.js +++ b/server/src/balancing.test.js @@ -70,7 +70,7 @@ test('Übernahmen: nur plausible Ziele mit passendem, deutlich größerem Bieter g.corp.offers = []; assert.ok(made >= 290, `nur ${made} von 300 Versuchen ergaben ein Angebot – Ziele ohne Bieter werden gezogen`); assert.ok(targets.size >= 6, 'verschiedene Ziele'); - for (const sym of ['WIB10', 'WIB2', 'USD', 'OEL', 'GOLD', 'WIBC']) { + for (const sym of ['WIB10', 'WIB2', 'USD', 'OEL', 'GAS', 'GOLD', 'WIBC']) { if (!g.stocks.has(sym)) continue; assert.throws(() => g.corp.takeover(sym), /Aktie/); assert.ok(!targets.has(sym)); diff --git a/server/src/economy.js b/server/src/economy.js index d934cf6..a53c0d1 100644 --- a/server/src/economy.js +++ b/server/src/economy.js @@ -5,7 +5,7 @@ import { SECTORS, stepMacro, releaseMacro, councilVote, cbExpectation, TREND_GDP import { initFundamentals, dailyFundamentals, updateAnalysts, fundamentalValue } from './fundamentals.js'; import { startInstitutional } from './bots.js'; import { runScript } from './scenarios.js'; -import { mentionsCrypto } from './newsanalysis.js'; +import { mentionsCrypto, mentionsGas } from './newsanalysis.js'; import { rnd, gauss, clamp, fmt } from './util.js'; // Lieferketten: wer wen beliefert (Anteil, mit dem ein Schock beim Lieferanten bei den Abnehmern ankommt) @@ -40,7 +40,7 @@ export class Economy { const ext = this.g.assets?.ext() ?? { oil: 0, usd: 0, risk: 0 }; const rateEff = this.macro.rate + (this.cbExpect?.mean ?? 0); return { - rateEff: rateEff + ext.risk * 0.5, baseRate: rateEff, risk: ext.risk, oil: ext.oil, usd: ext.usd, + rateEff: rateEff + ext.risk * 0.5, baseRate: rateEff, risk: ext.risk, oil: ext.oil, gas: ext.gas ?? 0, usd: ext.usd, expect: this.g.pol.expectFactors(), day: this.g.day, quarterDays: this.cfg.quarterDays, }; @@ -328,7 +328,7 @@ export class Economy { /** * Nachricht einpreisen. Die Auswertung (Regelwerk oder Sprachmodell) liefert Stimmung, Branchen, Themen und Stärke. * – Stimmung: kleiner Impuls auf alle Aktien, größerer auf die betroffenen Branchen (Branchen-Sonderwirkung beachtet) - * – Themen: wirken direkt auf Öl, Gold, Dollar und Anleihen sowie auf die Branchen, die daran hängen + * – Themen: wirken direkt auf Öl, Gas, Gold, Dollar und Anleihen sowie auf die Branchen, die daran hängen * – Stärke und Neuheit (Folgemeldungen derselben Geschichte wirken schwächer) skalieren alles */ newsImpact(n) { @@ -342,9 +342,13 @@ export class Economy { const addSec = (sec, v) => { sectorEff[sec] = (sectorEff[sec] ?? 0) + v; }; // Krypto direkt nur bei echtem Krypto-Bezug in der Überschrift (auch wenn ein Sprachmodell einem Marktbericht „crypto“ zuschreibt) const cryptoStory = n.symbol === 'WIBC' || mentionsCrypto(n.title); - const t = (x) => (x === 'crypto' && !cryptoStory ? 0 : topics[x] ?? 0); + // Gas: ein Sprachmodell, das einer Meldung ohne Gas-/Energiebezug in der Überschrift ein Gas-Thema zuschreibt, wirkt nur halb + const gasK = a.by === 'llm' && !mentionsGas(n.title) ? 0.5 : 1; + const t = (x) => (x === 'crypto' && !cryptoStory ? 0 : x === 'gas' ? (topics.gas ?? 0) * gasK : topics[x] ?? 0); // Themen → Branchen (klein, wirkt zusätzlich zur Stimmung) if (t('oil')) { addSec('energy', 0.012 * t('oil')); addSec('auto', -0.006 * t('oil')); addSec('industry', -0.004 * t('oil')); addSec('consumer', -0.003 * t('oil')); } + // teures Gas: Versorger profitieren, energieintensive Industrie und Verbraucher leiden (Firmenunterschiede über den inneren Wert) + if (t('gas')) { addSec('energy', 0.008 * t('gas')); addSec('industry', -0.005 * t('gas')); addSec('consumer', -0.003 * t('gas')); addSec('auto', -0.002 * t('gas')); } if (t('rates')) { addSec('banks', 0.006 * t('rates')); addSec('tech', -0.008 * t('rates')); addSec('consumer', -0.003 * t('rates')); } if (t('inflation')) { addSec('consumer', -0.005 * t('inflation')); addSec('tech', -0.003 * t('inflation')); } if (t('risk')) { addSec('defense', 0.012 * t('risk')); addSec('energy', 0.004 * t('risk')); } @@ -373,7 +377,9 @@ export class Economy { affected.add(sym); if (Math.abs(imp) > 0.012 && Math.random() < 0.5) startInstitutional(s, imp > 0 ? 'buy' : 'sell', Math.abs(imp) * 30); }; - inst('OEL', 0.04 * t('oil') + 0.012 * t('risk') + 0.006 * t('growth')); + // Öl und Gas hängen nur schwach aneinander + inst('OEL', 0.04 * t('oil') + 0.006 * t('gas') + 0.012 * t('risk') + 0.006 * t('growth')); + inst('GAS', 0.05 * t('gas') + 0.01 * t('oil') + 0.008 * t('risk')); inst('GOLD', 0.02 * t('gold') + 0.015 * t('risk') + 0.008 * t('inflation') - 0.006 * t('rates')); inst('USD', 0.012 * t('usd') + 0.004 * t('risk') + 0.002 * t('tariffs')); // Anleihen: höhere Zinsen/Inflation drücken den Kurs, Krisen treiben Anleger in sichere Staatsanleihen @@ -383,11 +389,17 @@ export class Economy { // höchstens ±6 %; die großen Sprünge bleiben den Krypto-Ereignissen vorbehalten), dazu schwach Börsenstimmung und Zinsen const wibc = g.stocks.get('WIBC'); if (wibc && t('crypto')) { g.assets.hype(wibc, clamp(0.05 * t('crypto') * scale / Math.max(0.001, k), -0.06, 0.06)); affected.add('WIBC'); } - inst('WIBC', 0.006 * n.sentiment - 0.01 * t('rates') - 0.004 * t('risk')); + // reine Rohstoffmeldungen (Öl, Gas) sagen nichts über den Krypto-Risikoappetit + const commodityOnly = Object.keys(topics).length > 0 && Object.keys(topics).every((x) => x === 'oil' || x === 'gas'); + inst('WIBC', (commodityOnly ? 0 : 0.006 * n.sentiment) - 0.01 * t('rates') - 0.004 * t('risk')); if (Math.abs(t('oil')) >= 0.6 && (a.strength ?? 0) >= 0.6 && !a.followUp) { const s = g.stocks.get('OEL'); if (s) this.revalue(() => { s.asset.supply = (s.asset.supply ?? 0) + 0.015 * t('oil') * k; }); } + if (Math.abs(t('gas')) >= 0.6 && (a.strength ?? 0) >= 0.6 && !a.followUp) { + const s = g.stocks.get('GAS'); + if (s) this.revalue(() => { s.asset.supply = (s.asset.supply ?? 0) + 0.02 * t('gas') * k; }); + } for (const sec of n.sectors) { const v = a.sectorImpact?.[sec] ?? n.sentiment; @@ -415,6 +427,7 @@ export class Economy { targets: { inflation: INFL_TARGET, gdp: TREND_GDP }, indicators: m.indicators ? { pmi: m.indicators.pmi, climate: m.indicators.climate, consensus: m.indicators.consensus, surprise: m.indicators.surprise, ts: m.indicators.ts, history: m.indicators.history.slice(-30) } : null, curve: this.g.assets?.curve() ?? null, + gas: this.g.assets?.gasInfo(30) ?? null, }; } diff --git a/server/src/fundamentals.js b/server/src/fundamentals.js index 672d348..b0837ad 100644 --- a/server/src/fundamentals.js +++ b/server/src/fundamentals.js @@ -44,8 +44,8 @@ export function fundamentalValue(s, ctx) { const fwdEps = f.consensus * 4 * (1 + sec.rateEps * ((ctx.baseRate ?? ctx.rateEff) - NEUTRAL_RATE)); const policy = Math.exp((f.policy ?? []).reduce((a, p) => a + p.log, 0)); const expect = ctx.expect?.[s.sector] ?? 1; - // Öl und Dollar wirken auf die Gewinne (Kosten bzw. Exporterlöse), der Länderrisikoaufschlag auf Banken (Anleihebestände, Refinanzierung) - const ext = Math.exp((sec.oil ?? 0) * (ctx.oil ?? 0) + (sec.fx ?? 0) * (ctx.usd ?? 0) + (sec.sov ?? 0) * Math.max(0, ctx.risk ?? 0)); + // Öl, Gas und Dollar wirken auf die Gewinne (Kosten bzw. Exporterlöse), der Länderrisikoaufschlag auf Banken (Anleihebestände, Refinanzierung) + const ext = Math.exp((sec.oil ?? 0) * (ctx.oil ?? 0) + (s.gasSens ?? sec.gas ?? 0) * (ctx.gas ?? 0) + (sec.fx ?? 0) * (ctx.usd ?? 0) + (sec.sov ?? 0) * Math.max(0, ctx.risk ?? 0)); return Math.max(0.5, fwdEps * valuationPe(s, ctx.rateEff) * policy * expect * ext) + accruedDividend(s, ctx.day, ctx.quarterDays); } diff --git a/server/src/game.js b/server/src/game.js index 51290ae..64d8f64 100644 --- a/server/src/game.js +++ b/server/src/game.js @@ -840,7 +840,7 @@ export class Game { news: this.news.filter((n) => n.symbol === symbol || n.affected?.includes(symbol) || n.sectors?.includes(s.sector)).slice(0, 15), dailyBars: this.store.dailyBars(symbol, 120), kind: 'stock', corporate: this.corp.view(symbol, pid), - oilSens: SECTORS[s.sector].oil, fxSens: SECTORS[s.sector].fx, + oilSens: SECTORS[s.sector].oil, gasSens: s.gasSens ?? SECTORS[s.sector].gas ?? 0, fxSens: SECTORS[s.sector].fx, ministry: MINISTRIES.find((m) => m.sectors.includes(s.sector))?.name ?? null, }; } @@ -863,6 +863,7 @@ export class Game { vol: this.econ.volNow(s), baseVol: s.vol, info: this.assets.info(s), curve: s.kind === 'bond' ? this.assets.curve() : null, budget: s.kind === 'bond' ? { debt: this.gov.budget.debt, deficit: this.gov.budget.deficit, rating: this.gov.budget.rating, riskPremium: this.gov.riskPremium() } : null, foreignRate: s.kind === 'fx' ? this.assets.foreignRate : null, rate: this.macro.rate, + gas: s.symbol === 'GAS' ? this.assets.gasInfo() : null, holders: holders.slice(0, 10), shortInterest, lending: this.ex.lendInfo(s), flowPrev: fp ? { day: fp.day, @@ -899,6 +900,7 @@ export class Game { } const km = cfg.macroEveryDays - (this.day % cfg.macroEveryDays); items.push({ ts: at(km), dayIn: km, kind: 'macro', title: 'Konjunkturdaten (Inflation, Wachstum, Arbeitslosigkeit)', detail: 'Statistikamt, zur Vorbörse' }); + items.push({ ts: at(km), dayIn: km, kind: 'macro', symbol: 'GAS', title: 'Gasspeicher-Bericht (Füllstand)', detail: 'Netzagentur Wiborien, zur Vorbörse' }); const cbDay = this.econ.nextCbDay(); const kc = cbDay - this.day; const hm = (t) => { const [h, m] = t.split(':').map(Number); return (h * 60 + m) * 60_000; }; @@ -1045,6 +1047,11 @@ export class Game { const v = clamp(Number(value) || 0.15, -0.5, 0.5); this.assets.oilShock(v); detail = { size: v }; break; } + case 'gasEvent': { + const ev = this.assets.gasEvent(); + if (!ev) throw new Error('Erdgas nicht vorhanden'); + detail = { event: ev.title }; break; + } case 'agm': { const m = this.agm.announce(this.stocks.get(String(value ?? ''))); detail = { agm: m.id, symbol: m.symbol }; break; diff --git a/server/src/gas.test.js b/server/src/gas.test.js new file mode 100644 index 0000000..e39d8ff --- /dev/null +++ b/server/src/gas.test.js @@ -0,0 +1,296 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import os from 'node:os'; +import fs from 'node:fs'; +import path from 'node:path'; + +process.env.NODE_ENV = 'test'; +process.env.TIME_MODE = 'turbo'; +process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'wibosim-gas-')); +const { settings } = await import('./settings.js'); +const { Store } = await import('./store.js'); +const { Game } = await import('./game.js'); +const { yearPhase, gasSeason, storageNorm, winterWeight, INSTRUMENTS } = await import('./assets.js'); +const { analyze, mentionsGas } = await import('./newsanalysis.js'); +const { stepMacro, createMacro, BILLS } = await import('./world.js'); +const { ruleImpact } = await import('./population.js'); +settings.news.enabled = false; + +const newGame = (dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wibosim-gas-g-'))) => ({ g: new Game({ store: new Store(dir), now: () => Date.now() }), dir }); +/** Handelstag, der im Spieljahr auf die Stelle phase (0 = 1. Januar) fällt */ +const dayAt = (phase, Y) => 1 + Math.round(((phase - 0.25 + 1) % 1) * Y); +/** GAS so bewerten, als wäre der Gasmarkt beim Handelstag day (Speicherabweichung gap) */ +function gasValue(g, day, gap = 0) { + const st = g.assets.gasState(); + const keep = { day: st.day, gap: st.gap }; + Object.assign(st, { day, gap }); + try { return g.assets.value(g.stocks.get('GAS'), g.econ.ctx()); } finally { Object.assign(st, keep); } +} + +test('Erdgas: Instrument wie Öl (Rohstoff, Handelszeiten, Startkurs um 35 €)', () => { + const def = INSTRUMENTS.find((i) => i.symbol === 'GAS'); + const oel = INSTRUMENTS.find((i) => i.symbol === 'OEL'); + assert.equal(def.kind, 'commodity'); + assert.equal(def.name, 'Erdgas (1 MWh)'); + assert.equal(def.price, 35); + assert.ok(Math.abs(def.vol - 0.6) < 1e-9); + assert.equal(!!def.allDay, !!oel.allDay, 'Handelszeiten wie Öl'); + assert.equal(!!def.noShort, !!oel.noShort); + const { g } = newGame(); + const s = g.stocks.get('GAS'); + assert.ok(s && s.asset && 'supply' in s.asset, 'Zustand angelegt'); + assert.ok(s.last > 28 && s.last < 45, `Startkurs ${s.last}`); + assert.ok(Math.abs(s.last / s.fv - 1) < 0.01, 'Startkurs = innerer Wert (kein Sprung am ersten Tag)'); + assert.ok(g.tickers().some((t) => t.symbol === 'GAS' && t.kind === 'commodity'), 'erscheint in der Marktliste'); +}); + +test('Erdgas: Heizsaison – im Winter teurer, im Sommer billiger (etwa ±15 %), am Spieldatum hängend', () => { + const Y = 84; + // Spieltag 1 liegt Anfang April + assert.ok(Math.abs(yearPhase(1, Y) - 0.25) < 1e-9); + assert.ok(Math.abs(yearPhase(1 + Y, Y) - 0.25) < 1e-9, 'Jahreszyklus'); + const jan = gasSeason(0.04), jul = gasSeason(0.54); + assert.ok(Math.exp(jan) - 1 > 0.13 && Math.exp(jan) - 1 < 0.17, `Januar ${jan}`); + assert.ok(Math.exp(jul) - 1 < -0.11 && Math.exp(jul) - 1 > -0.15, `Juli ${jul}`); + // im Spiel: GAS-Wert im Januar gegenüber Juli (ohne Speicherabweichung) + const { g } = newGame(); + const Yg = g.cfg.daysPerYear; + const w = gasValue(g, dayAt(0.04, Yg)), s = gasValue(g, dayAt(0.54, Yg)); + assert.ok(w / s > 1.22 && w / s < 1.38, `Winter/Sommer ${(w / s).toFixed(3)}`); + // Der normale Saisonverlauf ist eingeplant: er wirkt nicht auf Inflation und Gewinne + const gs = g.stocks.get('GAS'); + const fv0 = gs.fv; + try { + const st = g.assets.gasState(), keep = st.day; + st.day = dayAt(0.04, Yg); gs.fv = gasValue(g, st.day); + const winterExt = g.assets.ext().gas; + st.day = dayAt(0.54, Yg); gs.fv = gasValue(g, st.day); + const summerExt = g.assets.ext().gas; + st.day = keep; + assert.ok(Math.abs(winterExt - summerExt) < 0.01, `ext.gas Winter ${winterExt} / Sommer ${summerExt}`); + } finally { gs.fv = fv0; } +}); + +test('Gasspeicher: im Sommer gefüllt, im Winter geleert; knapper Speicher vor/im Winter treibt den Preis', () => { + // üblicher Füllstand: voll im Oktober, fast leer im April + assert.ok(storageNorm(0.79) > 0.88 && storageNorm(0.29) < 0.36); + const phases = Array.from({ length: 12 }, (_, i) => (i + 0.5) / 12); + for (const ph of phases) { + const rising = storageNorm(ph + 0.01) > storageNorm(ph); + if (ph > 0.35 && ph < 0.75) assert.ok(rising, `Sommer (${ph.toFixed(2)}): wird gefüllt`); + if (ph > 0.85 || ph < 0.2) assert.ok(!rising, `Winter (${ph.toFixed(2)}): wird geleert`); + } + assert.ok(winterWeight(0.04) > 0.9 && winterWeight(0.7) > 0.4 && winterWeight(0.54) < 0.1, 'Gewicht: Winter hoch, Herbst mittel, Hochsommer kaum'); + + const { g } = newGame(); + const Y = g.cfg.daysPerYear; + // Dezember: 12 Prozentpunkte unter dem Üblichen → deutlich teurer + const dec = dayAt(0.96, Y); + const low = gasValue(g, dec, -0.12) / gasValue(g, dec, 0); + assert.ok(low > 1.1 && low < 1.2, `Dezember, Speicher knapp: ×${low.toFixed(3)}`); + // Hochsommer: dieselbe Lücke wirkt kaum + const jul = dayAt(0.55, Y); + const lowSummer = gasValue(g, jul, -0.12) / gasValue(g, jul, 0); + assert.ok(lowSummer < 1.02, `Juli, Speicher knapp: ×${lowSummer.toFixed(3)}`); + // Vor dem Winter (September) wirkt sie schon spürbar + const sep = dayAt(0.7, Y); + assert.ok(gasValue(g, sep, -0.12) / gasValue(g, sep, 0) > 1.05, 'September: Lücke vor dem Winter treibt den Preis'); + + // Fortschreiben: Füllstand folgt dem Jahresverlauf, Verlauf wird gespeichert, Wert bleibt endlich + const rnd = Math.random; + let flip = 0; + Math.random = () => (flip++ % 2 ? 0.25 : 0.5); // gauss() ≈ 0: nur der übliche Jahresverlauf + try { + const st = g.assets.gasState(); + st.gap = 0; + const fills = []; + for (let i = 0; i < Y; i++) { g.day++; g.econ.revalue(() => g.assets.stepGas()); fills.push(g.assets.storage()); } + assert.ok(Math.max(...fills) > 0.85 && Math.min(...fills) < 0.4, 'ein Spieljahr: voll und fast leer'); + assert.ok(st.history.length > 10 && st.history.at(-1).day === g.day); + assert.ok(Number.isFinite(g.stocks.get('GAS').fair)); + } finally { Math.random = rnd; } +}); + +test('Speicherpflicht und Gaspreisbremse wirken; Gesetze im bestehenden Format', () => { + const brake = BILLS.find((b) => b.id === 'gasbrake'), duty = BILLS.find((b) => b.id === 'gasstore'); + assert.ok(brake && duty); + for (const b of [brake, duty]) { + assert.ok(['markt', 'staat', 'oeko'].includes(b.axis) && Number.isFinite(b.cost) && b.keywords.length && b.effects); + } + assert.ok(brake.cost > duty.cost && brake.cost > 0, 'Bremse kostet den Haushalt deutlich'); + assert.ok(brake.effects.consumer > 0 && (brake.macro.inflation ?? 0) < 0, 'entlastet Konsum'); + assert.ok(ruleImpact(brake).rente > 0 && ruleImpact(brake).land > 0, 'Bevölkerung begrüßt die Bremse'); + + const { g } = newGame(); + const gs = g.stocks.get('GAS'); + const Y = g.cfg.daysPerYear; + // teures Gas: 30 % über dem saisonüblichen Preis + const st = g.assets.gasState(); + gs.fv = 35 * Math.exp(0.3 + gasSeason(yearPhase(st.day, Y))); + assert.ok(Math.abs(g.assets.ext().gas - 0.3) < 1e-6); + assert.ok(Math.abs(g.assets.ext().gasCpi - 0.3) < 1e-6); + g.pol.inForce.gasbrake = { key: 'gasbrake', billId: 'gasbrake', title: brake.title, day: g.day, effects: {}, macro: {}, cost: brake.cost }; + assert.ok(Math.abs(g.assets.ext().gasCpi - 0.15) < 1e-6, 'Bremse halbiert die Wirkung auf Verbraucher'); + assert.ok(Math.abs(g.assets.ext().gas - 0.3) < 1e-6, '… nicht die Wirkung auf die Unternehmen'); + delete g.pol.inForce.gasbrake; + + // Speicherpflicht: Lücke schließt sich schneller und Ziel liegt über dem Üblichen + const rnd = Math.random; + Math.random = () => 0.5; + try { + const run = (withDuty) => { + if (withDuty) g.pol.inForce.gasstore = { key: 'gasstore', billId: 'gasstore', title: duty.title, day: g.day, effects: {}, macro: {}, cost: duty.cost }; + else delete g.pol.inForce.gasstore; + st.gap = -0.15; st.day = g.day; + const d0 = g.day; + for (let i = 0; i < 10; i++) { g.day++; g.assets.stepGas(); } + const gap = st.gap; g.day = d0; st.day = d0; + return gap; + }; + const free = run(false), dutyGap = run(true); + assert.ok(dutyGap > free + 0.03, `Lücke nach 10 Tagen: frei ${free.toFixed(3)}, mit Pflicht ${dutyGap.toFixed(3)}`); + // Ereignis mit Speicherverlust fällt mit Pflicht kleiner aus + st.gap = 0; + g.assets.gasShock(0, 'Test', -0.1, false); + assert.ok(Math.abs(st.gap + 0.06) < 1e-9, `Lücke ${st.gap}`); + } finally { Math.random = rnd; delete g.pol.inForce.gasstore; } +}); + +test('Teures Gas: Inflation höher, Wachstum etwas schwächer, Bevölkerung murrt, Versorger gewinnen, Stahl verliert', () => { + const rnd = Math.random; + Math.random = () => 0.3; + try { + const a = createMacro(), b = createMacro(); + a.ext = { oil: 0, usd: 0, risk: 0, gas: 0, gasCpi: 0 }; + b.ext = { oil: 0, usd: 0, risk: 0, gas: 0.3, gasCpi: 0.3 }; + for (let i = 0; i < 84; i++) { stepMacro(a, 1 / 84, 2 / 84); stepMacro(b, 1 / 84, 2 / 84); } + const dInfl = b.inflation - a.inflation, dGdp = b.gdp - a.gdp; + assert.ok(dInfl > 0.1 && dInfl < 0.4, `Inflation +${dInfl.toFixed(2)} Pp. (moderat)`); + assert.ok(dGdp < 0 && dGdp > -0.2, `Wachstum ${dGdp.toFixed(2)} Pp.`); + } finally { Math.random = rnd; } + + const { g } = newGame(); + const gs = g.stocks.get('GAS'); + const Y = g.cfg.daysPerYear; + const base = 35 * Math.exp(gasSeason(yearPhase(g.assets.gasState().day, Y))); + const fv0 = gs.fv; + const at = (dev) => { + gs.fv = base * Math.exp(dev); + const ctx = g.econ.ctx(); + const v = (sym) => g.econ.valueOf(g.stocks.get(sym), ctx); + const pop = g.pop.view().groups; + return { HLIO: v('HLIO'), STHL: v('STHL'), NVLT: v('NVLT'), KRMA: v('KRMA'), heat: Object.fromEntries(pop.map((x) => [x.id, x.reasons.find((r) => r.label.startsWith('Heizkosten'))?.amt ?? 0])) }; + }; + try { + const n = at(0), hi = at(0.3); + assert.ok(hi.HLIO / n.HLIO > 1.04, 'Versorger profitiert'); + assert.ok(hi.STHL / n.STHL < 0.97, 'Stahl leidet'); + assert.ok(hi.KRMA / n.KRMA < 1, 'Handel leidet leicht'); + assert.ok(Math.abs(hi.NVLT / n.NVLT - 1) < 1e-9, 'Technologie unberührt'); + assert.ok(hi.heat.land < 0 && hi.heat.rente < 0, `Heizkosten belasten Land und Rentner: ${JSON.stringify(hi.heat)}`); + assert.ok(hi.heat.land > -0.15, 'moderat'); + } finally { gs.fv = fv0; } +}); + +test('Nachrichten zum Gas: eigenes Thema, Vorzeichen, Stocken/Umkehr, Sprachmodell kennt das Thema', async () => { + const cases = [ + ['Gaspreis steigt kräftig', 1], ['Gaspreis fällt deutlich', -1], ['Erdgas wird teurer', 1], + ['Gasspeicher gut gefüllt', -1], ['Gasspeicher leeren sich schneller als erwartet', 1], ['Speicherfüllstand sinkt auf Rekordtief', 1], + ['LNG-Lieferungen steigen deutlich', -1], ['Gaslieferungen aus dem Osten gedrosselt', 1], ['Pipeline-Störung treibt Gaspreise', 1], + ['Flüssiggas-Importe nehmen zu', -1], ['Gasmangel droht im Winter', 1], ['Regierung beschließt Gaspreisbremse', -1], ['Gasumlage kommt', 1], + ['Gaspreisanstieg gerät ins Stocken', -1], ['Gaspreis steigt nicht weiter', -1], ['Erdgaspreise sinken auf Jahrestief', -1], + ]; + for (const [title, sign] of cases) { + const a = analyze(title); + assert.equal(Math.sign(a.topics.gas ?? 0), sign, `${title}: ${JSON.stringify(a.topics)}`); + assert.equal(a.topics.oil, undefined, `${title}: kein Öl-Thema`); + // für Verbraucher und Börse: teures Gas schlecht, billiges gut + assert.equal(Math.sign(a.sentiment), -sign, `${title}: Stimmung ${a.sentiment}`); + assert.ok(a.sectors.includes('energy'), `${title}: Energie betroffen`); + assert.equal(Math.sign(a.sectorImpact.energy), sign, `${title}: Versorger`); + } + // Öl bleibt Öl, beides zusammen geht auch + assert.equal(analyze('Ölpreis steigt kräftig').topics.gas, undefined); + const both = analyze('Öl- und Gaspreise steigen'); + assert.ok(both.topics.gas > 0 && both.topics.oil > 0); + assert.equal(analyze('Gastronomie meldet Umsatzplus').topics.gas, undefined, 'kein Gas in „Gastronomie“'); + assert.ok(mentionsGas('Gasspeicher-Füllstand sinkt') && mentionsGas('LNG-Terminal eröffnet') && !mentionsGas('Gastronomie boomt')); + // Sprachmodell: Prompt nennt das Thema, Prüfung lässt es durch + const src = fs.readFileSync(new URL('./newsanalysis.js', import.meta.url), 'utf8'); + assert.match(src, /oil, gas, rates/); + const { validate } = await import('./newsanalysis.js'); + assert.deepEqual(validate({ relevant: true, sentiment: -0.3, topics: { gas: 0.8 } }).topics, { gas: 0.8 }); +}); + +test('Gas-Meldung bewegt GAS, Versorger und Stahl – Öl nur schwach, WiboCoin gar nicht; Ursachen-Anzeige stimmt', () => { + const { g } = newGame(); + const rnd = Math.random; + let id = 0; + const run = (title, analysis = null) => { + const a = analysis ?? analyze(title); + const f0 = new Map([...g.stocks.values()].map((s) => [s.symbol, s.fair])); + const sup0 = g.stocks.get('GAS').asset.supply, sent0 = g.macro.sentiment, mood0 = { ...g.macro.sectorMood }; + g.causes.state.bySym = {}; + Math.random = () => 0.5; + try { g.addNews({ id: `gt${id++}`, title, source: 'Test', real: true, sentiment: a.sentiment, sectors: a.sectors, ts: Date.now(), analysis: a }); } finally { Math.random = rnd; } + const mv = Object.fromEntries([...g.stocks.values()].map((s) => [s.symbol, Math.log(s.fair / f0.get(s.symbol))])); + const booked = g.causes.view('GAS')[0]?.items.find((x) => x.label === `Nachricht: ${title}`)?.pct ?? 0; + for (const s of g.stocks.values()) s.fair = f0.get(s.symbol); + g.stocks.get('GAS').asset.supply = sup0; g.macro.sentiment = sent0; Object.assign(g.macro.sectorMood, mood0); + g.news = []; + return { mv, booked }; + }; + const up = run('Gaspreis steigt kräftig'); + assert.ok(up.mv.GAS > 0.02 && up.mv.GAS < 0.12, `GAS ${(up.mv.GAS * 100).toFixed(2)} %`); + assert.ok(up.mv.OEL > 0 && up.mv.OEL < up.mv.GAS * 0.25, `OEL nur schwach: ${(up.mv.OEL * 100).toFixed(2)} %`); + assert.equal(up.mv.WIBC, 0, 'WiboCoin unberührt'); + assert.ok(up.mv.HLIO > 0, 'Versorger steigt'); + assert.ok(up.mv.STHL < 0 && up.mv.KRMA < 0, 'Stahl und Handel fallen'); + assert.ok(Math.abs(up.booked - (Math.exp(up.mv.GAS) - 1) * 100) < 0.01, `Ursachen: gebucht ${up.booked} %`); + const down = run('Gasspeicher randvoll – Gaspreis fällt deutlich'); + assert.ok(down.mv.GAS < -0.02, `GAS ${(down.mv.GAS * 100).toFixed(2)} %`); + assert.equal(down.mv.WIBC, 0); + // Ölmeldung: Gas zieht nur leicht mit + const oil = run('Ölpreis steigt kräftig'); + assert.ok(oil.mv.GAS > 0 && oil.mv.GAS < oil.mv.OEL * 0.4, `Öl-Meldung: GAS ${(oil.mv.GAS * 100).toFixed(2)} %, OEL ${(oil.mv.OEL * 100).toFixed(2)} %`); + // Sprachmodell schreibt einer Meldung ohne Gasbezug ein Gas-Thema zu: halbe Wirkung + const full = run('Gaspreis steigt', { by: 'llm', sentiment: 0, sectors: [], topics: { gas: 0.8 }, strength: 0.5, reasons: [] }); + const half = run('Marktbericht: DAX schließt im Minus', { by: 'llm', sentiment: 0, sectors: [], topics: { gas: 0.8 }, strength: 0.5, reasons: [] }); + assert.ok(Math.abs(half.mv.GAS / full.mv.GAS - 0.5) < 0.02, `ohne Gasbezug ×${(half.mv.GAS / full.mv.GAS).toFixed(2)}`); +}); + +test('Alter Spielstand ohne Erdgas: GAS wird sauber ergänzt, Gasmarkt angelegt, Spiel läuft weiter', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wibosim-gas-old-')); + const { g } = newGame(dir); + g.day = 137; + const oel = g.stocks.get('OEL').last; + g.flush(true); + g.store.close(); + // Spielstand so zurechtstutzen, wie ihn eine Version ohne Erdgas gespeichert hätte + const store = new Store(dir); + const { meta } = store.load(); + delete meta.stocks.GAS; + delete meta.macro.gas; + meta.macro.ext = { oil: 0.05, usd: 0, risk: 0 }; + meta.core.day = 137; + store.write({ meta }); + store.close(); + + const g2 = new Game({ store: new Store(dir), now: () => Date.now() }); + const s = g2.stocks.get('GAS'); + assert.ok(s, 'GAS vorhanden'); + assert.equal(s.kind, 'commodity'); + assert.ok(s.asset && s.asset.supply === 0 && s.asset.drift === 0, 'Zustand frisch angelegt'); + assert.ok(g2.macro.gas && g2.macro.gas.day === 137 && g2.macro.gas.gap === 0, 'Gasmarkt im Makrozustand angelegt'); + assert.ok(Math.abs(s.last / s.fv - 1) < 0.01 && s.prevClose === s.last, `Kurs aus dem inneren Wert (${s.last} / ${s.fv})`); + assert.equal(g2.stocks.get('OEL').last, oel, 'übrige Werte unverändert'); + assert.ok(Number.isFinite(g2.assets.ext().gas)); + // ein Handelstag und Takte laufen ohne Fehler; danach wird GAS mitgespeichert + g2.econ.newDay(); + for (let i = 0; i < 20; i++) g2.econ.step(1000, true); + assert.ok(Number.isFinite(s.fair) && s.fair > 0); + assert.ok(g2.econ.publicMacro().gas.storage > 0); + g2.flush(true); + assert.ok(g2.store.load().meta.stocks.GAS, 'GAS im Spielstand'); + assert.ok(g2.store.load().meta.macro.gas, 'Gasspeicher im Spielstand'); +}); diff --git a/server/src/news.js b/server/src/news.js index 55147a1..42c85f1 100644 --- a/server/src/news.js +++ b/server/src/news.js @@ -28,6 +28,8 @@ export const SIM_TEMPLATES = [ // Energie ['Ölpreis springt nach Förderkürzung des Petrolia-Kartells auf Jahreshoch', -1, 'energy'], ['Petrolia-Kartell weitet Fördermenge aus – Ölpreis fällt deutlich', 1, 'energy'], + ['Gasspeicher leeren sich schneller als erwartet – Gaspreis steigt kräftig', -1, 'energy'], + ['Gasspeicher randvoll – Gaspreis fällt deutlich', 1, 'energy'], ['Wasserstoff-Pipeline: Regierung sagt Milliardenförderung zu', 1, 'energy'], ['Wasserstoff-Pipeline gescheitert: Energieversorger schreiben Milliarden ab', -1, 'energy'], // Auto diff --git a/server/src/news.test.js b/server/src/news.test.js index 83a4cda..9b44bd2 100644 --- a/server/src/news.test.js +++ b/server/src/news.test.js @@ -23,7 +23,7 @@ test('Simulierte Meldungen: Vorlagen sind je Branche und Thema ausgeglichen (kei const g = new Game({ store: new Store(fs.mkdtempSync(path.join(os.tmpdir(), 'wibosim-news-g-'))), now: () => Date.now() }); const stocks = [...g.stocks.values()]; const sectors = [...new Set(stocks.filter((s) => s.kind === 'stock').map((s) => s.sector))]; - const keys = [...sectors, 'OEL', 'GOLD', 'USD']; + const keys = [...sectors, 'OEL', 'GAS', 'GOLD', 'USD']; const sum = Object.fromEntries(keys.map((k) => [k, 0])), abs = Object.fromEntries(keys.map((k) => [k, 0])); const rnd = Math.random; try { @@ -31,7 +31,7 @@ test('Simulierte Meldungen: Vorlagen sind je Branche und Thema ausgeglichen (kei Math.random = () => 0.5; const n = simulatedNews(i); const f0 = new Map(stocks.map((s) => [s.symbol, s.fair])); - const mood0 = { ...g.macro.sectorMood }, sent0 = g.macro.sentiment, sup0 = g.stocks.get('OEL').asset.supply; + const mood0 = { ...g.macro.sectorMood }, sent0 = g.macro.sentiment, sup0 = g.stocks.get('OEL').asset.supply, gsup0 = g.stocks.get('GAS').asset.supply; g.econ.newsImpact(n); const move = {}; for (const sec of sectors) { @@ -39,10 +39,10 @@ test('Simulierte Meldungen: Vorlagen sind je Branche und Thema ausgeglichen (kei // Sofortsprung plus Branchenstimmung (treibt die Drift über den Tag) move[sec] = ss.reduce((a, s) => a + Math.log(s.fair / f0.get(s.symbol)), 0) / ss.length + (g.macro.sectorMood[sec] - mood0[sec]) * 0.02; } - for (const sym of ['OEL', 'GOLD', 'USD']) move[sym] = Math.log(g.stocks.get(sym).fair / f0.get(sym)); + for (const sym of ['OEL', 'GAS', 'GOLD', 'USD']) move[sym] = Math.log(g.stocks.get(sym).fair / f0.get(sym)); for (const k of keys) { sum[k] += move[k]; abs[k] += Math.abs(move[k]); } for (const s of stocks) s.fair = f0.get(s.symbol); - Object.assign(g.macro.sectorMood, mood0); g.macro.sentiment = sent0; g.stocks.get('OEL').asset.supply = sup0; + Object.assign(g.macro.sectorMood, mood0); g.macro.sentiment = sent0; g.stocks.get('OEL').asset.supply = sup0; g.stocks.get('GAS').asset.supply = gsup0; } } finally { Math.random = rnd; } for (const k of keys) { diff --git a/server/src/newsanalysis.js b/server/src/newsanalysis.js index 35a7eee..39e0d8d 100644 --- a/server/src/newsanalysis.js +++ b/server/src/newsanalysis.js @@ -9,18 +9,18 @@ // Seine Antwort wird streng geprüft; bei Fehlern, Zeitüberschreitung oder Unsinn gilt das Regelwerk. // // Ergebnis (beide Stufen gleich): -// { sentiment −1…1, sectors[], topics {oil, rates, inflation, usd, gold, risk, tariffs, labor, growth} je −1…1, +// { sentiment −1…1, sectors[], topics {oil, gas, rates, inflation, usd, gold, risk, tariffs, labor, growth, crypto} je −1…1, // strength 0…1, relevant, reasons[] (kurze deutsche Begründungen), by 'regeln'|'llm' } -// Themen-Vorzeichen: + = „mehr davon“ (Ölpreis höher, Zinsen höher, mehr Risiko, mehr Zölle, bessere Beschäftigung, mehr Wachstum). +// Themen-Vorzeichen: + = „mehr davon“ (Ölpreis höher, Gaspreis höher, Zinsen höher, mehr Risiko, mehr Zölle, bessere Beschäftigung, mehr Wachstum). import { SECTORS } from './world.js'; export const TOPICS = { - oil: 'Ölpreis', rates: 'Zinsen', inflation: 'Inflation', usd: 'Dollar', gold: 'Goldpreis', + oil: 'Ölpreis', gas: 'Gaspreis', rates: 'Zinsen', inflation: 'Inflation', usd: 'Dollar', gold: 'Goldpreis', risk: 'Krisenrisiko', tariffs: 'Zölle/Handelsstreit', labor: 'Arbeitsmarkt', growth: 'Konjunktur', crypto: 'Krypto', }; // Wirkung eines steigenden Themas auf die allgemeine Börsenstimmung -const TOPIC_POLARITY = { oil: -0.5, rates: -0.5, inflation: -0.6, usd: 0, gold: 0, risk: -1, tariffs: -0.8, labor: 1, growth: 1, crypto: 0 }; +const TOPIC_POLARITY = { oil: -0.5, gas: -0.4, rates: -0.5, inflation: -0.6, usd: 0, gold: 0, risk: -1, tariffs: -0.8, labor: 1, growth: 1, crypto: 0 }; // ------------------------------------------------------------ Wortzerlegung const UMLAUT = /[^a-z0-9äöüß%]+/g; @@ -114,6 +114,7 @@ const UP = lex({ 'hebt': 1, 'anheben': 1, 'anhebung*': 1, 'angehoben': 1, 'verteuer*': 1, 'teurer': 1, 'zieht an': 1, 'ziehen an': 1, 'plus': 0.8, 'wächst': 1, 'wachsen': 1, 'gewachsen': 1, 'zunahme': 1, 'nimmt zu': 1, 'nehmen zu': 1, 'aufwärts': 1, 'kräftiger': 0.6, 'stärker': 0.6, 'gewinnt': 0.8, 'gewinnen': 0.8, 'aufwertung*': 1, 'wertet auf': 1, 'werten auf': 1, 'aufgewertet': 1, 'festigt sich': 0.6, 'festigen sich': 0.6, 'höhenflug': 1, + 'gefüllt': 0.6, 'randvoll': 1, 'aufgefüllt': 0.8, 'füllen sich': 0.8, 'füllt sich': 0.8, 'verschärf*': 1, 'droht': 0.6, 'drohen': 0.6, 'ausgeweitet': 0.8, 'hellt sich auf': 0.8, 'hellen sich auf': 0.8, 'aufgehellt': 0.8, }); const DOWN = lex({ @@ -123,6 +124,7 @@ const DOWN = lex({ 'bricht ein': 1.3, 'brechen ein': 1.3, 'eingebrochen': 1.3, 'einbruch': 1.3, 'verbillig*': 1, 'billiger': 1, 'günstiger': 0.8, 'schrumpft': 1, 'schrumpfen': 1, 'geschrumpft': 1, 'gibt nach': 0.8, 'geben nach': 0.8, 'schwächt sich ab': 0.8, 'schwächen sich ab': 0.8, 'abgeschwächt': 0.8, 'flaut ab': 0.8, 'flauen ab': 0.8, 'abgeflaut': 0.8, 'nachgegeben': 0.8, 'tiefststand': 1.2, 'jahrestief': 1.2, 'mehrjahrestief': 1.2, 'abschwächung': 0.8, 'schwächer': 0.8, 'verliert': 1, 'verlieren': 1, 'verloren': 1, + 'leeren sich': 1, 'leert sich': 1, 'geleert': 0.8, 'leer': 0.8, 'halbleer': 0.6, 'kürzt': 1, 'kürzen': 1, 'gekürzt': 1, 'kürzung*': 1, 'drosselt': 1, 'drosseln': 1, 'gedrosselt': 1, 'abnahme': 1, 'nimmt ab': 1, 'entspannt': 0.8, 'entspannung': 0.8, 'lockert': 0.8, 'lockerung*': 0.8, 'niedriger': 0.8, 'abwärts': 1, 'stagniert': 0.4, 'unter druck': 0.8, 'geht zurück': 1, 'gehen zurück': 1, 'ging zurück': 1, 'gingen zurück': 1, 'zurückgegangen': 1, 'trübt sich ein': 0.8, 'trüben sich ein': 0.8, 'eingetrübt': 0.8, @@ -133,9 +135,20 @@ const TOPIC_WORDS = lex({ 'ölpreis*': { t: 'oil' }, '*ölpreis': { t: 'oil' }, '*ölpreise': { t: 'oil' }, 'rohöl*': { t: 'oil' }, 'erdöl*': { t: 'oil' }, 'öl': { t: 'oil' }, 'brent': { t: 'oil' }, 'wti': { t: 'oil' }, 'opec*': { t: 'oil', cartel: true }, 'petrolia*': { t: 'oil', cartel: true }, 'barrel': { t: 'oil' }, '*spritpreis*': { t: 'oil', w: 0.6 }, '*benzinpreis*': { t: 'oil', w: 0.6 }, 'heizöl*': { t: 'oil', w: 0.6 }, - '*gaspreis*': { t: 'oil', w: 0.5 }, '*energiepreis*': { t: 'oil', w: 0.6 }, '*strompreis*': { t: 'oil', w: 0.3 }, + '*energiepreis*': { t: 'oil', w: 0.6 }, 'förderkürzung*': { t: 'oil', dir: 1, w: 1.2 }, 'förderstopp': { t: 'oil', dir: 1, w: 1.2 }, 'lieferstopp': { t: 'oil', dir: 1, w: 0.8 }, 'fördermenge*': { t: 'oil', supply: true }, 'förderung': { t: 'oil', supply: true, weak: true }, 'produktionskürzung*': { t: 'oil', dir: 1, w: 0.6, weak: true }, + // Erdgas (eigenes Thema). Speicherfüllstand und Lieferungen wirken umgekehrt: mehr Gas im Speicher → billiger. + // Gaspreisbremse/Gasumlage betreffen den Preis für Verbraucher – schwach, mit fester Richtung. + 'gaspreisbremse*': { t: 'gas', dir: -1, w: 0.4 }, 'gasumlage*': { t: 'gas', dir: 1, w: 0.4 }, + 'gaspreisanstieg*': { t: 'gas', dir: 1 }, 'gaspreisrückgang': { t: 'gas', dir: -1 }, + 'gaspreis': { t: 'gas' }, 'gaspreise': { t: 'gas' }, 'gaspreisen': { t: 'gas' }, '*gaspreis': { t: 'gas' }, '*gaspreise': { t: 'gas' }, '*gaspreisen': { t: 'gas' }, + 'erdgas*': { t: 'gas' }, 'gas': { t: 'gas', w: 0.8 }, 'gasmarkt*': { t: 'gas', w: 0.8 }, 'heizkosten': { t: 'gas', w: 0.5 }, '*strompreis*': { t: 'gas', w: 0.3 }, + 'gasspeicher*': { t: 'gas', invert: true }, 'speicherfüllstand*': { t: 'gas', invert: true }, + 'gasmangel*': { t: 'gas', dir: 1 }, 'gasknappheit': { t: 'gas', dir: 1 }, 'gasnotstand': { t: 'gas', dir: 1, w: 1.2 }, 'gaslieferstopp*': { t: 'gas', dir: 1, w: 1.2 }, + 'pipelinestörung*': { t: 'gas', dir: 1, w: 0.8 }, 'pipelineausfall': { t: 'gas', dir: 1, w: 0.8 }, + 'gaslieferung*': { t: 'gas', supply: true }, 'gasversorgung*': { t: 'gas', supply: true }, 'gasimport*': { t: 'gas', supply: true }, + 'lng*': { t: 'gas', supply: true }, 'flüssiggas*': { t: 'gas', supply: true }, 'pipeline*': { t: 'gas', supply: true, w: 0.6 }, 'zins': { t: 'rates' }, 'zinsen': { t: 'rates' }, '*zins': { t: 'rates' }, '*zinsen': { t: 'rates' }, 'leitzins*': { t: 'rates' }, 'zinserhöhung*': { t: 'rates', dir: 1 }, 'zinsanhebung*': { t: 'rates', dir: 1 }, 'zinsschritt*': { t: 'rates', dir: 1, w: 0.6 }, 'zinssenkung*': { t: 'rates', dir: -1 }, 'zinswende': { t: 'rates', dir: 1, w: 0.6 }, 'zinspause': { t: 'rates', dir: -1, w: 0.4 }, @@ -176,7 +189,7 @@ const TOPIC_WORDS = lex({ const SECTOR_WORDS = { tech: ['chip*', '*chip', '*chips', 'halbleiter*', '*halbleiter', 'software*', '*software', 'ki', 'künstliche intelligenz', 'digital*', 'tech*', '*tech', 'cloud*', 'cyber*', 'ai', 'rechenzentr*', 'smartphone*', 'internet*', 'computer*', 'nvidia', 'apple', 'microsoft', 'google', 'sap', 'openai', 'telekom*'], - energy: ['energie*', '*energie', 'strom*', '*strom', 'gas', 'erdgas*', 'flüssiggas*', '*gaspreis*', 'öl', '*öl', 'ölpreis*', 'rohöl*', 'opec*', 'petrolia*', 'wasserstoff*', + energy: ['energie*', '*energie', 'strom*', '*strom', 'gas', 'erdgas*', 'flüssiggas*', '*gaspreis*', 'gasspeicher*', 'gasliefer*', 'lng*', 'öl', '*öl', 'ölpreis*', 'rohöl*', 'opec*', 'petrolia*', 'wasserstoff*', 'solar*', 'windkraft*', 'windpark*', 'windräder', 'kohle*', 'atom*', 'kernkraft*', 'pipeline*', 'raffinerie*', 'kraftwerk*', 'netzbetreiber*', 'rwe', 'eon', 'shell', 'bp'], auto: ['auto*', '*auto', '*autos', 'eauto*', 'elektroauto*', 'fahrzeug*', '*fahrzeug', '*fahrzeuge', 'zulieferer*', '*zulieferer', 'verbrenner*', 'pkw*', 'neuzulassung*', 'vw', 'volkswagen', 'bmw', 'mercedes*', 'porsche', 'tesla', 'stellantis', 'toyota', 'continental', 'bosch'], @@ -396,6 +409,15 @@ export function mentionsCrypto(text) { return toks.some((_, i) => CRYPTO_LEX.some((c) => c.test(toks, i))); } +// Gas- bzw. Energiebezug in der Überschrift – sonst wirkt ein vom Sprachmodell zugeschriebenes Gas-Thema nur halb (economy.js) +const GAS_LEX = ['gas', 'gase', 'gasmarkt*', 'gaspreis*', '*gaspreis*', 'gasspeicher*', 'gasliefer*', 'gasversorg*', 'gasumlage*', 'gasmangel*', 'gasimport*', + 'erdgas*', 'flüssiggas*', 'lng*', 'pipeline*', 'speicherfüllstand*', 'heizkosten', 'energiepreis*', '*energiepreis*', 'strompreis*', '*strompreis*', 'energiekrise*'].map(compile); +/** Nennt der Text Erdgas, Gasspeicher, Flüssiggas oder Energiepreise? */ +export function mentionsGas(text) { + const toks = tokenize(text, { split: true }); + return toks.some((_, i) => GAS_LEX.some((c) => c.test(toks, i))); +} + /** Regelbasierte Auswertung einer Meldung */ export function analyze(title, desc = '') { const acc = { mood: 0, hits: 0, topics: {}, sectorScore: {}, reasons: [], anchor: false, surprise: false }; @@ -418,12 +440,13 @@ export function analyze(title, desc = '') { let sentiment = clamp1(Math.tanh(raw)); const sectors = Object.entries(acc.sectorScore).filter(([, v]) => v >= 1).sort((a, b) => b[1] - a[1]).slice(0, 3).map(([k]) => k); // Energiebranche profitiert von teurem Öl, Rüstung von Krisen: Branchen ergänzen - if ((topics.oil ?? 0) !== 0 && !sectors.includes('energy')) sectors.push('energy'); + if (((topics.oil ?? 0) !== 0 || (topics.gas ?? 0) !== 0) && !sectors.includes('energy')) sectors.push('energy'); if ((topics.risk ?? 0) > 0.3 && !sectors.includes('defense') && acc.sectorScore.defense) sectors.push('defense'); // Branchen, die bei einem Thema gegen den Markt laufen (Rüstung bei Krisen, Energie bei teurem Öl, Banken bei steigenden Zinsen) const sectorImpact = {}; if (sectors.includes('defense') && topics.risk) sectorImpact.defense = clamp1(topics.risk * 0.8); - if (sectors.includes('energy') && topics.oil) sectorImpact.energy = clamp1(topics.oil * 0.7 + (acc.mood > 0 ? 0.1 : 0)); + // Energie bei teurem Öl oder Gas (Versorger, Förderer) + if (sectors.includes('energy') && (topics.oil || topics.gas)) sectorImpact.energy = clamp1((topics.oil ?? 0) * 0.7 + (topics.gas ?? 0) * 0.5 + (acc.mood > 0 ? 0.1 : 0)); if (sectors.includes('banks') && topics.rates) sectorImpact.banks = clamp1(topics.rates * 0.4); const relevant = Object.keys(topics).length > 0 || (acc.hits > 0 && (sectors.length > 0 || acc.anchor)); if (!relevant) sentiment = 0; @@ -451,8 +474,8 @@ Felder: - "sentiment": Zahl von -1 bis 1 – Wirkung auf die Börse insgesamt (negativ = Kurse fallen). - "sectors": Liste aus ${Object.keys(SECTORS).map((k) => `"${k}"`).join(', ')} – nur direkt betroffene Branchen (höchstens 3). - "sectorImpact": Objekt Branche → Zahl -1 bis 1 (Wirkung auf diese Branche, darf von "sentiment" abweichen). -- "topics": Objekt mit beliebig vielen der Schlüssel oil, rates, inflation, usd, gold, risk, tariffs, labor, growth, crypto, jeweils -1 bis 1. - Vorzeichen: + bedeutet "mehr davon": oil = Ölpreis steigt, rates = Zinsen steigen, inflation = Inflation steigt, usd = Dollar wird stärker, +- "topics": Objekt mit beliebig vielen der Schlüssel oil, gas, rates, inflation, usd, gold, risk, tariffs, labor, growth, crypto, jeweils -1 bis 1. + Vorzeichen: + bedeutet "mehr davon": oil = Ölpreis steigt, gas = Erdgaspreis steigt (auch: Gasspeicher leeren sich, Lieferungen stocken), rates = Zinsen steigen, inflation = Inflation steigt, usd = Dollar wird stärker, gold = Goldpreis steigt, risk = mehr Krisen-/Kriegsrisiko, tariffs = mehr Zölle/Handelsstreit, labor = Arbeitsmarkt besser, growth = Konjunktur besser, crypto = Kryptowährungen steigen. Nur Themen angeben, zu denen die Meldung wirklich etwas aussagt. - "strength": 0 bis 1 – wie stark und überraschend die Nachricht ist (Routinemeldung 0.2, Paukenschlag 1). diff --git a/server/src/population.js b/server/src/population.js index 0c819c0..40ac700 100644 --- a/server/src/population.js +++ b/server/src/population.js @@ -12,11 +12,11 @@ import { clamp, rnd, uid } from './util.js'; const pick = (a) => a[Math.floor(Math.random() * a.length)]; export const GROUPS = { - arbeit: { name: 'Beschäftigte', icon: '👷', share: 0.42, parties: { suw: 0.5, wvp: 0.3, bb: 0.2 }, sens: { unemp: -0.4, infl: -0.2, gdp: 0.1 }, desc: 'Angestellte und Arbeiter – ihnen geht es um sichere Jobs, Löhne und Preise.' }, - rente: { name: 'Rentnerinnen & Rentner', icon: '👵', share: 0.24, parties: { wvp: 0.45, bb: 0.3, suw: 0.25 }, sens: { unemp: -0.05, infl: -0.4, gdp: 0.05 }, desc: 'Feste Einkommen – Inflation und Rentenpolitik treffen sie direkt.' }, - unter: { name: 'Selbstständige & Unternehmen', icon: '💼', share: 0.10, parties: { lmp: 0.55, wvp: 0.45 }, sens: { unemp: -0.05, infl: -0.1, gdp: 0.35 }, desc: 'Steuern, Bürokratie und Konjunktur entscheiden über ihre Aufträge.' }, - jung: { name: 'Junge Leute & Studierende', icon: '🎓', share: 0.12, parties: { ga: 0.55, suw: 0.25, lmp: 0.2 }, sens: { unemp: -0.3, infl: -0.1, gdp: 0.1 }, desc: 'Berufseinstieg, Klima und Zukunftschancen.' }, - land: { name: 'Landbevölkerung', icon: '🚜', share: 0.12, parties: { bb: 0.5, wvp: 0.5 }, sens: { unemp: -0.15, infl: -0.3, gdp: 0.05 }, desc: 'Landwirtschaft, Pendeln und Energiepreise.' }, + arbeit: { name: 'Beschäftigte', icon: '👷', share: 0.42, parties: { suw: 0.5, wvp: 0.3, bb: 0.2 }, sens: { unemp: -0.4, infl: -0.2, gdp: 0.1, energy: -0.08 }, desc: 'Angestellte und Arbeiter – ihnen geht es um sichere Jobs, Löhne und Preise.' }, + rente: { name: 'Rentnerinnen & Rentner', icon: '👵', share: 0.24, parties: { wvp: 0.45, bb: 0.3, suw: 0.25 }, sens: { unemp: -0.05, infl: -0.4, gdp: 0.05, energy: -0.12 }, desc: 'Feste Einkommen – Inflation und Rentenpolitik treffen sie direkt.' }, + unter: { name: 'Selbstständige & Unternehmen', icon: '💼', share: 0.10, parties: { lmp: 0.55, wvp: 0.45 }, sens: { unemp: -0.05, infl: -0.1, gdp: 0.35, energy: -0.06 }, desc: 'Steuern, Bürokratie und Konjunktur entscheiden über ihre Aufträge.' }, + jung: { name: 'Junge Leute & Studierende', icon: '🎓', share: 0.12, parties: { ga: 0.55, suw: 0.25, lmp: 0.2 }, sens: { unemp: -0.3, infl: -0.1, gdp: 0.1, energy: -0.04 }, desc: 'Berufseinstieg, Klima und Zukunftschancen.' }, + land: { name: 'Landbevölkerung', icon: '🚜', share: 0.12, parties: { bb: 0.5, wvp: 0.5 }, sens: { unemp: -0.15, infl: -0.3, gdp: 0.05, energy: -0.15 }, desc: 'Landwirtschaft, Pendeln und Energiepreise.' }, }; const GROUP_IDS = Object.keys(GROUPS); @@ -41,6 +41,8 @@ const LAW_GROUPS = { pharmrd: { rente: 0.04, jung: 0.03 }, retire: { rente: -0.3, arbeit: -0.15, jung: 0.04, unter: 0.08 }, oilres: { land: 0.04, rente: 0.02 }, + gasbrake: { rente: 0.12, land: 0.12, arbeit: 0.08, jung: 0.03, unter: 0.04 }, + gasstore: { land: 0.02, rente: 0.02, unter: -0.03 }, export: { arbeit: 0.06, unter: 0.08, land: 0.02 }, wealth: { arbeit: 0.1, jung: 0.08, unter: -0.25, rente: -0.02 }, }; @@ -162,7 +164,12 @@ export class Population { const u = clamp((pub.unemployment - 5.8) / 3, -1, 1.5); const i = clamp((pub.inflation - 2) / 4, -0.5, 1.5); const y = clamp((pub.gdp - TREND_GDP) / 2, -1.5, 1); - return s.unemp * u + s.infl * i + s.gdp * y - (this.g.gov?.budget?.crisis ? 0.15 : 0); + return s.unemp * u + s.infl * i + s.gdp * y + this.#energy(k) - (this.g.gov?.budget?.crisis ? 0.15 : 0); + } + /** Heizkosten: teures Gas (über dem saisonüblichen Preis, nach Gaspreisbremse) drückt die Stimmung, billiges hebt sie leicht */ + #energy(k) { + const e = clamp((this.g.assets?.ext().gasCpi ?? 0) / 0.5, -0.5, 1.5); + return (GROUPS[k].sens.energy ?? 0) * e; } #lawPart(k) { return this.impulses.filter((x) => x.group === k).reduce((a, x) => a + x.amt * Math.pow(0.5, (this.g.day - x.day) / HALF_LIFE), 0); } /** Konsumklima −1 … +1 (gewichtete Stimmung) */ @@ -399,8 +406,9 @@ JSON: {"groups": {"arbeit": 0, "rente": 0, "unter": 0, "jung": 0, "land": 0}, "r const groups = GROUP_IDS.map((k) => { const G = GROUPS[k]; const reasons = []; - const econ = this.#econ(k); + const energy = this.#energy(k), econ = this.#econ(k) - energy; if (Math.abs(econ) >= 0.03) reasons.push({ label: 'Wirtschaftslage (Jobs, Preise, Wachstum)', amt: r2(econ) }); + if (Math.abs(energy) >= 0.02) reasons.push({ label: 'Heizkosten (Gaspreis)', amt: r2(energy) }); const byLabel = {}; for (const x of this.impulses.filter((y) => y.group === k)) byLabel[x.label] = (byLabel[x.label] ?? 0) + x.amt * Math.pow(0.5, (this.g.day - x.day) / HALF_LIFE); for (const [label, amt] of Object.entries(byLabel)) if (Math.abs(amt) >= 0.02) reasons.push({ label, amt: r2(amt) }); diff --git a/server/src/rivalmind.js b/server/src/rivalmind.js index 7230140..c24f0a6 100644 --- a/server/src/rivalmind.js +++ b/server/src/rivalmind.js @@ -12,7 +12,7 @@ import { SECTORS } from './world.js'; import { clamp } from './util.js'; const MIN = 60_000; -const ASSETS = ['OEL', 'GOLD', 'USD', 'WIB10', 'WIB2', 'WIBC']; +const ASSETS = ['OEL', 'GAS', 'GOLD', 'USD', 'WIB10', 'WIB2', 'WIBC']; const MAX_INFLIGHT = 2; const SYSTEM = `Du spielst eine Figur in WiBoSim, einem Börsen- und Politikspiel im fiktiven Land Wiborien (Währung Euro). Bleib immer in deiner Rolle, schreib auf Deutsch, kurz und lebendig, ohne Beleidigungen, ohne echte Personen, ohne Links. @@ -107,9 +107,9 @@ export class RivalMind { }).slice(0, 8).join(', ') || 'nur Bargeld'; const idx = g.index(); return `Leitindex ${Math.round(idx.value)} (${idx.change.toFixed(1)} % heute). -Konjunktur (veröffentlicht): Leitzins ${m.rate?.toFixed?.(2)} %, Inflation ${m.inflation?.toFixed?.(1)} % (Ziel ${m.targets.inflation}), Wachstum ${m.gdp?.toFixed?.(1)} %, Arbeitslosigkeit ${m.unemployment?.toFixed?.(1)} %${m.indicators ? `, Einkaufsmanagerindex ${m.indicators.pmi?.toFixed?.(1)}` : ''}${m.cb?.hint ? `, Zentralbank: ${m.cb.hint}` : ''}. +Konjunktur (veröffentlicht): Leitzins ${m.rate?.toFixed?.(2)} %, Inflation ${m.inflation?.toFixed?.(1)} % (Ziel ${m.targets.inflation}), Wachstum ${m.gdp?.toFixed?.(1)} %, Arbeitslosigkeit ${m.unemployment?.toFixed?.(1)} %${m.indicators ? `, Einkaufsmanagerindex ${m.indicators.pmi?.toFixed?.(1)}` : ''}${m.gas ? `, Gasspeicher ${Math.round(m.gas.storage * 100)} % (üblich ${Math.round(m.gas.norm * 100)} %, ${m.gas.month})` : ''}${m.cb?.hint ? `, Zentralbank: ${m.cb.hint}` : ''}. Branchen heute: ${sectors}. -Anlagen: ${assets} (OEL Rohöl, GOLD, USD Dollar, WIB2/WIB10 Staatsanleihen, WIBC WiboCoin – Krypto). +Anlagen: ${assets} (OEL Rohöl, GAS Erdgas, GOLD, USD Dollar, WIB2/WIB10 Staatsanleihen, WIBC WiboCoin – Krypto). Nachrichten (24 h): ${news} Gesetzgebung: @@ -135,7 +135,7 @@ Dein Depot: ${pos}.`; Schätze die Lage aus Sicht deines Charakters ein. Antworte als JSON: {"mood": Zahl −1…+1 (Gesamtmarkt), "risk": Zahl 0…1 (wie viel Risiko du jetzt nimmst), "sectors": {Branchenschlüssel: Zahl −1…+1, nur wo du eine klare Meinung hast; Schlüssel: ${Object.keys(SECTORS).join(', ')}}, - "assets": {"OEL"|"GOLD"|"USD"|"WIB10"|"WIB2"|"WIBC": Zahl −1…+1, nur bei klarer Meinung}, + "assets": {"OEL"|"GAS"|"GOLD"|"USD"|"WIB10"|"WIB2"|"WIBC": Zahl −1…+1, nur bei klarer Meinung}, "note": "dein Lagebild in einem Satz, höchstens 160 Zeichen, in deinem Ton"}`, { temperature: 0.4, maxTokens: 350 }); const v = validateView(out); if (!v) { if (out) { this.stats.failed++; this.stats.lastError = 'Lagebild unbrauchbar'; } return null; } diff --git a/server/src/rivals.js b/server/src/rivals.js index 67d42a5..91133db 100644 --- a/server/src/rivals.js +++ b/server/src/rivals.js @@ -71,7 +71,7 @@ export const CHARACTERS = { }, rita: { name: 'Rita Rohstoff', title: 'Die Makro-Strategin', style: 'macro', - desc: 'Denkt in Zinsen, Inflation und Rohstoffen: Anleihen bei sinkender Inflation, Gold bei Angst, Öl nach Nachrichtenlage.', + desc: 'Denkt in Zinsen, Inflation und Rohstoffen: Anleihen bei sinkender Inflation, Gold bei Angst, Öl und Gas nach Nachrichtenlage.', every: [90, 240], weight: 0.2, maxPos: 5, short: true, stop: 0.1, take: 0.15, politics: 0.4, chat: 0.35, pos: { markt: 0.1, staat: 0.3, oeko: 0.5 }, battle: { accept: 0.5, challenge: 0.6, mode: 'arena' }, say: { @@ -412,6 +412,7 @@ export class Rivals { const t = n.analysis?.topics ?? {}; const moves = []; if (Math.abs(t.oil ?? 0) >= 0.3) moves.push(['OEL', Math.sign(t.oil)]); + if (Math.abs(t.gas ?? 0) >= 0.3) moves.push(['GAS', Math.sign(t.gas)]); if ((t.risk ?? 0) >= 0.3 || (t.gold ?? 0) >= 0.3) moves.push(['GOLD', 1]); if (Math.abs(t.rates ?? 0) >= 0.3) moves.push(['WIB10', -Math.sign(t.rates)]); if (Math.abs(t.usd ?? 0) >= 0.3) moves.push(['USD', Math.sign(t.usd)]); @@ -451,6 +452,7 @@ export class Rivals { WIB10: infl < INFL_TARGET + 0.4 && gdp < TREND_GDP + 0.3 ? 0.3 : infl > INFL_TARGET + 1.2 ? -0.12 : 0.1, GOLD: 0.06 + (m.sentiment < -0.25 ? 0.08 : 0) + clamp(topic('risk') * 0.04, 0, 0.08), OEL: clamp(topic('oil') * 0.06, -0.15, 0.15), + GAS: clamp(topic('gas') * 0.05, -0.12, 0.12), USD: clamp(topic('usd') * 0.05 + ((m.rate ?? 2.5) < 3 ? 0.04 : -0.04), -0.1, 0.1), }; const sym = pick(Object.keys(targets)); diff --git a/server/src/scenarios.js b/server/src/scenarios.js index fb07d6b..cfa8116 100644 --- a/server/src/scenarios.js +++ b/server/src/scenarios.js @@ -22,11 +22,11 @@ export const SCENARIOS = { ], }, energiekrise: { - title: 'Energiekrise', desc: 'Lieferausfälle treiben den Ölpreis, die Inflation steigt, energieintensive Branchen leiden. Die Politik ringt um Entlastungen.', - macro: { inflation: 3.9, gdp: 0.3 }, oil: 0.35, sectorMood: { energy: 0.4, industry: -0.4, auto: -0.3 }, + title: 'Energiekrise', desc: 'Lieferausfälle treiben Öl- und Gaspreis, die Inflation steigt, energieintensive Branchen leiden. Die Politik ringt um Entlastungen.', + macro: { inflation: 3.9, gdp: 0.3 }, oil: 0.35, gas: 0.2, gasGap: -0.06, sectorMood: { energy: 0.4, industry: -0.4, auto: -0.3 }, script: [ - { at: 0.3, oil: 0.2, news: 'Pipeline-Störung: Ölpreis klettert auf ein Mehrjahreshoch' }, - { at: 0.7, oil: -0.3, news: 'Neue Förderquellen erschlossen – Energiepreise entspannen sich', sentiment: 0.3 }, + { at: 0.3, oil: 0.2, gas: 0.12, news: 'Pipeline-Störung: Öl- und Gaspreis klettern auf ein Mehrjahreshoch' }, + { at: 0.7, oil: -0.3, gas: -0.25, gasGap: 0.04, news: 'Neue Förderquellen und Flüssiggas-Terminals erschlossen – Energiepreise entspannen sich', sentiment: 0.3 }, ], }, rezession: { @@ -84,6 +84,8 @@ function step(g, ev) { for (const [sec, v] of Object.entries(ev.mis ?? {})) for (const s of g.stocks.values()) if (s.sector === sec) s.mis = (s.mis ?? 0) + v; for (const [sec, v] of Object.entries(ev.shock ?? {})) for (const s of g.stocks.values()) if (s.sector === sec) { g.econ.shiftFair(s, 1 + v); g.econ.bumpVol(s, 2.5); } if (ev.oil) g.assets.oilShock(ev.oil, ev.news); + // Gas: eigene Meldung nur, wenn das Ereignis nicht schon als Ölschock gemeldet wurde + if (ev.gas) g.assets.gasShock(ev.gas, ev.news, ev.gasGap ?? 0, !ev.oil); if (ev.budget && g.gov) { const b = g.gov.budget; if (ev.budget.debt !== undefined) b.debt = ev.budget.debt; @@ -101,7 +103,7 @@ export function runScript(g) { if (done.includes(i) || prog < ev.at) return; done.push(i); step(g, ev); - if (ev.news && !ev.oil) g.addNews({ id: `scn-${Date.now()}-${i}`, title: ev.news, source: 'Wirtschaftsredaktion', real: false, sentiment: ev.sentiment ?? 0, sectors: ev.sectors ?? [], ts: Date.now() }, !ev.shock); + if (ev.news && !ev.oil && !ev.gas) g.addNews({ id: `scn-${Date.now()}-${i}`, title: ev.news, source: 'Wirtschaftsredaktion', real: false, sentiment: ev.sentiment ?? 0, sectors: ev.sectors ?? [], ts: Date.now() }, !ev.shock); g.metaDirty = true; }); } diff --git a/server/src/world.js b/server/src/world.js index 2f3bf9e..14424a2 100644 --- a/server/src/world.js +++ b/server/src/world.js @@ -5,16 +5,18 @@ import { gauss, clamp } from './util.js'; export const SECTORS = { // rateEps: Gewinnwirkung je Prozentpunkt Zins (Banken verdienen an Zinsmarge) · gdpSens: Konjunkturbeta // pe: typisches KGV · payout: Ausschüttungsquote · pricing/cost: Preissetzungsmacht bzw. Kostenanteil bei Inflation - // oil/fx: Gewinnelastizität ggü. Ölpreis bzw. Dollarkurs (Dollar teurer = Euro schwächer → Exporteure profitieren) + // oil/gas/fx: Gewinnelastizität ggü. Ölpreis, Gaspreis (Abweichung vom saisonüblichen Preis) bzw. Dollarkurs + // (Dollar teurer = Euro schwächer → Exporteure profitieren); einzelne Firmen setzen gasSens abweichend + // (Versorger mit Gaskraftwerken profitieren, energieintensive Stahlwerke leiden) // sov: Gewinnwirkung je Prozentpunkt Länderrisikoaufschlag (Banken halten viele Staatsanleihen – steigt der Aufschlag, verlieren sie) - tech: { name: 'Technologie', rateEps: 0, gdpSens: 1.4, pe: 28, payout: 0.15, pricing: 0.6, cost: 0.3, oil: 0, fx: 0.10 }, - energy: { name: 'Energie', rateEps: 0, gdpSens: 0.8, pe: 12, payout: 0.60, pricing: 1.0, cost: 0.5, oil: 0.45, fx: -0.05 }, - auto: { name: 'Automobil', rateEps: -0.02, gdpSens: 1.5, pe: 8, payout: 0.40, pricing: 0.4, cost: 0.8, oil: -0.15, fx: 0.25 }, - banks: { name: 'Banken', rateEps: 0.08, gdpSens: 1.1, pe: 10, payout: 0.50, pricing: 0.5, cost: 0.3, oil: 0, fx: 0.02, sov: -0.08 }, - pharma: { name: 'Pharma', rateEps: 0, gdpSens: 0.3, pe: 18, payout: 0.45, pricing: 0.7, cost: 0.4, oil: -0.03, fx: 0.15 }, - consumer: { name: 'Konsum', rateEps: -0.01, gdpSens: 0.9, pe: 16, payout: 0.50, pricing: 0.5, cost: 0.7, oil: -0.08, fx: -0.10 }, - industry: { name: 'Industrie', rateEps: -0.01, gdpSens: 1.3, pe: 14, payout: 0.45, pricing: 0.5, cost: 0.8, oil: -0.12, fx: 0.20 }, - defense: { name: 'Verteidigung', rateEps: 0, gdpSens: 0.2, pe: 22, payout: 0.35, pricing: 0.8, cost: 0.4, oil: 0, fx: 0.05 }, + tech: { name: 'Technologie', rateEps: 0, gdpSens: 1.4, pe: 28, payout: 0.15, pricing: 0.6, cost: 0.3, oil: 0, gas: 0, fx: 0.10 }, + energy: { name: 'Energie', rateEps: 0, gdpSens: 0.8, pe: 12, payout: 0.60, pricing: 1.0, cost: 0.5, oil: 0.45, gas: 0.12, fx: -0.05 }, + auto: { name: 'Automobil', rateEps: -0.02, gdpSens: 1.5, pe: 8, payout: 0.40, pricing: 0.4, cost: 0.8, oil: -0.15, gas: -0.02, fx: 0.25 }, + banks: { name: 'Banken', rateEps: 0.08, gdpSens: 1.1, pe: 10, payout: 0.50, pricing: 0.5, cost: 0.3, oil: 0, gas: 0, fx: 0.02, sov: -0.08 }, + pharma: { name: 'Pharma', rateEps: 0, gdpSens: 0.3, pe: 18, payout: 0.45, pricing: 0.7, cost: 0.4, oil: -0.03, gas: -0.01, fx: 0.15 }, + consumer: { name: 'Konsum', rateEps: -0.01, gdpSens: 0.9, pe: 16, payout: 0.50, pricing: 0.5, cost: 0.7, oil: -0.08, gas: -0.03, fx: -0.10 }, + industry: { name: 'Industrie', rateEps: -0.01, gdpSens: 1.3, pe: 14, payout: 0.45, pricing: 0.5, cost: 0.8, oil: -0.12, gas: -0.06, fx: 0.20 }, + defense: { name: 'Verteidigung', rateEps: 0, gdpSens: 0.2, pe: 22, payout: 0.35, pricing: 0.8, cost: 0.4, oil: 0, gas: 0, fx: 0.05 }, }; export const COMPANIES = [ @@ -23,7 +25,7 @@ export const COMPANIES = [ desc: 'Entwickelt KI-Beschleuniger und Rechenzentrumschips.', founded: 2004, hq: 'Dresden', employees: 18400 }, { symbol: 'QBIT', name: 'Quantbit Software SE', sector: 'tech', price: 61.2, shares: 3.1e8, vol: 0.45, growth: 0.25, payout: 0, desc: 'Cloud-Software für Logistik und Quantensimulation.', founded: 2011, hq: 'Berlin', employees: 6200 }, - { symbol: 'HLIO', name: 'Helion Energie AG', sector: 'energy', price: 38.9, shares: 9.0e8, vol: 0.30, growth: 0.03, + { symbol: 'HLIO', name: 'Helion Energie AG', sector: 'energy', price: 38.9, shares: 9.0e8, vol: 0.30, growth: 0.03, gasSens: 0.2, desc: 'Versorger mit Gas-, Wind- und Solarkraftwerken.', founded: 1952, hq: 'Essen', employees: 41000 }, { symbol: 'VOLT', name: 'Voltwerk Motoren AG', sector: 'auto', price: 87.3, shares: 5.5e8, vol: 0.33, growth: 0.04, desc: 'Autobauer im Umbau vom Verbrenner zum E-Antrieb.', founded: 1937, hq: 'Stuttgart', employees: 132000 }, @@ -33,18 +35,18 @@ export const COMPANIES = [ desc: 'Onkologie- und Impfstoffhersteller mit starker Pipeline.', founded: 1898, hq: 'Mannheim', employees: 29000 }, { symbol: 'KRMA', name: 'Kaufrausch Retail AG', sector: 'consumer', price: 19.4, shares: 7.0e8, vol: 0.29, growth: 0.03, desc: 'Warenhaus- und Onlinehandelskette.', founded: 1961, hq: 'Köln', employees: 38000 }, - { symbol: 'STHL', name: 'Stahlhafen Industrie', sector: 'industry', price: 45.1, shares: 6.3e8, vol: 0.27, growth: 0.02, + { symbol: 'STHL', name: 'Stahlhafen Industrie', sector: 'industry', price: 45.1, shares: 6.3e8, vol: 0.27, growth: 0.02, gasSens: -0.15, desc: 'Stahl- und Anlagenbau, Zulieferer für Auto und Energie.', founded: 1891, hq: 'Duisburg', employees: 47000 }, { symbol: 'AEGS', name: 'Aegis Defence Group', sector: 'defense', price: 203.8, shares: 1.2e8, vol: 0.31, growth: 0.12, desc: 'Radar-, Luftabwehr- und Fahrzeugsysteme.', founded: 1979, hq: 'München', employees: 14500 }, - { symbol: 'GRNH', name: 'Grünhain Wasserstoff', sector: 'energy', price: 9.85, shares: 4.0e8, vol: 0.55, growth: 0.40, payout: 0, + { symbol: 'GRNH', name: 'Grünhain Wasserstoff', sector: 'energy', price: 9.85, shares: 4.0e8, vol: 0.55, growth: 0.40, gasSens: 0.06, payout: 0, desc: 'Elektrolyseure und Wasserstoff-Infrastruktur, noch kaum profitabel.', founded: 2016, hq: 'Hamburg', employees: 1900 }, // ab Version 0.12: mehr Auswahl je Branche (nicht im WIBO-10) { symbol: 'PIXL', name: 'Pixelhain Games AG', sector: 'tech', price: 34.7, shares: 2.2e8, vol: 0.48, growth: 0.20, payout: 0.1, desc: 'Entwickler von Online-Spielen; abhängig von wenigen Hit-Titeln.', founded: 2009, hq: 'Leipzig', employees: 2300 }, { symbol: 'SNSR', name: 'Sensorik Nordwerk AG', sector: 'tech', price: 22.4, shares: 3.0e8, vol: 0.42, growth: 0.15, desc: 'Sensoren und Mikrochips für Autos, Maschinen und Medizintechnik.', founded: 1998, hq: 'Jena', employees: 5600 }, - { symbol: 'NRDW', name: 'Nordwind Offshore AG', sector: 'energy', price: 27.8, shares: 5.0e8, vol: 0.33, growth: 0.08, payout: 0.5, + { symbol: 'NRDW', name: 'Nordwind Offshore AG', sector: 'energy', price: 27.8, shares: 5.0e8, vol: 0.33, growth: 0.08, gasSens: 0.08, payout: 0.5, desc: 'Betreibt Windparks in Nord- und Ostsee; feste Einspeisevergütungen.', founded: 2003, hq: 'Bremerhaven', employees: 3800 }, { symbol: 'RADL', name: 'Radler Mobility SE', sector: 'auto', price: 15.6, shares: 2.6e8, vol: 0.52, growth: 0.22, payout: 0, desc: 'E-Bikes, Lastenräder und Sharing-Flotten – stark wachsend, noch mit Verlust.', founded: 2014, hq: 'Freiburg', employees: 2100 }, @@ -58,11 +60,11 @@ export const COMPANIES = [ desc: 'Biotech mit zwei Wirkstoffen in der Zulassungsstudie – alles hängt an den Daten.', founded: 2010, hq: 'Martinsried', employees: 480 }, { symbol: 'VITA', name: 'Vitalis Generika AG', sector: 'pharma', price: 56.2, shares: 2.0e8, vol: 0.19, growth: 0.03, payout: 0.55, desc: 'Nachahmerpräparate und rezeptfreie Arzneien; stabil, wenig Fantasie.', founded: 1949, hq: 'Ulm', employees: 12500 }, - { symbol: 'BRAU', name: 'Kronquell Brauerei AG', sector: 'consumer', price: 73.5, shares: 1.1e8, vol: 0.18, growth: 0.02, payout: 0.7, + { symbol: 'BRAU', name: 'Kronquell Brauerei AG', sector: 'consumer', price: 73.5, shares: 1.1e8, vol: 0.18, growth: 0.02, gasSens: -0.05, payout: 0.7, desc: 'Bier, Limonaden und Mineralwasser; treue Kundschaft, hohe Ausschüttung.', founded: 1812, hq: 'Bamberg', employees: 6900 }, - { symbol: 'BAUW', name: 'Baukraft Werke AG', sector: 'industry', price: 31.9, shares: 4.1e8, vol: 0.32, growth: 0.04, + { symbol: 'BAUW', name: 'Baukraft Werke AG', sector: 'industry', price: 31.9, shares: 4.1e8, vol: 0.32, growth: 0.04, gasSens: -0.04, desc: 'Hoch- und Tiefbau, Brücken und Schienen; profitiert von staatlichen Aufträgen.', founded: 1902, hq: 'Dortmund', employees: 39000 }, - { symbol: 'ROBO', name: 'Robotik Alpen AG', sector: 'industry', price: 96.4, shares: 1.3e8, vol: 0.36, growth: 0.14, payout: 0.25, + { symbol: 'ROBO', name: 'Robotik Alpen AG', sector: 'industry', price: 96.4, shares: 1.3e8, vol: 0.36, growth: 0.14, gasSens: -0.02, payout: 0.25, desc: 'Industrieroboter und Fabrikautomatisierung.', founded: 1986, hq: 'Augsburg', employees: 8800 }, { symbol: 'ORBT', name: 'Orbitum Raumfahrt AG', sector: 'defense', price: 64.0, shares: 1.4e8, vol: 0.40, growth: 0.16, payout: 0.1, desc: 'Satelliten, Trägerraketen und Bodenstationen für Staat und Wirtschaft.', founded: 2001, hq: 'Bremen', employees: 4200 }, @@ -102,11 +104,13 @@ export function stepMacro(m, dtYears, sentimentHalfLifeYears) { const realGap = (m.rate - (m.published?.inflation ?? m.inflation)) - 0.5; // Realzins vs. neutral const trend = m.regime === 'recession' ? -1.2 : 1.3; // Außenwirtschaft & Staat: Ölpreis und Dollarkurs (log. Abweichung vom Ausgangswert), Risikoaufschlag der Staatsanleihen + // Gas: nur die Abweichung vom saisonüblichen Preis (gasCpi: nach Gaspreisbremse) – Energiekomponente der Verbraucherpreise const ext = m.ext ?? { oil: 0, usd: 0, risk: 0 }; - const gdpEq = trend - realGap * 0.4 + m.sentiment * 0.6 + m.eqShift.gdp - ext.oil * 1.2 + ext.usd * 0.5 - ext.risk * 0.4; + const gas = ext.gasCpi ?? 0; + const gdpEq = trend - realGap * 0.4 + m.sentiment * 0.6 + m.eqShift.gdp - ext.oil * 1.2 - gas * 0.4 + ext.usd * 0.5 - ext.risk * 0.4; m.gdpEq = gdpEq; m.gdp += 1.5 * (gdpEq - m.gdp) * dtYears + 0.9 * sq * gauss(); - const inflEq = INFL_TARGET + 0.2 - realGap * 0.3 + (m.gdp - TREND_GDP) * 0.3 + m.eqShift.inflation + ext.oil * 2 + ext.usd * 1; + const inflEq = INFL_TARGET + 0.2 - realGap * 0.3 + (m.gdp - TREND_GDP) * 0.3 + m.eqShift.inflation + ext.oil * 2 + gas * 0.8 + ext.usd * 1; m.inflation += 1.0 * (inflEq - m.inflation) * dtYears + 0.5 * sq * gauss(); const uEq = 5.8 - (m.gdp - TREND_GDP) * 0.5 + m.eqShift.unemployment; m.unemployment += 0.8 * (uEq - m.unemployment) * dtYears + 0.2 * sq * gauss(); @@ -196,6 +200,10 @@ export const BILLS = [ { id: 'pharmrd', title: 'Forschungszulage für Pharma', axis: 'markt', cost: 0.15, legal: 0, effects: { pharma: 0.05 }, macro: {}, keywords: ['forschung', 'impfstoff', 'vaccine'] }, { id: 'retire', title: 'Rentenreform mit späterem Eintritt', axis: 'markt', cost: -0.4, legal: 0.15, effects: { consumer: -0.01, banks: 0.01 }, macro: { unemployment: -0.1, gdp: 0.05 }, keywords: ['rente', 'pension'] }, { id: 'oilres', title: 'Strategische Ölreserve aufstocken', axis: 'staat', cost: 0.2, legal: 0, effects: { energy: 0.02 }, macro: { inflation: 0.03 }, keywords: ['öl', 'oil', 'opec', 'erdöl'] }, + // Gas: Sonderwirkung in assets.js – die Bremse halbiert, was teures Gas bei Inflation und Bevölkerung anrichtet; + // die Speicherpflicht hebt den Füllstand vor dem Winter und schließt Lücken schneller + { id: 'gasbrake', title: 'Gaspreisbremse für Haushalte und Betriebe', axis: 'staat', cost: 0.5, legal: 0.05, effects: { consumer: 0.02, industry: 0.015, energy: -0.01 }, macro: { inflation: -0.1 }, keywords: ['gaspreis', 'gaspreisbremse', 'heizkosten', 'gasumlage', 'energiepreis'] }, + { id: 'gasstore', title: 'Gasspeicherpflicht: Mindestfüllstand vor dem Winter', axis: 'staat', cost: 0.1, legal: 0.05, effects: { energy: 0.01, industry: 0.005 }, macro: { inflation: 0.02 }, keywords: ['gasspeicher', 'speicherfüllstand', 'gasversorgung', 'flüssiggas', 'lng', 'erdgas'] }, { id: 'export', title: 'Exportkreditgarantien ausweiten', axis: 'markt', cost: 0.1, legal: 0, effects: { industry: 0.03, auto: 0.02, pharma: 0.01 }, macro: { gdp: 0.05 }, keywords: ['export', 'handel', 'trade'] }, { id: 'wealth', title: 'Vermögensabgabe für Großvermögen', axis: 'staat', cost: -0.5, legal: 0.4, effects: { banks: -0.02, consumer: 0.01 }, macro: { gdp: -0.05 }, keywords: ['vermögensteuer', 'vermögen', 'wealth tax'] }, ];