File size: 27,125 Bytes
2c09224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
#!/usr/bin/env python3
"""Amazon leveraged product analysis from a private EUR investor view.

The script intentionally separates two things:
- real observable data where public historical quotes are available
- transparent model columns where retail derivative histories are not reliably
  available from a stable public endpoint
"""

from __future__ import annotations

import argparse
import json
import math
import time
import urllib.parse
import urllib.request
from dataclasses import dataclass
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from typing import Iterable

import numpy as np
import pandas as pd


START_DATE = "2026-01-01"
END_DATE = "2026-04-14"


@dataclass(frozen=True)
class Trade:
    execution_time: str
    isin: str
    name: str
    quantity: float
    price_eur: float
    venue: str

    @property
    def amount_eur(self) -> float:
        return self.quantity * self.price_eur


ETP_TRADES = [
    Trade(
        execution_time="2026-02-03 15:55:09",
        isin="IE00BK5BZQ82",
        name="Leverage Shares 3x Amazon ETP",
        quantity=1000.0,
        price_eur=8.2385,
        venue="EIX",
    ),
    Trade(
        execution_time="2026-02-03 16:05:06",
        isin="IE00BK5BZQ82",
        name="Leverage Shares 3x Amazon ETP",
        quantity=2000.0,
        price_eur=7.9890,
        venue="EIX",
    ),
    Trade(
        execution_time="2026-02-06 07:42:37",
        isin="IE00BK5BZQ82",
        name="Leverage Shares 3x Amazon ETP",
        quantity=4000.0,
        price_eur=4.5000,
        venue="gettex",
    ),
]


PRODUCTS = {
    "amzn_usd": {
        "symbol": "AMZN",
        "kind": "basiswert_usd",
        "source": "Yahoo Finance chart API",
    },
    "amzn_eur": {
        "symbol": "AMZ.DE",
        "kind": "basiswert_eur",
        "source": "Yahoo Finance chart API",
    },
    "eurusd": {
        "symbol": "EURUSD=X",
        "kind": "fx",
        "source": "Yahoo Finance chart API",
    },
    "etp_real": {
        "symbol": "3AN.DE",
        "isin": "IE00BK5BZQ82",
        "kind": "real_quote",
        "source": "Yahoo Finance chart API",
        "annual_product_cost": 0.0475,
    },
    "turbo_model": {
        "wkn": "UG523U",
        "isin": "DE000UG523U8",
        "kind": "model_only",
        "issuer": "UniCredit Bank GmbH / HVB",
        "name": "HVB TuBull O.EndAmazon172,9414",
        "basis_price_usd": 172.9414,
        "note": "Model uses constant financing level from product name; real issuer financing adjustments and spreads are not included.",
    },
    "factor_model": {
        "wkn": "MC2W9J",
        "isin": "DE000MC2W9J9",
        "kind": "model_only",
        "issuer": "Morgan Stanley",
        "factor": 3.0,
        "note": "Selected real 3x long Amazon factor product, but historical public quotes are not fetched; model uses 3x daily AMZN EUR path.",
    },
    "option_model": {
        "wkn": "HT0Q26",
        "isin": "DE000HT0Q262",
        "kind": "model_only",
        "issuer": "HSBC Trinkaus & Burkhardt GmbH",
        "type": "call",
        "strike_usd": 245.0,
        "ratio": 0.1,
        "expiry": "2026-12-18",
        "implied_volatility": 0.3676,
        "risk_free_rate": 0.03,
        "note": "Black-Scholes proxy with constant IV from 2026-04-13 finanzen.net snapshot; real warrant prices can diverge materially.",
    },
}


