#!/usr/bin/env python3
"""Original synthetic worksheet for alphascope.app/blog/pinball-loss.

Undoubled pinball loss. Standard library only; no network calls.
Run next to pinball-loss-events.csv, or pass a CSV path as the first argument.
The numeric forecast is a quantile VALUE, not a binary event probability.
"""

import csv
from fractions import Fraction
from pathlib import Path
import sys


def number(value):
    """Use decimal strings, not binary floats, for exact input arithmetic."""
    if isinstance(value, bool):
        raise ValueError("A boolean is not a numeric observation")
    try:
        return Fraction(str(value))
    except (ValueError, ZeroDivisionError) as exc:
        raise ValueError("Inputs must be finite numbers") from exc


def losses(actuals, predictions, tau):
    actuals, predictions = list(actuals), list(predictions)
    level = number(tau)
    if not 0 < level < 1:
        raise ValueError("tau must lie strictly between 0 and 1")
    if not actuals or len(actuals) != len(predictions):
        raise ValueError("Use matched, nonempty observations and predictions")
    result = []
    for observed, predicted in zip(actuals, predictions):
        residual = number(observed) - number(predicted)
        result.append(level * residual if residual >= 0 else (level - 1) * residual)
    return result


def mean_loss(actuals, predictions, tau):
    values = losses(actuals, predictions, tau)
    return sum(values, Fraction(0)) / len(values)


def main():
    path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).with_name("pinball-loss-events.csv")
    with path.open(newline="", encoding="utf-8") as source:
        rows = list(csv.DictReader(source))
    y = [row["actual"] for row in rows]
    q = [row["predicted_quantile"] for row in rows]
    print("Undoubled pinball loss; equal weights; fictional numeric outcomes")
    for level in ("0.10", "0.50", "0.90"):
        score = mean_loss(y, q, level)
        print(f"tau={level}: mean={float(score):.6f}; exact={score}")
    print("Per-case tau=0.90 losses:", [str(v) for v in losses(y, q, "0.90")])
    # This comparison uses the article's fixed synthetic actuals, not an input CSV.
    fixture = [12, 18, 27, 35]
    for level in ("0.50", "0.90"):
        print(f"Constant forecasts, tau={level}: A=24 -> {float(mean_loss(fixture, [24]*4, level)):.2f}; B=32 -> {float(mean_loss(fixture, [32]*4, level)):.2f}")
    print("For actuals [10,20], all median forecasts from 10 to 20 minimize mean loss at 2.50.")


if __name__ == "__main__":
    main()
