#!/usr/bin/env python3 """Collect Kalshi temperature market candles on your own device for your own trading. python3 fetch-weather-prices.py --city knyc --start 2026-10-25 --end 2026-10-31 --output knyc-prices.csv.gz Dates are inclusive station-local target dates. Prices are USD per YES contract. Use only with data access and uses permitted to you. This script does not submit orders or upload data. """ import argparse import csv from datetime import date, datetime, timezone from decimal import Decimal import gzip from http.client import IncompleteRead import json import os from pathlib import Path import re from zoneinfo import ZoneInfo import sys from tempfile import NamedTemporaryFile import time from urllib.error import HTTPError, URLError from urllib.parse import quote, urlencode from urllib.request import Request, urlopen API = 'https://external-api.kalshi.com/trade-api/v2' REGISTRY = 'https://kalshireport.com/downloads/temperature-history/2026-11-02/index.json' PERIOD_METRICS = {'KXHDDCVG':'heating_degree_days','KXAVGTKIAH':'consecutive_average_temperature', 'KXMSNLOWT':'period_minimum','KXSJCLOWT':'period_minimum'} FIELDS = ('ticker','event_ticker','series_ticker','city_id','target_local_date','metric', 'price_ts_utc','price_kind','yes_price_dollars','yes_bid_dollars','yes_ask_dollars', 'volume_contracts','period_minutes','contract_period_start_local_date','contract_period_end_local_date','contract_rule','strike_type','floor_strike','cap_strike','strike_unit', 'yes_sub_title','open_time','close_time','settlement_ts','settlement_result','source') TICKER = re.compile(r'^([A-Z0-9]+)-+(?:\d+-)?(\d{2}[A-Z]{3}\d{2})-[A-Z0-9.+-]+$') MONTHS = 'JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC'.split() def get(url, params=None): if params: url += '?' + urlencode(params) request = Request(url, headers={'User-Agent':'WeatherBacktest-Local/1.0','Accept-Encoding':'gzip'}) for attempt in range(4): try: with urlopen(request, timeout=45) as response: data = response.read() if response.headers.get('Content-Encoding') == 'gzip': data = gzip.decompress(data) return json.loads(data) except (HTTPError, URLError, TimeoutError, IncompleteRead) as error: if (isinstance(error, HTTPError) and error.code not in (429,500,502,503,504)) or attempt == 3: raise retry = error.headers.get('Retry-After','') if isinstance(error, HTTPError) else '' delay = max(2**(attempt+1), int(retry) if retry.isdecimal() else 0) if delay > 120: raise time.sleep(delay) def target(ticker): m = TICKER.fullmatch(ticker) if not m: return None d = m[2] try: return date(2000 + int(d[:2]), MONTHS.index(d[2:5])+1, int(d[5:])) except ValueError: return None def period_dates(m, series): rules = m.get('rules_primary') or '' match = re.search(r'(?:within|between) ([A-Za-z]+ \d{1,2}, 20\d\d) (?:and|through) ([A-Za-z]+ \d{1,2}, 20\d\d)',rules,re.I) if match: def parse_day(text): month, day, year = text.replace(',','').split() return date(int(year),MONTHS.index(month[:3].upper())+1,int(day)).isoformat() return parse_day(match[1]),parse_day(match[2]) if series=='KXMSNLOWT' and "Market Open Time" in rules: end = re.search(r'end of ([A-Za-z]+ \d{1,2}, 20\d\d) in America/Chicago',rules) if end: month,day,year=end[1].replace(',','').split() start=datetime.fromtimestamp(epoch(m['open_time']),ZoneInfo('America/Chicago')).date() return start.isoformat(),date(int(year),MONTHS.index(month[:3].upper())+1,int(day)).isoformat() return '','' def market_pages(series, getter=get): found = {} # Query live first, then archive. A market can move between reads; prefer archived terms if duplicated. for tier in ('live','historical'): params = {'series_ticker':series,'limit':1000} seen = set() while True: path = '/markets' if tier == 'live' else '/historical/markets' data = getter(API+path, params) for m in data['markets']: if m['ticker'].split('-')[0] in (series,series.removeprefix('KX')): found[m['ticker']] = (m, tier) cursor = data.get('cursor') if not cursor: break if cursor in seen: raise ValueError('Exchange repeated a market page') seen.add(cursor) params['cursor'] = cursor time.sleep(0.2) return found.values() def epoch(value): # Python 3.9 accepts three or six fractional digits. The API also emits other precisions. stamp = re.sub(r'\.(\d+)(?=Z|[+-]\d{2}:\d{2}$)', lambda m: '.'+m[1][:6].ljust(6,'0'), value) return datetime.fromisoformat(stamp.replace('Z','+00:00')).timestamp() def candle_path(ticker, series, tier): ticker = quote(ticker, safe='') if tier == 'historical': return '/historical/markets/'+ticker+'/candlesticks' return '/series/'+quote(series, safe='')+'/markets/'+ticker+'/candlesticks' def close_price(field): if not isinstance(field, dict): return '' if field.get('close_dollars') is not None: v = Decimal(str(field['close_dollars'])) elif field.get('close') is not None: raw = field['close'] v = Decimal(str(raw)) / (100 if isinstance(raw, int) else 1) else: return '' if not v.is_finite() or not 0 <= v <= 1: raise ValueError('Invalid price in provider candle') return format(v,'f') def candle_rows(m, tier, series, city, metric, unit, period, getter=get, window=None): ticker = m['ticker'] start, end = epoch(m['open_time']), min(epoch(m['close_time']),time.time()) if end <= start: return start_s, end_s = int(start), int(end) if window: start_s, end_s = max(start_s,window[0]), min(end_s,window[1]) measure = target(ticker) if series not in PERIOD_METRICS else None pstart, pend = period_dates(m,series) if series in PERIOD_METRICS else ('','') # Bounded ranges avoid endpoint truncation even for older long-lived contracts. span = period*60*4000 for left in range(start_s,end_s+1,span): args = {'start_ts':left,'end_ts':min(left+span-1,end_s),'period_interval':period} actual_tier = tier try: page = getter(API+candle_path(ticker,series,tier),args) except HTTPError as e: if e.code != 404: raise actual_tier = 'historical' if tier == 'live' else 'live' page = getter(API+candle_path(ticker,series,actual_tier),args) if page.get('ticker', ticker) != ticker: raise ValueError('Candle response has wrong market') times = set() for c in sorted(page['candlesticks'],key=lambda r:r['end_period_ts']): t = c['end_period_ts'] if not isinstance(t,int): raise ValueError('Invalid candle end timestamp') if not (start < t <= end and left <= t <= args['end_ts']): continue if t in times: raise ValueError('Duplicate candle in exchange response') times.add(t) p,b,a = (close_price(c.get(name)) for name in ('price','yes_bid','yes_ask')) volume = c.get('volume_fp',c.get('volume')) if volume is not None and Decimal(str(volume)) == 0: p = '' if p==b==a=='': continue yield {**{key:m.get(key,'') for key in ('ticker','event_ticker','open_time','close_time','settlement_ts','yes_sub_title','strike_type','floor_strike','cap_strike')}, 'series_ticker':series,'city_id':city,'target_local_date':measure.isoformat() if measure else '', 'contract_period_start_local_date':pstart,'contract_period_end_local_date':pend, 'contract_rule':m.get('rules_primary','') if series in PERIOD_METRICS else '', 'metric':metric,'strike_unit':unit,'settlement_result':m.get('result',''), 'price_ts_utc':datetime.fromtimestamp(t,timezone.utc).isoformat().replace('+00:00','Z'), 'price_kind':'candle_close','period_minutes':period,'yes_price_dollars':p, 'yes_bid_dollars':b,'yes_ask_dollars':a,'volume_contracts':c.get('volume_fp',c.get('volume','')), 'source':'kalshi_'+actual_tier+'_candlesticks'} time.sleep(0.2) def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--city',required=True,help='Station id on the Kalshi Report city page, e.g. knyc') parser.add_argument('--start',required=True,type=date.fromisoformat) parser.add_argument('--end',required=True,type=date.fromisoformat) parser.add_argument('--metric',choices=('daily_high','daily_low','period'),default='daily_high',help='For period contracts --start/--end filter UTC candle dates; daily metrics filter station-local target dates') parser.add_argument('--period',type=int,choices=(1,60,1440),default=60,help='Candle period in minutes (default 60)') parser.add_argument('--output',required=True,type=Path,help='Local .csv or .csv.gz file') args = parser.parse_args() if args.end < args.start: parser.error('--end must be on or after --start') if not args.output.name.endswith(('.csv','.csv.gz')): parser.error('--output must end in .csv or .csv.gz') registry = get(REGISTRY) station = next((s for s in registry['stations'] if s['city_id']==args.city.lower()),None) if not station: parser.error('Unknown station id') prefix = 'KXHIGH' if args.metric=='daily_high' else 'KXLOW' series_list = [s for s in station['series'] if (s in PERIOD_METRICS if args.metric=='period' else s.startswith(prefix))] if not series_list: parser.error('No supported single-station series for this metric') args.output.parent.mkdir(parents=True,exist_ok=True) with NamedTemporaryFile(dir=args.output.parent,prefix='.weather-prices-',delete=False) as temp: tmp=Path(temp.name) counts = {'markets':0,'priced_markets':0,'price_rows':0} try: writer_open = gzip.open if args.output.name.endswith('.gz') else open with writer_open(tmp,'wt',encoding='utf-8',newline='') as f: writer=csv.DictWriter(f,fieldnames=FIELDS,lineterminator='\n') writer.writeheader() for series in series_list: for m,tier in market_pages(series): day=target(m['ticker']) window = None if args.metric == 'period': window = (int(datetime.fromisoformat(args.start.isoformat()).replace(tzinfo=timezone.utc).timestamp()), int(datetime.fromisoformat(args.end.isoformat()).replace(tzinfo=timezone.utc).timestamp())+86399) if epoch(m['close_time']) < window[0] or epoch(m['open_time']) > window[1]: continue elif not day or not args.start <= day <= args.end: continue counts['markets']+=1 rows=0 unit = 'F' if station['country']=='United States' else 'C' if args.metric == 'period': unit = {'KXHDDCVG':'HDD','KXAVGTKIAH':'days'}.get(series,'F') for row in candle_rows(m,tier,series,station['city_id'],PERIOD_METRICS.get(series,args.metric),unit,args.period,window=window): writer.writerow(row) rows+=1 counts['price_rows']+=rows counts['priced_markets']+=int(rows>0) os.replace(tmp,args.output) finally: tmp.unlink(missing_ok=True) print(json.dumps(counts),file=sys.stderr) if __name__=='__main__': main()