def yahoo_chart(symbol: str, start: str, end: str) -> pd.DataFrame:
    """Fetch daily close prices from Yahoo's chart endpoint."""
    start_dt = datetime.fromisoformat(start).replace(tzinfo=timezone.utc)
    end_dt = datetime.fromisoformat(end).replace(tzinfo=timezone.utc) + timedelta(days=1)
    params = urllib.parse.urlencode(
        {
            "period1": int(start_dt.timestamp()),
            "period2": int(end_dt.timestamp()),
            "interval": "1d",
            "events": "history",
        }
    )
    url = f"https://query2.finance.yahoo.com/v8/finance/chart/{urllib.parse.quote(symbol)}?{params}"
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
    with urllib.request.urlopen(req, timeout=30) as response:
        payload = json.loads(response.read().decode("utf-8"))

    result = payload.get("chart", {}).get("result")
    if not result:
        error = payload.get("chart", {}).get("error")
        raise RuntimeError(f"Yahoo returned no result for {symbol}: {error}")

    data = result[0]
    timestamps = data.get("timestamp") or []
    quote = data.get("indicators", {}).get("quote", [{}])[0]
    closes = quote.get("close") or []
    volumes = quote.get("volume") or []

    rows = []
    for ts, close, volume in zip(timestamps, closes, volumes):
        if close is None:
            continue
        rows.append(
            {
                "date": datetime.fromtimestamp(ts, tz=timezone.utc).date(),
                "close": float(close),
                "volume": np.nan if volume is None else float(volume),
            }
        )

    if not rows:
        raise RuntimeError(f"Yahoo returned no close prices for {symbol}")

    return pd.DataFrame(rows).drop_duplicates("date").sort_values("date")


def norm_cdf(x: float) -> float:
    return 0.5 * (1.0 + math.erf(x / math.sqrt(2.0)))


def norm_pdf(x: float) -> float:
    return math.exp(-0.5 * x * x) / math.sqrt(2.0 * math.pi)


def black_scholes_call(
    spot: float,
    strike: float,
    years: float,
    volatility: float,
    risk_free_rate: float,
) -> dict[str, float]:
    if years <= 0 or volatility <= 0 or spot <= 0 or strike <= 0:
        intrinsic = max(spot - strike, 0.0)
        return {
            "price": intrinsic,
            "delta": 1.0 if spot > strike else 0.0,
            "theta_per_day": 0.0,
            "vega": 0.0,
        }

    sigma_sqrt_t = volatility * math.sqrt(years)
    d1 = (math.log(spot / strike) + (risk_free_rate + 0.5 * volatility**2) * years) / sigma_sqrt_t
    d2 = d1 - sigma_sqrt_t
    price = spot * norm_cdf(d1) - strike * math.exp(-risk_free_rate * years) * norm_cdf(d2)
    delta = norm_cdf(d1)
    theta_annual = (
        -(spot * norm_pdf(d1) * volatility) / (2.0 * math.sqrt(years))
        - risk_free_rate * strike * math.exp(-risk_free_rate * years) * norm_cdf(d2)
    )
    vega = spot * norm_pdf(d1) * math.sqrt(years) / 100.0
    return {
        "price": price,
        "delta": delta,
        "theta_per_day": theta_annual / 365.0,
        "vega": vega,
    }


def max_drawdown(series: pd.Series) -> float:
    clean = series.dropna()
    if clean.empty:
        return np.nan
    peak = clean.cummax()
    drawdown = clean / peak - 1.0
    return float(drawdown.min())


def first_valid_value(series: pd.Series) -> float:
    clean = series.dropna()
    if clean.empty:
        return np.nan
    return float(clean.iloc[0])


def fair_value(series: pd.Series, start_value: float = 1000.0) -> pd.Series:
    base = first_valid_value(series)
    if not np.isfinite(base) or base == 0:
        return pd.Series(np.nan, index=series.index)
    return start_value * series / base


def model_factor_path(returns: pd.Series, leverage: float, start_value: float = 1000.0) -> pd.Series:
    out = pd.Series(index=returns.index, dtype=float)
    value = start_value
    first_seen = False
    for idx, ret in returns.items():
        if pd.isna(ret):
            if not first_seen:
                out.loc[idx] = value
                first_seen = True
            else:
                out.loc[idx] = np.nan
            continue
        if not first_seen:
            out.loc[idx] = value
            first_seen = True
            continue
        value *= max(1.0 + leverage * float(ret), 0.0)
        out.loc[idx] = value
    return out.ffill()


