"""Offline, exact-rational educational examples. No prices, accounts or network access.
Loss is positive for a loss and negative for a gain. Alpha is confidence.
Weights must describe one distribution at one common horizon and sum to one.
"""
from fractions import Fraction as F


def tail_metrics(scenarios, alpha):
    scenarios = [(F(loss), F(weight)) for loss, weight in scenarios]
    alpha = F(alpha)
    if not scenarios or not 0 < alpha < 1:
        raise ValueError("Provide scenarios and a confidence strictly between 0 and 1")
    if any(w < 0 for _, w in scenarios) or sum(w for _, w in scenarios) != 1:
        raise ValueError("Nonnegative scenario weights must sum exactly to 1")
    cumulative = F(0)
    for loss, weight in sorted(scenarios):
        cumulative += weight
        if cumulative >= alpha:
            var = loss
            break
    tail = 1 - alpha
    remaining, weighted_loss = tail, F(0)
    for loss, weight in sorted(scenarios, reverse=True):
        used = min(weight, remaining)
        weighted_loss += loss * used
        remaining -= used
        if remaining == 0:
            break
    return var, weighted_loss / tail


def objective_reference(scenarios, alpha):
    # Independent piecewise-linear minimization characterization for this fixture.
    return min(t + sum(w * max(loss - t, 0) for loss, w in scenarios) / (1 - alpha)
               for t in {loss for loss, _ in scenarios})


if __name__ == "__main__":
    sample = [(F(x), F(1, 10)) for x in [0, 0, 0, 0, 0, 0, 10, 20, 40, 100]]
    for alpha, expected in [(F(3, 4), (F(20), F(60))),
                            (F(4, 5), (F(20), F(70))),
                            (F(9, 10), (F(40), F(100)))]:
        result = tail_metrics(sample, alpha)
        assert result == expected
        assert result[1] == objective_reference(sample, alpha)
        print(f"Confidence {float(alpha):.0%}: VaR={result[0]}, ES={result[1]}")
    binary = [(F(-30), F(24, 25)), (F(70), F(1, 25))]
    assert tail_metrics(binary, F(19, 20)) == (F(-30), F(50))
    assert objective_reference(binary, F(19, 20)) == 50
    for shift in [F(-17), F(3)]:
        moved = [(x + shift, w) for x, w in sample]
        assert tail_metrics(moved, F(3, 4)) == (20 + shift, 60 + shift)
    assert tail_metrics([(2*x, w) for x, w in sample], F(3, 4)) == (40, 120)
    assert tail_metrics([(F(0), F(24, 25)), (F(100), F(1, 25))], F(19, 20)) == (0, 80)
    assert tail_metrics([(F(0), F(24, 25)), (F(500), F(1, 25))], F(19, 20)) == (0, 400)
    for bad in [[], [(F(1), F(1, 2))], [(F(0), F(-1)), (F(2), F(2))]]:
        try:
            tail_metrics(bad, F(3, 4))
        except ValueError:
            pass
        else:
            raise AssertionError("Expected invalid weight rejection")
    print("Binary fixture: VaR=-30, ES=50. Independent objective checks passed.")
    print("All fixtures are supplied teaching distributions, not forecasts.")
