mirror of
https://github.com/db9979/wibosim.git
synced 2026-12-06 05:24:08 +01:00
- Sanierung (Schuldenschnitt) sagt Fusion, Abspaltung, Übernahme-/Pflichtangebote und offene Hauptversammlung ab, Abfindungsangebot eines Beherrschers entfällt, Bilanzhistorie je Aktie bereinigt - Rückzug von der Börse sagt angekündigte Fusion, Abspaltung und Split sofort ab (Kalender, Logo, Kürzel) - Abspaltung: Tagesbalken (Volumen bleibt), Intraday-Kerzen, Pflichtangebot, Sonderdividende der HV, Kursziele, Bilanzhistorie, Analysen und Mindestpreis-Faktor (splits.adjust) der Mutter bereinigt - Gelöschte Orders bei Abspaltung/Fusion/Zusammenlegung nehmen wartende Bracket-Beine mit (keine Waisen) - Battle „3 Aktien“: Fusion tauscht Ziel gegen Käufer, Abspaltung erlaubt die Tochter - Abgesagte Abspaltung/Fusion mit Meldung, Chronik und Hinweis; Historienlänge Speicher = Spielstand - Regressionstests in review-konzern.test.js Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018i4GUhQVoPUusUzxgxLWkK
416 lines
29 KiB
JavaScript
416 lines
29 KiB
JavaScript
// Abspaltung (Spin-off): Ein großer Konzern bringt eine Sparte als eigene Aktiengesellschaft an die Börse.
|
||
//
|
||
// Ablauf
|
||
// 1. Ankündigung (Zufall etwa alle cfg.spinoffEveryDays Handelstage oder Admin): Meldung, Kalendertermin, Hinweis an alle
|
||
// Aktionäre. Name, Kürzel und Logo (Logo-Pool, markpool.js) der Tochter werden schon reserviert. Stichtag
|
||
// cfg.spinoffNoticeDays Handelstage später.
|
||
// 2. Stichtag (Vorbörse, vor der Eröffnungsauktion): Je N alte Aktien gibt es 1 Aktie der Tochter ins Depot. Der Anteil
|
||
// der Sparte am Konzern (alpha) wandert mit: Gewinne, Umsatz, Bilanz (Schulden, Kasse, Eigenkapital) werden vom Mutter-
|
||
// konzern abgezogen und bilden die Zahlen der Tochter. Startkurs der Tochter = alpha × Kurs der Mutter × N, der
|
||
// Mutterkurs fällt um denselben Wert – Wert vorher = Wert Mutter + Wert Tochter (bis auf Rundung auf Cent).
|
||
// Die Tochter wird über denselben Weg wie ein Börsengang gelistet (ipo.listStock): Orderbuch, Kerzen, Fundamentaldaten.
|
||
//
|
||
// Wer bekommt was (alle Konten: Haupt-, Battle-, Clan-Fonds-Depots und Rivalen; Bots haben keine Depots)
|
||
// – Aktionäre: floor(Bestand ÷ N) Tochteraktien; der Rest (Bruchteil) wird zum Startkurs bar ausgeglichen.
|
||
// Steuer: Einbuchung steuerneutral – der Einstand wird nach dem Wertverhältnis aufgeteilt (Mutter × f, Tochter den Rest
|
||
// je Tochteraktie); nur der Barausgleich für den Bruchteil ist ein Verkauf (Gewinn/Verlust gegen den anteiligen Einstand).
|
||
// – Leerverkäufer der Mutter müssen die Tochter mitliefern (wie bei einer Sachdividende auf geliehene Aktien): Sie
|
||
// bekommen einen Leerverkauf über floor(|Bestand| ÷ N) Tochteraktien, den Bruchteil zahlen sie bar. Warum so und nicht
|
||
// bar ausgleichen? So bleibt ihre Position wirtschaftlich unverändert (sie sind weiter auf den ganzen alten Konzern
|
||
// short), niemand muss zu einem Preis eindecken, den er nicht gewählt hat, und es gibt keinen Gewinn durch die Maßnahme.
|
||
// – Ruhende Orders auf die Mutter werden gelöscht (wie am Ex-Tag einer Dividende, mit Nachricht); Stopps und andere
|
||
// bedingte Orders sowie Kursalarme werden mit dem Faktor f angepasst. Hebelprodukte: Basispreis × f, Bezugsverhältnis ÷ f.
|
||
// – Indizes: Die Tochter kommt mit dem Bezugsverhältnis in die Indizes der Mutter (WIBO-10: Basis verkettet), ETFs bekommen
|
||
// die Tochter in den Korb – kein Sprung im Indexstand oder NAV.
|
||
import { SECTORS } from './world.js';
|
||
import { updateAnalysts } from './fundamentals.js';
|
||
import { liqFor } from './ipo.js';
|
||
import { profileKeyOf } from './credit.js';
|
||
import { scaleFund, scaleFundInPlace, freshBsHist, bookIn, cashFraction, whereTxt, cancelBook, adjustConds, adjustAlerts, battleSymbols, eur, num } from './corpaction.js';
|
||
import { rnd, clamp, uid, r2, cleanText } from './util.js';
|
||
|
||
// Sparten je Branche: Wort für den Namen der Tochter („Novalith Cloud AG“) und Beschreibung
|
||
const UNITS = {
|
||
tech: [['Cloud', 'Rechenzentren und Software zur Miete'], ['Halbleiter', 'Chips und Sensoren für Industrie und Autos'], ['Netzwerke', 'Netzwerktechnik für Unternehmen'], ['Software', 'Unternehmenssoftware im Abonnement']],
|
||
energy: [['Netze', 'Strom- und Gasnetze mit regulierten Erträgen'], ['Erneuerbare', 'Wind- und Solarparks'], ['Speicher', 'Großbatterien und Pumpspeicher'], ['Wärme', 'Fernwärme für Städte und Gewerbe']],
|
||
auto: [['Antriebe', 'Elektromotoren und Getriebe'], ['Zulieferung', 'Teile und Module für Autohersteller'], ['Batterien', 'Batteriezellen und -module'], ['Mobilitätsdienste', 'Carsharing, Leasing und Ladedienste']],
|
||
banks: [['Vermögensverwaltung', 'Fonds und Depots für Privatkunden'], ['Zahlungsdienste', 'Kartenzahlung und Online-Bezahlen'], ['Versicherung', 'Lebens- und Sachversicherungen'], ['Immobilienfinanz', 'Baufinanzierung und Gewerbekredite']],
|
||
pharma: [['Generika', 'Nachahmerpräparate mit stabilen Erträgen'], ['Diagnostik', 'Labortests und Schnelltests'], ['Tiergesundheit', 'Arzneimittel für Haus- und Nutztiere'], ['Biotech', 'Forschung an neuen Wirkstoffen']],
|
||
consumer: [['Marken', 'Markenartikel für Haushalt und Pflege'], ['Handel', 'Filialen und Onlineshop'], ['Getränke', 'Getränkemarken und Abfüllung'], ['Versand', 'Versandhandel und Abodienste']],
|
||
industry: [['Automation', 'Steuerungen und Roboter'], ['Anlagenbau', 'Industrieanlagen und Service'], ['Antriebstechnik', 'Getriebe, Pumpen und Kompressoren'], ['Werkzeuge', 'Präzisionswerkzeuge und Messtechnik']],
|
||
defense: [['Raumfahrt', 'Satelliten und Trägersysteme'], ['Sensorik', 'Radar und Optronik'], ['Sicherheitssysteme', 'Schutz für Netze und Gebäude'], ['Marine', 'Schiffe und Werftdienste']],
|
||
realestate: [['Gewerbe', 'Büros und Gewerbeflächen'], ['Wohnen', 'Mietwohnungen in Ballungsräumen'], ['Projektentwicklung', 'Neubauprojekte zum Verkauf'], ['Logistikflächen', 'Hallen und Verteilzentren']],
|
||
utilities: [['Netze', 'Strom- und Wassernetze'], ['Wasser', 'Trinkwasser und Abwasser'], ['Wärme', 'Fernwärme und Contracting'], ['Erzeugung', 'Kraftwerke und Stromhandel']],
|
||
telecom: [['Funktürme', 'Funkmasten zur Vermietung an Netzbetreiber'], ['Glasfaser', 'Glasfaseranschlüsse für Haushalte'], ['Rechenzentren', 'Serverflächen und Anbindung'], ['Mobilfunk', 'Mobilfunkverträge für Privatkunden']],
|
||
logistics: [['Paket', 'Paketzustellung bis zur Haustür'], ['Kontraktlogistik', 'Lager und Versand für Händler'], ['Luftfracht', 'Fracht per Flugzeug'], ['Lagerflächen', 'Hallen und Umschlagplätze']],
|
||
media: [['Streaming', 'Filme und Serien im Abonnement'], ['Verlag', 'Zeitungen, Zeitschriften und Bücher'], ['Werbung', 'Werbevermarktung online und im Fernsehen'], ['Radio', 'Radiosender und Podcasts']],
|
||
materials: [['Spezialchemie', 'Zusätze für Lacke, Kunststoffe und Elektronik'], ['Kunststoffe', 'Granulate und Folien'], ['Baustoffe', 'Zement, Dämmstoffe und Mörtel'], ['Agrarchemie', 'Dünger und Pflanzenschutz']],
|
||
health: [['Labore', 'Labordiagnostik für Praxen und Kliniken'], ['Medizintechnik', 'Geräte und Implantate'], ['Reha', 'Reha-Kliniken'], ['Pflege', 'Pflegeheime und ambulante Dienste']],
|
||
};
|
||
// Bezugsverhältnisse: je N alte Aktien eine neue
|
||
const RATIOS = [1, 2, 3, 4, 5, 8, 10, 20];
|
||
// Historie: im Speicher und im Spielstand gleich lang (sonst ändert ein Neustart die Liste)
|
||
const HIST_MAX = 30;
|
||
|
||
const pick = (a) => a[Math.floor(Math.random() * a.length)];
|
||
|
||
export class Spinoff {
|
||
constructor(g, saved) {
|
||
this.g = g;
|
||
this.state = { pending: [], history: [], nextDay: null, ...(saved ?? {}) };
|
||
}
|
||
get cfg() { return this.g.cfg; }
|
||
snapshot() { return { ...this.state, history: this.state.history.slice(0, HIST_MAX) }; }
|
||
get pending() { return this.state.pending; }
|
||
|
||
/** Reservierte Kürzel und Namen angekündigter Töchter (für Börsengänge und den Logo-Pool) */
|
||
reservedSymbols() { return this.pending.map((x) => x.symbol); }
|
||
reservedNames() { return this.pending.map((x) => x.name); }
|
||
|
||
/** Ist die Aktie gerade in eine Kapitalmaßnahme eingebunden (Abspaltung, Fusion, Übernahme, Beherrschung)? */
|
||
busy(s) {
|
||
const g = this.g;
|
||
if (this.pending.some((x) => x.parent === s.symbol)) return 'Abspaltung angekündigt';
|
||
if (g.merger?.dealOf?.(s.symbol)) return 'Fusion angekündigt';
|
||
if (g.splits?.pendingOf?.(s.symbol)) return 'Aktiensplit angekündigt';
|
||
if (g.corp?.offers?.some((o) => o.target === s.symbol || o.bidder === s.symbol)) return 'Übernahmeangebot läuft';
|
||
if (s.control && g.day <= s.control.untilDay) return 'wird von einem anderen Konzern beherrscht';
|
||
return null;
|
||
}
|
||
|
||
/** Mögliche Mütter: große, liquide Aktien (Börsenwert mindestens im Mittelfeld), kein frischer Börsengang */
|
||
candidates() {
|
||
const g = this.g;
|
||
const list = [...g.stocks.values()].filter((s) => s.kind === 'stock' && !s.delisted && s.last > 0 && s.shares > 0);
|
||
const caps = list.map((s) => s.last * s.shares).sort((a, b) => a - b);
|
||
const med = caps[Math.floor(caps.length / 2)] ?? 0;
|
||
return list.filter((s) => s.last * s.shares >= med && s.last >= 3 && s.shares >= 2e7 && !this.busy(s)
|
||
&& !(s.ipo && g.day - (s.ipo.day ?? 0) < this.cfg.quarterDays));
|
||
}
|
||
|
||
/** Bezugsverhältnis so, dass die Tochter etwa 10–60 € kostet (Ziel ≈ 25 €) */
|
||
static ratioFor(price, alpha) {
|
||
let best = RATIOS[0], bd = Infinity;
|
||
for (const n of RATIOS) { const c = alpha * price * n; const d = Math.abs(Math.log(c / 25)); if (d < bd) { bd = d; best = n; } }
|
||
return best;
|
||
}
|
||
|
||
// ================================================================ Ankündigung
|
||
/**
|
||
* Abspaltung ankündigen. opts: {symbol: Mutter, alpha: Anteil der Sparte (0,08–0,45), ratio: N, name, unit, days, source}
|
||
* Wirft, wenn nicht möglich.
|
||
*/
|
||
announce(opts = {}) {
|
||
const g = this.g, cfg = this.cfg;
|
||
if (this.pending.length >= 2) throw new Error('Es laufen bereits zwei Abspaltungen');
|
||
if ((g.ipo?.listedCount?.() ?? 0) + this.pending.length + (g.ipo?.pending?.filter((x) => x.status === 'signup').length ?? 0) >= cfg.ipoMaxStocks) throw new Error(`Höchstzahl von ${cfg.ipoMaxStocks} Aktien erreicht`);
|
||
let parent;
|
||
if (opts.symbol) {
|
||
parent = g.stocks.get(String(opts.symbol));
|
||
if (!parent || parent.kind !== 'stock') throw new Error('Unbekannte Aktie');
|
||
if (parent.delisted) throw new Error(g.delist.error(parent));
|
||
const b = this.busy(parent);
|
||
if (b) throw new Error(`${parent.symbol}: ${b}`);
|
||
} else {
|
||
const c = this.candidates();
|
||
if (!c.length) throw new Error('Kein passender Konzern');
|
||
const w = c.map((s) => Math.sqrt(s.last * s.shares));
|
||
let r = Math.random() * w.reduce((a, x) => a + x, 0);
|
||
parent = c.find((_, i) => (r -= w[i]) <= 0) ?? c[0];
|
||
}
|
||
const alpha = clamp(Number(opts.alpha) || r2(rnd(0.12, 0.32)), 0.05, 0.5);
|
||
const ratio = RATIOS.includes(Number(opts.ratio)) ? Number(opts.ratio) : Spinoff.ratioFor(parent.last, alpha);
|
||
const units = UNITS[parent.sector] ?? UNITS.industry;
|
||
const [unit, unitDesc] = units.find((u) => u[0] === opts.unit) ?? pick(units);
|
||
const stem = parent.name.split(/\s+/)[0].replace(/[^\p{L}-]/gu, '') || parent.symbol;
|
||
let name = opts.name ? cleanText(opts.name, 40) : `${stem} ${unit} ${Math.random() < 0.7 ? 'AG' : 'SE'}`;
|
||
if (!name || name.length < 3) throw new Error('Ungültiger Name');
|
||
if (g.ipo.nameTaken(name)) {
|
||
if (opts.name) throw new Error('Name ist bereits vergeben');
|
||
name = g.ipo.nameFor(parent.sector);
|
||
}
|
||
const symbol = g.ipo.symbolFor(name);
|
||
const days = Math.max(1, Math.round(Number(opts.days) || cfg.spinoffNoticeDays || 3));
|
||
const x = {
|
||
id: uid(4), parent: parent.symbol, parentName: parent.name, symbol, name, sector: parent.sector, unit,
|
||
desc: `${unitDesc}. Hervorgegangen aus der ${unit}-Sparte der ${parent.name}.`,
|
||
alpha, ratio, announcedDay: g.day, recordDay: g.day + days, source: opts.source ?? 'auto', ts: Date.now(),
|
||
employees: Math.round((parent.employees ?? 5000) * alpha / 10) * 10 || 500,
|
||
};
|
||
this.pending.push(x);
|
||
g.marks?.assign(symbol, parent.sector); // Logo schon zur Ankündigung reservieren
|
||
g.metaDirty = true;
|
||
// Aufspaltungen setzen oft Wert frei (klarere Struktur) – kleine positive Reaktion
|
||
g.econ.shiftFair(parent, 1 + rnd(0.005, 0.025));
|
||
g.econ.bumpVol(parent, 1.4);
|
||
const est = alpha * parent.last * ratio;
|
||
const title = `${parent.name} spaltet ${unit}-Sparte ab: ${name} (${symbol}) kommt am Handelstag ${x.recordDay} an die Börse – je ${ratio} ${parent.symbol}-Aktie${ratio === 1 ? '' : 'n'} gibt es 1 neue Aktie (Anteil am Konzern etwa ${Math.round(alpha * 100)} %)`;
|
||
g.addNews({ id: `spin-${x.id}`, title, source: 'Unternehmensmeldung', real: false, sentiment: 0.15, sectors: [parent.sector], symbol: parent.symbol, affected: [parent.symbol], ts: Date.now() }, false);
|
||
g.log('corporate', title, { symbol: parent.symbol });
|
||
g.corp?.note?.(parent, title);
|
||
g.chronicle?.add?.(parent.symbol, { kind: 'spinoff', title: `Abspaltung angekündigt: ${name}`, text: title, day: g.day, data: { child: symbol, ratio, alpha, recordDay: x.recordDay } });
|
||
for (const acc of g.allAccounts()) {
|
||
const q = acc.positions[parent.symbol]?.qty ?? 0;
|
||
if (!q) continue;
|
||
const owner = g.ownerOf(acc), pl = g.players.get(owner);
|
||
if (!pl || pl.rival) continue;
|
||
g.notify(owner, { kind: 'corporate', title: `Abspaltung bei ${parent.symbol}`, text: `${parent.name} bringt ${name} an die Börse. Stichtag Handelstag ${x.recordDay}: Für deine ${Math.abs(q)} Aktien${whereTxt(acc)} ${q > 0 ? 'bekommst' : 'lieferst'} du ${Math.floor(Math.abs(q) / ratio)} ${symbol}-Aktien (heute etwa ${eur(est)} je Stück)${q < 0 ? ' – als Leerverkäufer musst du die Tochter mitliefern' : ''}. Der Kurs von ${parent.symbol} fällt am Stichtag um den Wert der Tochter.`, action: { symbol: parent.symbol } });
|
||
}
|
||
g.broadcast?.({ type: 'corpAction', kind: 'spinoff', symbol: parent.symbol });
|
||
return x;
|
||
}
|
||
|
||
// ================================================================ Takt
|
||
/** Vorbörse: fällige Abspaltungen ausführen, ggf. neue ankündigen */
|
||
newDay() {
|
||
const g = this.g, cfg = this.cfg;
|
||
for (const x of [...this.pending]) {
|
||
if (g.day < x.recordDay) continue;
|
||
const parent = g.stocks.get(x.parent);
|
||
if (!parent || parent.delisted) { this.#drop(x, parent ? 'Der Konzern wurde von der Börse genommen' : 'Konzern unbekannt'); continue; }
|
||
try { this.execute(x); } catch (e) { console.warn('[abspaltung]', e.message); this.#drop(x, 'technischer Fehler'); }
|
||
}
|
||
if (!cfg.spinoffEnabled || !(cfg.spinoffEveryDays > 0)) return;
|
||
this.state.nextDay ??= g.day + Math.round(cfg.spinoffEveryDays * rnd(0.5, 1.5));
|
||
if (g.day >= this.state.nextDay) {
|
||
this.state.nextDay = g.day + Math.max(2, Math.round(cfg.spinoffEveryDays * rnd(0.6, 1.4)));
|
||
try { this.announce({ source: 'auto' }); } catch { /* kein passender Konzern o. ä. */ }
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Angekündigte Abspaltung absagen (Mutter eingestellt, Insolvenz mit Schuldenschnitt, technischer Fehler): Kürzel, Name
|
||
* und Logo werden frei; Meldung, Chronik und Hinweis an die Aktionäre der Mutter.
|
||
*/
|
||
#drop(x, why) {
|
||
const g = this.g;
|
||
this.state.pending = this.pending.filter((y) => y !== x);
|
||
g.marks?.release?.(x.symbol, { immediate: true });
|
||
this.state.history.unshift({ id: x.id, parent: x.parent, symbol: x.symbol, name: x.name, day: g.day, status: 'cancelled', why });
|
||
if (this.state.history.length > HIST_MAX) this.state.history.length = HIST_MAX;
|
||
g.metaDirty = true;
|
||
const parent = g.stocks.get(x.parent);
|
||
if (!parent) return;
|
||
const title = `Abspaltung von ${x.name} abgesagt: ${why}`;
|
||
g.addNews({ id: `spin-c-${x.id}`, title, source: 'Unternehmensmeldung', real: false, sentiment: -0.1, sectors: [parent.sector], symbol: parent.symbol, affected: [parent.symbol], ts: Date.now() }, false);
|
||
g.log('corporate', title, { symbol: parent.symbol });
|
||
g.corp?.note?.(parent, title);
|
||
g.chronicle?.add?.(parent.symbol, { kind: 'spinoff', title: `Abspaltung abgesagt: ${x.name}`, text: title, day: g.day, data: { child: x.symbol } });
|
||
const told = new Set();
|
||
for (const acc of g.allAccounts()) {
|
||
if (!(acc.positions[parent.symbol]?.qty ?? 0)) continue;
|
||
const owner = g.ownerOf(acc), pl = g.players.get(owner);
|
||
if (!pl || pl.rival || told.has(owner)) continue;
|
||
told.add(owner);
|
||
g.notify(owner, { kind: 'corporate', title: `Abspaltung bei ${parent.symbol} abgesagt`, text: `${title}. Es werden keine ${x.symbol}-Aktien eingebucht.`, action: { symbol: parent.symbol } });
|
||
}
|
||
g.broadcast?.({ type: 'corpAction', kind: 'spinoff', symbol: parent.symbol, cancelled: true });
|
||
}
|
||
|
||
/** Alle angekündigten Abspaltungen einer Mutter absagen (Insolvenz, Rückzug von der Börse). Liefert die Anzahl. */
|
||
abort(sym, why) {
|
||
const xs = this.pending.filter((x) => x.parent === sym);
|
||
for (const x of xs) this.#drop(x, why);
|
||
return xs.length;
|
||
}
|
||
|
||
/**
|
||
* Stichtag: Tochter listen, Bestände einbuchen, Kurs, Zahlen, Orders, Hebelprodukte und Indizes der Mutter anpassen.
|
||
* Liefert eine Zusammenfassung (für Tests und Admin).
|
||
*/
|
||
execute(x) {
|
||
const g = this.g;
|
||
const parent = g.stocks.get(x.parent);
|
||
const N = x.ratio;
|
||
g.causes?.set(`Abspaltung ${x.name}`);
|
||
const P = parent.last;
|
||
// Startkurs der Tochter und angepasster Mutterkurs (auf Cent; die Summe bleibt beim alten Wert)
|
||
const C = Math.max(0.05, r2(x.alpha * P * N));
|
||
const P1 = Math.max(0.01, r2(P - C / N));
|
||
const f = P1 / P; // Kursfaktor der Mutter
|
||
const alpha = 1 - f; // tatsächlicher Anteil der Tochter am Wert
|
||
const childShares = Math.max(1, Math.floor(parent.shares / N));
|
||
const w10Before = g.indices?.w10Sum?.() ?? 0;
|
||
|
||
// ---- Orders der Mutter: ruhende löschen (wie am Ex-Tag), bedingte und Kursalarme anpassen
|
||
const why = `Abspaltung von ${x.name}`;
|
||
cancelBook(g, parent, `Orders ${parent.symbol} gelöscht`, `${why}: Am Stichtag werden ruhende Orders auf ${parent.symbol} gelöscht, weil der Kurs um den Wert der Tochter sinkt (Faktor ${num(f, 4)}).`);
|
||
adjustConds(g, parent, f, `Stopps ${parent.symbol} angepasst`, `${why}: Auslöse- und Limitkurse deiner bedingten Orders auf ${parent.symbol} wurden mit dem Faktor ${num(f, 4)} angepasst.`);
|
||
adjustAlerts(g, parent.symbol, f, `${why}: Deine Kursalarme auf ${parent.symbol} wurden mit dem Faktor ${num(f, 4)} angepasst.`);
|
||
|
||
// ---- Unternehmenszahlen: Anteil alpha wandert zur Tochter (je Tochteraktie skaliert)
|
||
const perChild = (alpha * parent.shares) / childShares;
|
||
const childFund = scaleFund({ ...parent.fund, analysts: null }, perChild, alpha);
|
||
Object.assign(childFund, { pendingDividend: 0, exDivDay: null, warningIssued: false, policy: structuredClone(parent.fund.policy ?? []) });
|
||
g.econ.revalue(() => scaleFundInPlace(parent.fund, f, f));
|
||
// Kurs der Mutter: Sprung um den Wert der Tochter (fairer Kurs folgt über revalue)
|
||
for (const k of ['last', 'prevClose', 'close', 'open', 'high', 'low', 'refAuction']) if (Number.isFinite(parent[k])) parent[k] = Math.max(0.01, r2(parent[k] * f));
|
||
parent.fair = Math.max(0.01, parent.fair);
|
||
if (parent.mmState) parent.mmState.mid = 0;
|
||
parent.indicative = null;
|
||
adjustHistory(g, parent, f);
|
||
|
||
// ---- Tochter listen (wie ein Börsenneuling)
|
||
const def = {
|
||
symbol: x.symbol, name: x.name, sector: x.sector, price: C, shares: childShares, vol: r2(clamp(parent.vol * rnd(1.0, 1.25), 0.15, 0.9)),
|
||
growth: parent.fund.g ?? parent.growth, liq: liqFor(C * childShares), ...(parent.payout !== undefined ? { payout: parent.payout } : {}),
|
||
profile: profileKeyOf(parent), ...(parent.gasSens ? { gasSens: parent.gasSens } : {}),
|
||
desc: x.desc, founded: new Date().getFullYear() - Math.floor(rnd(0, 3)), hq: parent.hq ?? 'Wiborien', employees: x.employees,
|
||
ipo: { day: g.day, price: C, spinoff: { from: parent.symbol, ratio: N } },
|
||
};
|
||
const child = g.ipo.listStock(def, { price: C, fund: childFund, fair: C, hDay: 2 });
|
||
child.fund.nextEarningsDay = parent.fund.nextEarningsDay;
|
||
freshBsHist(child, g.day);
|
||
updateAnalysts(child, child.fv);
|
||
|
||
// ---- Bestände aller Konten
|
||
let accounts = 0, delivered = 0;
|
||
const owners = new Map(); // Eigentümer → Zusammenfassung für Nachrichten und Erfolge
|
||
for (const acc of g.allAccounts()) {
|
||
const pos = acc.positions[parent.symbol];
|
||
const q = pos?.qty ?? 0;
|
||
if (!q) continue;
|
||
const a0 = pos.avgCost;
|
||
pos.avgCost = a0 * f; // Einstand nach Wertverhältnis aufteilen
|
||
const childCost = a0 * (1 - f) * N; // je Tochteraktie
|
||
const sign = Math.sign(q);
|
||
const whole = Math.floor(Math.abs(q) / N);
|
||
const frac = Math.abs(q) / N - whole;
|
||
const owner = g.ownerOf(acc);
|
||
const ts = g.clock.now();
|
||
let realized = 0;
|
||
if (whole) {
|
||
realized += bookIn(acc, child.symbol, sign * whole, childCost);
|
||
g.recordFill({ ts, owner, account: acc.id, symbol: child.symbol, side: sign > 0 ? 'buy' : 'sell', qty: whole, price: r2(childCost), fee: 0, realized: 0, kind: 'spinoff' });
|
||
}
|
||
const fr = cashFraction(acc, sign * frac, C, childCost);
|
||
if (fr.cash) g.recordFill({ ts, owner, account: acc.id, symbol: child.symbol, side: sign > 0 ? 'sell' : 'buy', qty: 0, price: C, fee: 0, realized: fr.realized, cash: fr.cash, kind: 'spinoffCash' });
|
||
realized += fr.realized;
|
||
g.markDirty(acc);
|
||
accounts++; delivered += sign * whole;
|
||
const o = owners.get(owner) ?? { items: [], qty: 0 };
|
||
o.items.push({ acc, q, whole: sign * whole, cash: fr.cash, realized });
|
||
o.qty += sign * whole;
|
||
owners.set(owner, o);
|
||
}
|
||
for (const [owner, o] of owners) {
|
||
const pl = g.players.get(owner);
|
||
if (pl && !pl.rival) {
|
||
const lines = o.items.map(({ acc, q, whole, cash }) => (q > 0
|
||
? `${Math.abs(whole)} ${child.symbol}-Aktien${whereTxt(acc)} eingebucht (für ${q} ${parent.symbol})${cash ? `, Bruchteil ${eur(cash)} gutgeschrieben` : ''}`
|
||
: `Leerverkauf über ${Math.abs(whole)} ${child.symbol}-Aktien${whereTxt(acc)} eingebucht (du lieferst die Tochter für ${Math.abs(q)} leerverkaufte ${parent.symbol})${cash ? `, Bruchteil ${eur(-cash)} belastet` : ''}`)).join('; ');
|
||
g.notify(owner, { kind: 'corporate', title: `Abspaltung: ${child.name} im Depot`, text: `${lines}. Startkurs ${eur(C)}, ${parent.symbol} jetzt ${eur(parent.last)}. Dein Einstand wurde nach dem Wertverhältnis aufgeteilt (${Math.round(f * 100)} % ${parent.symbol}, ${Math.round((1 - f) * 100)} % ${child.symbol}) – keine Steuer auf die Einbuchung.`, action: { symbol: child.symbol } });
|
||
}
|
||
if (o.qty > 0) g.achievements?.onEvent?.(owner, 'spinoffReceived', { symbol: child.symbol, from: parent.symbol, qty: o.qty });
|
||
}
|
||
|
||
// ---- ETFs, Indizes, Hebelprodukte
|
||
try { g.etfs?.onSpinoff?.(parent.symbol, child.symbol, 1 / N); } catch (e) { console.warn('[abspaltung/etf]', e.message); }
|
||
try { g.indices?.onSpinoff?.(parent.symbol, child.symbol, 1 / N, w10Before); } catch (e) { console.warn('[abspaltung/index]', e.message); }
|
||
let derivs = 0;
|
||
try { derivs = g.derivs?.adjustUnderlying?.(parent.symbol, f, why) ?? 0; } catch (e) { console.warn('[abspaltung/hebel]', e.message); }
|
||
// Battle „3 Aktien“: Wer die Mutter handeln darf, darf auch die eingebuchte Tochter verkaufen
|
||
battleSymbols(g, (list) => (list.includes(parent.symbol) && !list.includes(child.symbol) ? [...list, child.symbol] : null));
|
||
|
||
// ---- Abschluss
|
||
this.state.pending = this.pending.filter((y) => y !== x);
|
||
const rec = { id: x.id, parent: parent.symbol, parentName: parent.name, symbol: child.symbol, name: child.name, sector: child.sector, ratio: N, alpha: r2(alpha * 1000) / 1000, price: C, parentBefore: P, parentAfter: parent.last, factor: f, day: g.day, ts: g.clock.now(), accounts, delivered, derivs, status: 'done' };
|
||
this.state.history.unshift(rec);
|
||
if (this.state.history.length > HIST_MAX) this.state.history.length = HIST_MAX;
|
||
const title = `Abspaltung vollzogen: ${child.name} (${child.symbol}) startet heute an der Börse – Bezugsverhältnis ${N} : 1, Startkurs ${eur(C)}. ${parent.name} jetzt ${eur(parent.last)} (vorher ${eur(P)}).`;
|
||
g.addNews({ id: `spin-d-${x.id}`, title, source: 'Börse Wiborien', real: false, sentiment: 0.05, sectors: [child.sector], symbol: child.symbol, affected: [child.symbol, parent.symbol], ts: Date.now() }, false);
|
||
g.log('corporate', title, { symbol: parent.symbol });
|
||
g.corp?.note?.(parent, title);
|
||
g.corp?.note?.(child, `Abgespalten von ${parent.name} (${N} : 1), Startkurs ${eur(C)}`);
|
||
g.chronicle?.add?.(parent.symbol, { kind: 'spinoff', title: `Abspaltung vollzogen: ${child.name}`, text: title, day: g.day, data: { child: child.symbol, ratio: N, price: C, factor: f } });
|
||
g.chronicle?.add?.(child.symbol, { kind: 'spinoff', title: `Börsenstart als Abspaltung von ${parent.name}`, text: title, day: g.day, data: { parent: parent.symbol, ratio: N, price: C } });
|
||
g.metaDirty = true;
|
||
g.broadcast?.({ type: 'corpAction', kind: 'spinoff', symbol: parent.symbol, child: child.symbol, done: true });
|
||
return rec;
|
||
}
|
||
|
||
// ================================================================ Ansichten
|
||
/** Für die Unternehmensansicht (Mutter: laufende Abspaltung; Tochter: Herkunft in den ersten Wochen) */
|
||
view(symbol, pid = null) {
|
||
const g = this.g;
|
||
const x = this.pending.find((y) => y.parent === symbol);
|
||
if (x) {
|
||
const s = g.stocks.get(symbol);
|
||
const acc = pid ? g.players.get(pid) : null;
|
||
const q = acc?.positions?.[symbol]?.qty ?? 0;
|
||
const est = r2(x.alpha * s.last * x.ratio);
|
||
return {
|
||
role: 'parent', id: x.id, child: x.symbol, childName: x.name, unit: x.unit, sector: x.sector, sectorName: SECTORS[x.sector]?.name ?? x.sector,
|
||
ratio: x.ratio, alpha: x.alpha, recordDay: x.recordDay, daysLeft: x.recordDay - g.day, announcedDay: x.announcedDay,
|
||
estPrice: est, parentAfter: r2(s.last - est / x.ratio), mark: g.marks?.of?.(x.symbol) ?? null,
|
||
mine: q ? { qty: q, child: Math.sign(q) * Math.floor(Math.abs(q) / x.ratio), cash: r2(Math.sign(q) * (Math.abs(q) / x.ratio - Math.floor(Math.abs(q) / x.ratio)) * est) } : null,
|
||
};
|
||
}
|
||
const h = this.state.history.find((y) => y.status === 'done' && (y.symbol === symbol || y.parent === symbol) && g.day - y.day <= Math.max(5, this.cfg.quarterDays));
|
||
if (h) return { role: h.symbol === symbol ? 'child' : 'done', ...h, parentName: h.parentName ?? g.stocks.get(h.parent)?.name ?? h.parent, childName: h.name };
|
||
return null;
|
||
}
|
||
|
||
/** Kalendereinträge */
|
||
calendarItems(at) {
|
||
const g = this.g;
|
||
return this.pending.map((x) => ({ ts: at(x.recordDay - g.day), dayIn: x.recordDay - g.day, kind: 'corporate', symbol: x.parent, title: `Abspaltung: ${x.name} (${x.symbol}) aus ${x.parentName}`, detail: `Stichtag · je ${x.ratio} ${x.parent}-Aktien 1 neue Aktie` }));
|
||
}
|
||
|
||
/** Marktliste: Abzeichen */
|
||
badge(symbol) { return this.pending.some((x) => x.parent === symbol) ? 'spinoff' : null; }
|
||
|
||
adminView() { return { pending: this.pending, history: this.state.history.slice(0, 10) }; }
|
||
}
|
||
|
||
/**
|
||
* Kursbezogene Daten der Mutter nach der Abspaltung bereinigen (Faktor f = Kurs danach ÷ Kurs davor), damit Charts,
|
||
* Mindestpreise und Kennzahlen nicht springen – wie beim Aktiensplit, nur ohne Änderung der Stückzahlen:
|
||
* Tagesbalken in SQLite (rückwirkend, Volumen bleibt), Intraday-Kerzen und Umsätze, Pflichtangebote (Preis und
|
||
* Mindestpreis-Grundlagen), Sonderdividende einer offenen Hauptversammlung, Kursziele der Analysten, Buchwert/Gewinn
|
||
* je Aktie der Bilanzhistorie, offene Analysen der Spieler und Einstiegskurse der Rivalen.
|
||
*/
|
||
function adjustHistory(g, s, f) {
|
||
const P = (x) => (Number.isFinite(x) ? x * f : x);
|
||
(g.pendingBarScales ??= []).push({ symbol: s.symbol, ts: g.clock.now(), f: 1 / f, vf: 1 });
|
||
s.candles = (s.candles ?? []).map((c) => ({ ...c, o: P(c.o), h: P(c.h), l: P(c.l), c: P(c.c) }));
|
||
s.tape = (s.tape ?? []).map((t) => ({ ...t, price: P(t.price) }));
|
||
if (s.lastAuction) s.lastAuction = { ...s.lastAuction, price: P(s.lastAuction.price) };
|
||
for (const o of g.corp?.offers ?? []) {
|
||
if (o.target !== s.symbol) continue;
|
||
o.price = r2(P(o.price));
|
||
if (o.basis) o.basis = { ...o.basis, maxPaid: P(o.basis.maxPaid ?? 0), vwap: P(o.basis.vwap ?? 0) };
|
||
}
|
||
for (const m of g.agm?.state?.meetings ?? []) {
|
||
if (m.symbol !== s.symbol || m.status !== 'open') continue;
|
||
for (const it of m.items ?? []) {
|
||
if (it.key !== 'dividend' || !Number.isFinite(it.amount)) continue;
|
||
it.amount = Math.max(0.01, r2(P(it.amount)));
|
||
it.desc = `Einmalige Ausschüttung von ${eur(it.amount)} je Aktie aus den Rücklagen (zahlbar bei Annahme sofort; nach der Abspaltung angepasst).`;
|
||
}
|
||
}
|
||
const fd = s.fund;
|
||
// Kursziele der Analysten auf den kleineren Konzern beziehen (neu bewertet wird wie üblich zur nächsten Vorbörse)
|
||
if (fd?.analysts) {
|
||
const a = fd.analysts;
|
||
fd.analysts = { ...a, target: r2(P(a.target)), low: r2(P(a.low)), high: r2(P(a.high)), ratings: (a.ratings ?? []).map((x) => ({ ...x, target: r2(P(x.target)) })) };
|
||
}
|
||
if (fd?.bsHist) {
|
||
fd.bsHist = fd.bsHist.map((h) => {
|
||
const x = { ...h };
|
||
for (const k of ['bvps', 'eps']) if (Number.isFinite(x[k])) x[k] = Math.round(x[k] * f * 1e4) / 1e4;
|
||
for (const k of ['eq', 'debt', 'nd', 'cash', 'ebitda', 'revenue']) if (Number.isFinite(x[k])) x[k] = Math.round(x[k] * f);
|
||
return x;
|
||
});
|
||
}
|
||
for (const a of g.analyses?.state?.list ?? []) {
|
||
if (a.symbol !== s.symbol || a.status !== 'open') continue;
|
||
a.start = P(a.start);
|
||
if (a.target !== null && a.target !== undefined) a.target = r2(P(a.target));
|
||
}
|
||
for (const p of g.players.values()) {
|
||
const e = p.rival?.mem?.entry?.[s.symbol];
|
||
if (e && Number.isFinite(e.px)) { e.px = P(e.px); g.markDirty(p); }
|
||
}
|
||
}
|