def build_daily(start: str, end: str) -> pd.DataFrame:
    raw = {}
    for key in ("amzn_usd", "amzn_eur", "eurusd", "etp_real"):
        symbol = PRODUCTS[key]["symbol"]
        raw[key] = yahoo_chart(symbol, start, end).rename(columns={"close": key})
        time.sleep(0.2)

    # EUR investor view: keep the German Amazon trading calendar. FX can have
    # extra rows that would otherwise create dates without a basis-value move.
    all_dates = sorted(set(raw["amzn_eur"]["date"]))
    daily = pd.DataFrame({"date": all_dates})
    for key, frame in raw.items():
        daily = daily.merge(frame[["date", key]], on="date", how="left")

    daily["eurusd"] = daily["eurusd"].ffill().bfill()
    daily["amzn_eur_from_usd"] = daily["amzn_usd"] / daily["eurusd"]
    daily["amzn_eur_used"] = daily["amzn_eur"].combine_first(daily["amzn_eur_from_usd"])
    daily["amzn_usd_used"] = daily["amzn_usd"].combine_first(daily["amzn_eur_used"] * daily["eurusd"])
    daily["amzn_daily_return"] = daily["amzn_eur_used"].pct_change()
    daily["amzn_usd_daily_return"] = daily["amzn_usd"].pct_change()

    daily["etp_real_daily_return"] = daily["etp_real"].pct_change()
    daily["etp_model_3x"] = np.nan
    first_etp = first_valid_value(daily["etp_real"])
    if np.isfinite(first_etp):
        model = model_factor_path(daily["amzn_daily_return"], 3.0, first_etp)
        daily["etp_model_3x"] = model
        daily["etp_model_3x_daily_return"] = daily["etp_model_3x"].pct_change()
        daily["etp_drag_tracking"] = daily["etp_real"] / daily["etp_model_3x"] - 1.0

    turbo_basis = PRODUCTS["turbo_model"]["basis_price_usd"]
    daily["turbo_intrinsic_usd_per_unit"] = (daily["amzn_usd_used"] - turbo_basis).clip(lower=0.0)
    daily["turbo_intrinsic_eur_per_unit"] = daily["turbo_intrinsic_usd_per_unit"] / daily["eurusd"]
    daily["turbo_knocked_out_model"] = daily["amzn_usd_used"] <= turbo_basis
    daily["turbo_leverage_model"] = daily["amzn_usd_used"] / (daily["amzn_usd_used"] - turbo_basis)
    daily.loc[daily["turbo_intrinsic_usd_per_unit"] <= 0, "turbo_leverage_model"] = np.nan
    daily["turbo_ko_distance_pct"] = daily["amzn_usd_used"] / turbo_basis - 1.0
    daily["fair_1000_turbo_model"] = fair_value(daily["turbo_intrinsic_eur_per_unit"])

    daily["factor_model_3x"] = model_factor_path(daily["amzn_daily_return"], 3.0, 1000.0)

    option = PRODUCTS["option_model"]
    expiry = date.fromisoformat(option["expiry"])
    option_rows = []
    for _, row in daily.iterrows():
        trade_date = row["date"]
        years = max((expiry - trade_date).days / 365.0, 0.0)
        bs = black_scholes_call(
            spot=float(row["amzn_usd_used"]),
            strike=option["strike_usd"],
            years=years,
            volatility=option["implied_volatility"],
            risk_free_rate=option["risk_free_rate"],
        )
        price_eur = option["ratio"] * bs["price"] / row["eurusd"]
        theta_eur_day = option["ratio"] * bs["theta_per_day"] / row["eurusd"]
        intrinsic_eur = option["ratio"] * max(float(row["amzn_usd_used"]) - option["strike_usd"], 0.0) / row["eurusd"]
        option_rows.append(
            {
                "option_model_price": price_eur,
                "option_delta": bs["delta"],
                "option_omega": (bs["delta"] * float(row["amzn_usd_used"]) / bs["price"]) if bs["price"] > 0 else np.nan,
                "option_theta_per_day": theta_eur_day,
                "option_vega_per_vol_point_eur": option["ratio"] * bs["vega"] / row["eurusd"],
                "option_intrinsic_eur": intrinsic_eur,
                "option_time_value_eur": price_eur - intrinsic_eur,
            }
        )
    daily = pd.concat([daily, pd.DataFrame(option_rows)], axis=1)
    daily["fair_1000_option_model"] = fair_value(daily["option_model_price"])

    daily["fair_1000_amzn_eur"] = fair_value(daily["amzn_eur_used"])
    daily["fair_1000_etp_real"] = fair_value(daily["etp_real"])
    daily["fair_1000_etp_model_3x"] = fair_value(daily["etp_model_3x"])

    total_quantity = sum(trade.quantity for trade in ETP_TRADES)
    total_cost = sum(trade.amount_eur for trade in ETP_TRADES)
    avg_entry = total_cost / total_quantity
    daily["portfolio_etp_quantity"] = total_quantity
    daily["portfolio_etp_cost_basis_eur"] = total_cost
    daily["portfolio_etp_avg_entry_eur"] = avg_entry
    daily["portfolio_etp_value_eur"] = daily["etp_real"] * total_quantity
    daily["portfolio_etp_pnl_eur"] = daily["portfolio_etp_value_eur"] - total_cost
    daily["portfolio_etp_pnl_pct"] = daily["portfolio_etp_value_eur"] / total_cost - 1.0
    daily["portfolio_etp_break_even_gap_pct"] = daily["etp_real"] / avg_entry - 1.0

    preferred = [
        "date",
        "amzn_eur_used",
        "amzn_eur",
        "amzn_usd",
        "amzn_usd_used",
        "eurusd",
        "amzn_daily_return",
        "etp_real",
        "etp_real_daily_return",
        "etp_model_3x",
        "etp_model_3x_daily_return",
        "etp_drag_tracking",
        "turbo_intrinsic_eur_per_unit",
        "turbo_leverage_model",
        "turbo_ko_distance_pct",
        "turbo_knocked_out_model",
        "factor_model_3x",
        "option_model_price",
        "option_delta",
        "option_omega",
        "option_theta_per_day",
        "option_vega_per_vol_point_eur",
        "option_intrinsic_eur",
        "option_time_value_eur",
        "fair_1000_amzn_eur",
        "fair_1000_etp_real",
        "fair_1000_etp_model_3x",
        "fair_1000_turbo_model",
        "fair_1000_option_model",
        "portfolio_etp_value_eur",
        "portfolio_etp_pnl_eur",
        "portfolio_etp_pnl_pct",
        "portfolio_etp_break_even_gap_pct",
    ]
    return daily[[col for col in preferred if col in daily.columns]]


