"""Offline, pinned study-C archive. Python 3.11+ standard library only. Run: python reproduce.py Creates a new work/ subdirectory; shipped reference files are never overwritten. The preserved original analyzers/verifiers run without --fetch and with their assertions enabled, even if this wrapper was started with python -O. """ from pathlib import Path from fractions import Fraction from decimal import Decimal,InvalidOperation from datetime import datetime,timezone import csv,hashlib,json,math,os,shutil,subprocess,sys,tempfile BASE=Path(__file__).resolve().parent PINNED_INPUTS={'ecb-original.csv': '12bda408fce288c0d9f68de03beffc6d89592a8fde37aff2d336b122baaddab3', 'hypothetical-case.json': '144ab66732b40b99f14a2fb9820f1d43f14403401a9c51513751d4249704ca04', 'original-code/base-analyze.py': 'b61febe59f79f41bfb8dc5f8599f528190ed6c34f1485a91fbb3399ec79cc490', 'original-code/base-verify.py': 'fd700b0bf99ee9585803172aa3d62f9fbbbdc509ab3065ee541866b22fe28e70', 'original-code/quotation-analyze.py': '68bdc8b13cb7e2c603cb3dcbd59cdb4ad59a2db22220f0eafe36aa768926e71c', 'original-code/quotation-verify.py': 'de634ceb82faeb544e0879f01563f1ceb85b9ed5100dc05d78b5b582ee142998', 'reference/base-metrics.json': '3ae82ee79f814b56bda57e18ee96a5fdc42b3afedec5c45e04b70afb09fd76b1', 'reference/base-path.csv': '17122f7aa730efe8876d4117698b5bcf0d748271b8cb8371ebb61c243728bf65', 'reference/quotation-metrics.json': 'db9a7c21bdd7fba8e66c016fab75e482949ea2c7fe618a2c96d83c61bec04c17', 'reference/quotation-path.csv': '59f76b3049611543f7eea66cc272aac8cf8c6e8e8ce9fe00b798869c7ecaeae3', 'snapshot.json': 'b659d51afae5023583aa14c616936a73ea6b5bc55a72a2366aabe23474de44f8'} RAW_SHA='12bda408fce288c0d9f68de03beffc6d89592a8fde37aff2d336b122baaddab3' TOLERANCE=Decimal('1e-11') def require(ok,message): if not ok:raise ValueError(message) def sha(blob):return hashlib.sha256(blob).hexdigest() def compare(expected,actual,label='result'): if isinstance(expected,dict): require(isinstance(actual,dict)and set(expected)==set(actual),'Object fields differ: '+label) for key in expected:compare(expected[key],actual[key],label+'/'+key) elif isinstance(expected,list): require(isinstance(actual,list)and len(expected)==len(actual),'List length differs: '+label) for i,(a,b)in enumerate(zip(expected,actual)):compare(a,b,label+'/'+str(i)) elif isinstance(expected,bool)or expected is None or isinstance(expected,str)or isinstance(expected,int): require(type(expected)is type(actual)and expected==actual,'Exact field differs: '+label) else: require(isinstance(actual,(int,float))and math.isfinite(expected)and math.isfinite(actual),'Nonfinite numerical result: '+label) require(abs(Decimal(str(expected))-Decimal(str(actual)))0 for x in values),'Invalid hypothetical inputs') changes=[100*(b/a-1)for a,b in zip(values,values[1:])] subset_declines=[maximum_decline([values[i]for i in indices])for indices in [exercise['period_A_indices'],exercise['period_B_indices']]] require(changes==[Fraction(x)for x in exercise['full_simple_changes_pct']],'Hypothetical changes differ') require(subset_declines==[Fraction(x)for x in exercise['within_period_maximum_declines_pct']]and maximum_decline(values)==Fraction(exercise['full_maximum_decline_pct']),'Hypothetical declines differ') for indices,expected in zip([exercise['period_A_indices'],exercise['period_B_indices']],exercise['within_period_simple_changes_pct']): subset=[values[i]for i in indices];require(len(subset)==2 and 100*(subset[1]/subset[0]-1)==Fraction(expected),'Hypothetical subperiod differs') work_parent=BASE/'work';work_parent.mkdir(exist_ok=True) work=Path(tempfile.mkdtemp(prefix='study-c-',dir=work_parent));require(work.resolve().is_relative_to(work_parent.resolve()),'Unexpected work directory') for folder in ['base','quotation']:(work/folder).mkdir() copies={'base/analyze.py':'original-code/base-analyze.py','base/verify.py':'original-code/base-verify.py', 'base/snapshot.json':'snapshot.json','base/ecb-eurusd-2016-2025-raw.csv':'ecb-original.csv', 'quotation/research-analyze.py':'original-code/quotation-analyze.py','quotation/research-verify.py':'original-code/quotation-verify.py', 'quotation/ecb-eurusd-original-2016-2025.csv':'ecb-original.csv'} for target,source in copies.items():shutil.copyfile(BASE/source,work/target) env=dict(os.environ);env['PYTHONOPTIMIZE']='0';env['PYTHONIOENCODING']='utf-8' calls=[] for relative in ['base/analyze.py','base/verify.py','quotation/research-analyze.py','quotation/research-verify.py']: script=work/relative process=subprocess.run([sys.executable,str(script)],cwd=script.parent,env=env,capture_output=True) (script.parent/(script.stem+'.stdout.txt')).write_bytes(process.stdout) (script.parent/(script.stem+'.stderr.txt')).write_bytes(process.stderr) require(process.returncode==0,'Preserved calculation/verification failed: '+relative) calls.append({'script':relative,'exit':process.returncode,'stdout_sha256':sha(process.stdout),'assertions_enabled':True}) compare(json.loads((BASE/'reference/base-metrics.json').read_text(encoding='utf-8')),json.loads((work/'base/metrics.json').read_text(encoding='utf-8')),'base') compare(json.loads((BASE/'reference/quotation-metrics.json').read_text(encoding='utf-8')),json.loads((work/'quotation/quotation-metrics.json').read_text(encoding='utf-8')),'quotation') base_rows=compare_csv(BASE/'reference/base-path.csv',work/'base/reference-rate-path.csv') quote_rows=compare_csv(BASE/'reference/quotation-path.csv',work/'quotation/quotation-path.csv') first=json.loads((work/'base/independent-verification.json').read_text(encoding='utf-8')) second=json.loads((work/'quotation/quotation-verification.json').read_text(encoding='utf-8')) require(first['status']=='PASS'and second['ok']is True,'Independent source verifiers did not pass') receipt={'status':'PASS','recalculated_utc':datetime.now(timezone.utc).isoformat(),'source_snapshot_retrieved_utc':'2026-10-07T14:18:17.889247+00:00', 'source_sha256':RAW_SHA,'source_observations':2560,'base_path_rows':base_rows,'quotation_path_rows':quote_rows, 'preserved_calculation_and_verification_calls':calls,'fresh_network_requests':0, 'hypothetical_case_checked_from_declared_inputs':True, 'comparison_tolerance_percentage_points':str(TOLERANCE), 'limits':'Pinned historical reference-rate data, not tradable quotes, equity, strategy performance, future-risk or expert endorsement. Historical source scripts may produce English figures carrying their original historical annotation; the supplied Russian figures are separate localized assets.'} (work/'reproduction-receipt.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2)+'\n',encoding='utf-8') print(json.dumps({'status':'PASS','observations':2560,'path_rows_each':base_rows,'work_directory':str(work.relative_to(BASE)),'fresh_network_requests':0,'preserved_verifier_programs':2},ensure_ascii=False)) if __name__=='__main__': try:run() except (OSError,ValueError,KeyError,TypeError)as error: print('FAIL: '+str(error),file=sys.stderr);raise SystemExit(1)