"""Offline reproduction of one frozen Coinbase window and two fictional paths. Python 3 standard library only. Reads local files; no network or trading calls. The Decimal calculations are independently checked by verify-fractions.py.txt. """ from pathlib import Path from datetime import datetime, timezone from decimal import Decimal, localcontext from fractions import Fraction import csv import hashlib import json ROOT=Path(__file__).resolve().parent INTERVAL=900 def epoch(iso): value=datetime.fromisoformat(iso.replace('Z','+00:00')) if value.tzinfo is None or value.utcoffset() is None: raise ValueError('UTC offset required') return int(value.timestamp()) def utc(t): return datetime.fromtimestamp(t,timezone.utc).isoformat().replace('+00:00','Z') def percent(numerator,denominator): # Preserve the exact fraction; the displayed decimal is explicitly rounded. ratio=Fraction(numerator)/Fraction(denominator)*100 with localcontext() as ctx: ctx.prec=60 approximation=(Decimal(ratio.numerator)/Decimal(ratio.denominator)).quantize(Decimal('0.00000001')) return dict(exact_numerator=ratio.numerator,exact_denominator=ratio.denominator, percent_decimal_rounded_8=str(approximation)) def normalize(raw_bytes,provenance): raw=json.loads(raw_bytes,parse_float=Decimal,parse_int=Decimal) if not isinstance(raw,list): raise ValueError('Expected array of candle arrays') start=epoch(provenance['window_start_utc']); end=epoch(provenance['window_end_exclusive_utc']) if start%INTERVAL or end%INTERVAL or end-start!=86400: raise ValueError('Expected UTC-aligned 24-hour bucket window') rows={};invalid=[];outside=[];identical=0;conflicting=0 for index,row in enumerate(raw): try: if not isinstance(row,list) or len(row)!=6: raise ValueError('Expected six values: time, low, high, open, close, volume') if not all(isinstance(x,Decimal) and x.is_finite() for x in row): raise ValueError('All fields must be finite JSON numbers') timestamp=row[0] if timestamp!=timestamp.to_integral_value(): raise ValueError('Timestamp must be integer seconds') timestamp=int(timestamp) if timestamp%INTERVAL: raise ValueError('Bucket start is not aligned to the interval') low,high,opening,closing,volume=row[1:] if min(low,high,opening,closing)<=0 or volume<0: raise ValueError('Invalid price or volume sign') if not low<=opening<=high or not low<=closing<=high: raise ValueError('Open/close outside low/high bounds') except (ValueError,TypeError) as exc: invalid.append(dict(raw_index=index,reason=str(exc)));continue if not start<=timestampend: outside.append(dict(raw_index=index,start_utc=utc(timestamp),reason='outside completed [start,end) bucket window')) continue normalized=dict(start_epoch=timestamp,start_utc=utc(timestamp),end_exclusive_utc=utc(timestamp+INTERVAL), low=str(low),high=str(high),open=str(opening),close=str(closing),volume=str(volume)) if timestamp in rows: if rows[timestamp]!=normalized: conflicting+=1 raise ValueError('Conflicting duplicate bucket: refuse to select a value') identical+=1 else: rows[timestamp]=normalized ordered=[rows[t] for t in sorted(rows)] expected=list(range(start,end,INTERVAL));missing=[utc(t) for t in expected if t not in rows] qa=dict(raw_count=len(raw),retained_unique_count=len(ordered),expected_count=len(expected), invalid_count=len(invalid),invalid_rows=invalid,excluded_window_count=len(outside),excluded_rows=outside, identical_duplicate_count=identical,conflicting_duplicate_count=conflicting, missing_count=len(missing),missing_bucket_starts_utc=missing, raw_sha256=hashlib.sha256(raw_bytes).hexdigest(), duplicate_rule='identical records collapse; conflicting records fail', missing_rule='no zero fill, interpolation or carried-forward price') return ordered,qa def observed_statistics(rows): if len(rows)<2: raise ValueError('At least two observed closes required') first,last=rows[0],rows[-1] high=max(rows,key=lambda r:Decimal(r['high']));low=min(rows,key=lambda r:Decimal(r['low'])) high_close=max(rows,key=lambda r:Decimal(r['close']));low_close=min(rows,key=lambda r:Decimal(r['close'])) peak=first;worst=Decimal(0);dd_peak=first;dd_trough=first with localcontext() as ctx: ctx.prec=60 for row in rows: if Decimal(row['close'])>Decimal(peak['close']):peak=row drop=(Decimal(peak['close'])-Decimal(row['close']))/Decimal(peak['close']) if drop>worst:worst=drop;dd_peak=peak;dd_trough=row close_at=lambda r:dict(start_utc=r['start_utc'],end_exclusive_utc=r['end_exclusive_utc'],price=r['close']) result=dict(first_recorded_close=close_at(first),last_recorded_close=close_at(last), highest_bucket_high=dict(start_utc=high['start_utc'],end_exclusive_utc=high['end_exclusive_utc'],price=high['high']), lowest_bucket_low=dict(start_utc=low['start_utc'],end_exclusive_utc=low['end_exclusive_utc'],price=low['low']), highest_recorded_close=close_at(high_close),lowest_recorded_close=close_at(low_close), high_minus_highest_close=str(Decimal(high['high'])-Decimal(high_close['close'])), lowest_close_minus_low=str(Decimal(low_close['close'])-Decimal(low['low'])), close_to_close_return=percent(Decimal(last['close'])-Decimal(first['close']),Decimal(first['close'])), maximum_close_drawdown=percent(Decimal(dd_peak['close'])-Decimal(dd_trough['close']),Decimal(dd_peak['close'])), drawdown_peak=close_at(dd_peak),drawdown_trough=close_at(dd_trough), bucket_end_boundary_separation_seconds=last['start_epoch']-first['start_epoch'], actual_last_trade_timestamps_available=False, scope='observed Coinbase Exchange LTC-USD buckets only; not all venues or executable quotes') return result def fictional_statistics(path): prices=[Decimal(x) for x in path['ordered_prices']] peak=prices[0];worst_num=Decimal(0);worst_den=peak for price in prices: peak=max(peak,price) if Fraction(peak-price)/Fraction(peak)>Fraction(worst_num)/Fraction(worst_den): worst_num,worst_den=peak-price,peak return dict(case_id=path['case_id'],fictional=True, ohlc=dict(open=str(prices[0]),high=str(max(prices)),low=str(min(prices)),close=str(prices[-1])), first_to_last_return=percent(prices[-1]-prices[0],prices[0]), maximum_ordered_point_drawdown=percent(worst_num,worst_den), scope='four constructed ordered price points; no observed ticks, timestamps, volume, fees or execution model') def compute(root=ROOT): provenance=json.loads((root/'provenance.json').read_text(encoding='utf-8')) raw_bytes=(root/'coinbase-response.json').read_bytes() assert hashlib.sha256(raw_bytes).hexdigest()==provenance['raw_sha256'] assert epoch(provenance['retrieved_at_utc'])>=epoch(provenance['window_end_exclusive_utc']) rows,qa=normalize(raw_bytes,provenance) paths=json.loads((root/'fictional-paths.json').read_text(encoding='utf-8'))['cases'] return rows,dict(version='2026-10-12-v1',source_provenance=provenance,coverage=qa, observed=observed_statistics(rows),fictional_paths=[fictional_statistics(p) for p in paths]) def verify(): rows,result=compute() saved=json.loads((ROOT/'results.json').read_text(encoding='utf-8')) assert saved==result,'Published result differs from raw response reproduction' with (ROOT/'candles.csv').open(encoding='utf-8',newline='') as f: cr=list(csv.DictReader(f)) assert len(cr)==len(rows) for row,other in zip(rows,cr): assert all(other[k]==str(v) for k,v in row.items()),row['start_utc'] normalized_json=json.loads((ROOT/'candles.json').read_text(encoding='utf-8')) assert normalized_json['candles']==rows,'Normalized JSON differs from raw response reproduction' assert result['coverage']['expected_count']==96 assert result['coverage']['retained_unique_count']==96 assert result['coverage']['invalid_count']==result['coverage']['missing_count']==0 assert result['coverage']['identical_duplicate_count']==result['coverage']['conflicting_duplicate_count']==0 assert result['coverage']['excluded_window_count']==1 a,b=result['fictional_paths'] assert a['ohlc']==b['ohlc']==dict(open='60',high='66',low='54',close='62') assert a['first_to_last_return']==b['first_to_last_return'] assert a['maximum_ordered_point_drawdown']!=b['maximum_ordered_point_drawdown'] print(json.dumps(dict(result='PASS',observed_buckets=len(rows),expected_buckets=96, excluded_raw_rows=1,actual_trade=False,fictional_path_count=2, return_percent=result['observed']['close_to_close_return']['percent_decimal_rounded_8'], drawdown_percent=result['observed']['maximum_close_drawdown']['percent_decimal_rounded_8']),indent=2)) if __name__=='__main__': verify()