def build_summary(daily: pd.DataFrame) -> pd.DataFrame:
    metrics = []
    series_map = {
        "Amazon EUR": daily["fair_1000_amzn_eur"],
        "ETP real IE00BK5BZQ82": daily["fair_1000_etp_real"],
        "ETP modeled 3x": daily["fair_1000_etp_model_3x"],
        "Turbo model UG523U": daily["fair_1000_turbo_model"],
        "Factor model MC2W9J": daily["factor_model_3x"],
        "Option model HT0Q26": daily["fair_1000_option_model"],
    }
    for name, series in series_map.items():
        clean = series.dropna()
        if clean.empty:
            continue
        metrics.append(
            {
                "instrument": name,
                "start_value": float(clean.iloc[0]),
                "end_value": float(clean.iloc[-1]),
                "performance_pct": float(clean.iloc[-1] / clean.iloc[0] - 1.0),
                "max_drawdown_pct": max_drawdown(clean),
                "daily_volatility_pct": float(clean.pct_change().std(skipna=True)),
                "observations": int(clean.shape[0]),
            }
        )

    total_quantity = sum(trade.quantity for trade in ETP_TRADES)
    total_cost = sum(trade.amount_eur for trade in ETP_TRADES)
    avg_entry = total_cost / total_quantity
    last = daily.dropna(subset=["etp_real"]).iloc[-1]
    metrics.append(
        {
            "instrument": "Depot ETP position",
            "start_value": total_cost,
            "end_value": float(last["portfolio_etp_value_eur"]),
            "performance_pct": float(last["portfolio_etp_pnl_pct"]),
            "max_drawdown_pct": max_drawdown(daily["portfolio_etp_value_eur"]),
            "daily_volatility_pct": float(daily["portfolio_etp_value_eur"].pct_change().std(skipna=True)),
            "observations": int(daily["portfolio_etp_value_eur"].dropna().shape[0]),
            "quantity": total_quantity,
            "avg_entry_eur": avg_entry,
            "break_even_gap_pct": float(last["portfolio_etp_break_even_gap_pct"]),
        }
    )
    return pd.DataFrame(metrics)


def write_trade_summary(output_dir: Path) -> None:
    trades = pd.DataFrame(
        [
            {
                "execution_time": trade.execution_time,
                "isin": trade.isin,
                "name": trade.name,
                "quantity": trade.quantity,
                "price_eur": trade.price_eur,
                "amount_eur": trade.amount_eur,
                "venue": trade.venue,
            }
            for trade in ETP_TRADES
        ]
    )
    trades.to_csv(output_dir / "amazon_etp_trades.csv", index=False)


