import csv
import json
from pathlib import Path
from statistics import mean


def moving_average(series, period):
    return [mean(series[i - period + 1:i + 1]) if i + 1 >= period else None
            for i in range(len(series))]


def visible_points(points):
    return sum(value is not None for value in points)


def rounded(value):
    return round(value, 2) if value is not None else None


def run():
    path = Path(__file__).with_name("kraken-daily-sample.csv")
    with path.open(encoding="utf-8", newline="") as source:
        closes = [float(row["btc_close"]) for row in csv.DictReader(source)]

    period = 20
    full = moving_average(closes, period)
    rows = []
    for size in (10, 20, 40, 80, 120):
        aligned = full[-size:]
        clipped = moving_average(closes[-size:], period)
        rows.append([size, visible_points(aligned), visible_points(clipped),
                     rounded(aligned[-1]), rounded(clipped[-1])])

    assert len(closes) == 120
    assert rows[0][1:] == [10, 0, 63613.99, None]
    assert rows[2][1:3] == [40, 21]
    assert rows[-1][1:3] == [101, 101]
    return rows


if __name__ == "__main__":
    print(json.dumps(run()))
