"""Reproduce the TradingSchule.com Q4 2024 Renko snapshot.

Keep renko_lab.py in the same folder and run: python renko_research.py
This fetches public historical inputs from FRED and the Bybit market API.
"""
import csv
import json
from datetime import datetime, timezone
from decimal import Decimal, ROUND_HALF_UP
from urllib.request import urlopen

from renko_lab import describe

START = "2024-10-01"
END = "2024-12-31"
BYBIT = "https://api.bybit.com/v5/market/kline"
FRED = "https://fred.stlouisfed.org/graph/fredgraph.csv?id=DEXUSEU"


def fetch(url):
    with urlopen(url, timeout=30) as response:
        return response.read().decode("utf-8-sig")


def inputs():
    rows = csv.reader(fetch(f"{FRED}&cosd={START}&coed={END}").splitlines())
    next(rows)
    yield "EUR/USD", Decimal("0.0001"), [(day, value) for day, value in rows
                                           if START <= day <= END and value not in ("", ".")]
    start = int(datetime(2024, 10, 1, tzinfo=timezone.utc).timestamp() * 1000)
    end = int(datetime(2025, 1, 1, tzinfo=timezone.utc).timestamp() * 1000) - 1
    for symbol in ("BTC", "ETH"):
        raw = json.loads(fetch(f"{BYBIT}?category=spot&symbol={symbol}USDT&interval=D&start={start}&end={end}&limit=92"))
        if raw["retCode"] != 0:
            raise ValueError(raw["retMsg"])
        records = sorted((datetime.fromtimestamp(int(row[0]) / 1000, tz=timezone.utc).date().isoformat(),
                          row[4]) for row in raw["result"]["list"])
        if len(records) != 92 or len({d for d, _ in records}) != 92 or records[0][0] != START or records[-1][0] != END:
            raise ValueError(f"{symbol} historical window is incomplete")
        yield f"{symbol}/USDT", Decimal("0.01"), records


def metrics(asset, precision, records):
    price = Decimal(records[0][1])
    output = []
    for bps in (25, 50, 100):
        size = (price * bps / 10000).quantize(precision, rounding=ROUND_HALF_UP)
        result = describe((value for _, value in records), size)
        output.append({"asset": asset, "bps": bps, "size": str(size), **result})
    return output


if __name__ == "__main__":
    print(json.dumps([row for args in inputs() for row in metrics(*args)], indent=2))