def write_readme(output_dir: Path, start: str, end: str) -> None:
    total_quantity = sum(trade.quantity for trade in ETP_TRADES)
    total_cost = sum(trade.amount_eur for trade in ETP_TRADES)
    avg_entry = total_cost / total_quantity
    text = f"""# Amazon Derivatives Analysis Outputs

Generated for {start} to {end}.

## Source hierarchy

1. Broker PDFs are the source of truth for executed ETP trades.
2. Official issuer documents are the source of truth for product mechanics.
3. Exchange/broker bid-ask quotes are the source of truth for tradable prices.
4. This model is a learning, risk, and plausibility model.

## ETP position

- ISIN: IE00BK5BZQ82
- Quantity: {total_quantity:,.0f}
- Cost basis: {total_cost:,.2f} EUR
- Weighted average entry: {avg_entry:.4f} EUR
- Running product cost from PDFs: 4.75% p.a.

## Model limitations

- `3AN.DE`, `AMZ.DE`, `AMZN`, and `EURUSD=X` are fetched from Yahoo Finance.
- UG523U is modeled from a constant USD financing level of 172.9414; issuer financing adjustments, spreads, and intraday knock-out handling are not included.
- MC2W9J is represented by a transparent 3x daily factor model because a stable public historical quote endpoint was not found.
- HT0Q26 is represented by a Black-Scholes proxy with constant IV 36.76%, strike 245 USD, ratio 0.1, and expiry 2026-12-18.
"""
    (output_dir / "README.md").write_text(text, encoding="utf-8")


def write_interpretation(output_dir: Path, daily: pd.DataFrame, summary: pd.DataFrame) -> None:
    by_name = summary.set_index("instrument")
    depot = by_name.loc["Depot ETP position"]
    amazon = by_name.loc["Amazon EUR"]
    etp_real = by_name.loc["ETP real IE00BK5BZQ82"]
    etp_model = by_name.loc["ETP modeled 3x"]
    turbo = by_name.loc["Turbo model UG523U"]
    factor = by_name.loc["Factor model MC2W9J"]
    option = by_name.loc["Option model HT0Q26"]

    end = daily.dropna(subset=["etp_real"]).iloc[-1]
    weighted_days = (
        sum(
            (end["date"] - date.fromisoformat(trade.execution_time[:10])).days * trade.amount_eur
            for trade in ETP_TRADES
        )
        / sum(trade.amount_eur for trade in ETP_TRADES)
    )
    etp_running_cost_pct = PRODUCTS["etp_real"]["annual_product_cost"] * weighted_days / 365.0
    etp_running_cost_eur = float(depot["start_value"] * etp_running_cost_pct)

    text = f"""# Was deine Wahl bis {end['date']} gezeigt hat

## Harte Depot-Wahrheit

- Dein gewichteter ETP-Einstieg: {depot['avg_entry_eur']:.4f} EUR.
- Letzter verwendeter ETP-Schlusskurs: {end['etp_real']:.4f} EUR.
- Depotwert ETP: {depot['end_value']:,.2f} EUR.
- P/L auf deine 7.000 Stk.: {end['portfolio_etp_pnl_eur']:,.2f} EUR ({depot['performance_pct']:.2%}).
- Geschätzte laufende Produktkosten über die gewichtete Haltedauer von {weighted_days:.1f} Tagen: ca. {etp_running_cost_pct:.2%} bzw. {etp_running_cost_eur:,.2f} EUR. Diese Kosten sind nicht als separate Brokerabbuchung sichtbar, sondern in der Produkt-/Indexentwicklung enthalten.

## 1.000-EUR-Vergleich seit Jahresanfang

| Instrument | Endwert | Performance | Max. Drawdown | Einordnung |
|---|---:|---:|---:|---|
| Amazon EUR | {amazon['end_value']:,.2f} EUR | {amazon['performance_pct']:.2%} | {amazon['max_drawdown_pct']:.2%} | Basiswert, kein Hebel |
| ETP real IE00BK5BZQ82 | {etp_real['end_value']:,.2f} EUR | {etp_real['performance_pct']:.2%} | {etp_real['max_drawdown_pct']:.2%} | echte Historie über 3AN.DE |
| ETP/Faktor 3x Modell | {etp_model['end_value']:,.2f} EUR | {etp_model['performance_pct']:.2%} | {etp_model['max_drawdown_pct']:.2%} | täglicher 3x-Pfad |
| Turbo UG523U Modell | {turbo['end_value']:,.2f} EUR | {turbo['performance_pct']:.2%} | {turbo['max_drawdown_pct']:.2%} | stärkste Performance, höchstes KO-Risiko |
| Optionsschein HT0Q26 Modell | {option['end_value']:,.2f} EUR | {option['performance_pct']:.2%} | {option['max_drawdown_pct']:.2%} | hoher Hebel, stark abhängig von IV/Zeitwert |

## Urteil zur Produktwahl

Deine Wahl war aus heutiger Sicht nicht schlecht, aber sie war nicht das maximal aggressive Produkt. Der Turbo hätte im Modell am meisten gebracht, hatte aber auch den tiefsten zwischenzeitlichen Absturz. Das ist genau der Trade-off: mehr Performance gegen viel höheres Knock-out- und Timing-Risiko.

Der echte ETP hat Amazon klar geschlagen und lag nahe am transparenten 3x-Tagesmodell. Am Ende lag er rund {end['etp_drag_tracking']:.2%} unter dem modellierten 3x-Pfad. Das ist die Zone, in der Tracking, Swap-/Indexkosten, FX, Handelsplatz und Spread sichtbar werden. Es ist kein Beweis für Fehlpreisung, aber ein guter Plausibilitätscheck.

Kosten-/Mechanik-Vergleich:

- ETP: laufende Kosten aus deinen PDFs 4,75% p.a.; kein Knock-out; täglicher Reset mit Variance Drain.
- Turbo: keine tägliche Reset-Mechanik; dafür Finanzierungslevel, Spread und Knock-out. Performance kann viel besser sein, aber ein falscher Gap kann die Position komplett beenden.
- Faktor: ähnlich wie ETP, täglicher Faktorpfad; privat gut modellierbar, echte Emittentenbedingungen bleiben entscheidend.
- Optionsschein: privat nur approximativ modellierbar, weil implizite Volatilität und Zeitwert den Preis stark bewegen.

## Praktische Lesart

Wenn dein Hauptproblem war, dass du das Produkt anfangs nicht vollständig verstanden hattest, dann war der ETP trotzdem die robustere gehebelte Wahl als ein Turbo: Du hattest keine KO-Schwelle, und der Nachkauf zu 4,50 EUR hat deinen Durchschnitt stark verbessert. Der Preis dafür war Variance Drain und laufende Produktkosten.

Wenn du ex post nur auf Rendite schaust, wäre der Turbo im Modell besser gewesen. Wenn du Risiko, KO-Gefahr und Produktverständnis mitbewertest, war der ETP die defensivere Hebelentscheidung.
"""
    (output_dir / "amazon_choice_interpretation.md").write_text(text, encoding="utf-8")


def write_cost_overview(output_dir: Path) -> None:
    total_cost = sum(trade.amount_eur for trade in ETP_TRADES)
    text = f"""# Kosten der verglichenen Produkte

## Wichtigste Einordnung

Bei diesen Produkten gibt es nicht nur "Gebühren" wie bei einem Fonds. Ein großer Teil der Kosten steckt in Geld/Brief-Spreads, Finanzierungskomponenten, Indexformeln, impliziter Volatilität und Emittentenpreisstellung. Deshalb ist der Broker-Ausführungskurs die Wahrheit für den Einstieg, und der handelbare Geldkurs die Wahrheit für den Ausstieg.

## Kostenmatrix

| Produkt | Explizit sichtbar | Im Preis versteckt | In unserem Modell |
|---|---:|---|---|
| ETP IE00BK5BZQ82 | laut deinen Scalable-PDFs: 0 EUR Einstieg, 0 EUR Ausstieg, 4,75% p.a. laufende Produktkosten | Swap-/Indexfinanzierung, Tracking, FX, Geld/Brief-Spread | echte Kursreihe `3AN.DE`, Kosten wirken im Kurs; zusätzlich grob ausgewiesen |
| Turbo UG523U | meist keine separate Orderproduktgebühr im Produkt selbst | Finanzierungskosten über steigendes Finanzierungslevel/Basispreis, Emittentenmarge, Spread, KO-Risiko | nur linearer Innerer-Wert-Proxy; Finanzierung/Spread nicht enthalten |
| Faktor MC2W9J | keine klassische TER; Morgan Stanley nennt u.a. Zinsanpassungssatz 2,00% p.a. | Geld/Brief-Spread, Management-/Finanzierungskomponente im virtuellen Index, Reset-Mechanik | 3x-Tagesmodell; reale Indexkosten/Spread nicht enthalten |
| Optionsschein HT0Q26 | keine laufende TER wie Fonds | Spread, Zeitwertverlust/Theta, implizite Volatilität, Emittentenmarge | Black-Scholes-Proxy mit konstantem IV; echter Emittentenpreis kann abweichen |

## ETP-Kosten aus deinen PDFs

Deine Kosteninformationen für IE00BK5BZQ82 zeigen:

- Einstiegskosten: 0,00 EUR
- Ausstiegskosten: 0,00 EUR
- Laufende Produktkosten: 4,75% p.a.
- bezogen auf deinen Einsatz von {total_cost:,.2f} EUR entspricht 4,75% p.a. rechnerisch {total_cost * 0.0475:,.2f} EUR pro Jahr, wenn der Positionswert konstant bliebe.

Für die gewichtete Haltedauer bis 2026-04-14 hat das Script grob ca. 0,89% bzw. rund 377,55 EUR laufende ETP-Kosten geschätzt. Das ist keine separate Abbuchung, sondern steckt in der Produktentwicklung.

Wichtig: Öffentliche ETF-Portale zeigen für IE00BK5BZQ82 teils eine TER von 0,75% p.a. Diese Zahl ist nicht identisch mit deiner ex-ante Broker-Kosteninformation von 4,75% p.a. Für deine konkrete Kaufentscheidung/Ex-ante-Kostensicht zählt die Broker-Kosteninformation; für Produktbasisdaten sollte man zusätzlich KID/Prospekt prüfen.

## Warum Turbo/Faktor/Optionsschein schwerer sind

Turbo:

- Die Kosten laufen primär über das Finanzierungslevel. Bei Open-End-Turbos wird der Basispreis/Finanzierungslevel typischerweise angepasst.
- Du siehst die Kosten nicht als Abbuchung, sondern als schlechtere Produktentwicklung gegenüber einem idealen linearen Modell.
- Zusätzlich kostet der Spread beim Kauf/Verkauf sofort Performance.

Faktor:

- Der Faktorpfad ist ähnlich wie beim ETP täglich neu gehebelt.
- Kosten stecken in der Index-/Faktorformel, im Zinsanpassungssatz und im Spread.
- Der wichtigste "Kostenblock" bei Seitwärtsbewegung ist aber nicht nur Gebühr, sondern Variance Drain durch täglichen Reset.

Optionsschein:

- Der größte laufende Effekt ist Theta/Zeitwertverlust.
- Zusätzlich kann implizite Volatilität den Schein teurer oder billiger machen, unabhängig davon, was Amazon macht.
- Spread ist sofortiger Einstiegsnachteil.

## Praktisches Fazit

Für Kostenwahrheit gilt:

1. Broker-Kosteninformation und Abrechnung für deinen Trade.
2. KID/Final Terms/Prospekt für Produktmechanik.
3. Aktueller Bid/Ask am Handelsplatz für real handelbare Kosten.
4. Modellrechnung nur als Plausibilitätscheck.

Wenn du die Produkte wirklich ex post kostenbereinigt vergleichen willst, brauchst du für Turbo/Faktor/Optionsschein historische Geld-/Briefkurse oder mindestens tägliche Schlusskurse vom Handelsplatz/Emittenten. Ohne diese Daten kann man nur approximieren.
"""
    (output_dir / "amazon_costs.md").write_text(text, encoding="utf-8")


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--start", default=START_DATE)
    parser.add_argument("--end", default=END_DATE)
    parser.add_argument("--output-dir", default="outputs")
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    output_dir = Path(args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    daily = build_daily(args.start, args.end)
    summary = build_summary(daily)

    daily.to_csv(output_dir / "amazon_derivate_daily.csv", index=False)
    summary.to_csv(output_dir / "amazon_derivate_summary.csv", index=False)
    write_trade_summary(output_dir)
    write_readme(output_dir, args.start, args.end)
    write_interpretation(output_dir, daily, summary)
    write_cost_overview(output_dir)

    print(f"Wrote {output_dir / 'amazon_derivate_daily.csv'}")
    print(f"Wrote {output_dir / 'amazon_derivate_summary.csv'}")
    print(f"Wrote {output_dir / 'amazon_etp_trades.csv'}")
    print(f"Wrote {output_dir / 'amazon_choice_interpretation.md'}")
    print(f"Wrote {output_dir / 'amazon_costs.md'}")


if __name__ == "__main__":
    main()