AFOS · USA 2024 Electoral Divergence — initial dataset (market × polls × press, honest two-market case)
dd99673 | import { readFileSync, writeFileSync, copyFileSync } from 'node:fs' | |
| const OUT = '.cache/usa2024/dataset' | |
| const day = t => new Date(t*1000).toISOString().slice(0,10) | |
| // ---------- helper: extrai série diária Trump/Harris de um mercado ---------- | |
| function marketSeries(path, label){ | |
| const j = JSON.parse(readFileSync(path,'utf8')) | |
| const want = {'Donald Trump':'Trump','Kamala Harris':'Harris'} | |
| const byDate = {} | |
| for (const o of j.odds){ | |
| const cn = want[o.candidate]; if(!cn) continue | |
| for (const h of (o.history||[])){ const d=day(h.t); byDate[d]=byDate[d]||{}; byDate[d][cn]=h.p*100 } | |
| } | |
| // CSV | |
| let csv='date,candidate,win_prob_pct\n' | |
| const dates=Object.keys(byDate).sort() | |
| for(const d of dates) for(const c of ['Trump','Harris']) if(byDate[d][c]!=null) csv+=`${d},${c},${byDate[d][c].toFixed(2)}\n` | |
| return {byDate, dates, csv, title:j.title, totalVol:j.odds.reduce((s,o)=>s+(o.volume||0),0)} | |
| } | |
| const winner = marketSeries('.cache/usa2024/poly-winner-raw.json','winner') // EIXO PRIMÁRIO (colégio) | |
| const popvote = marketSeries('.cache/usa2024/poly-popularvote-raw.json','popvote') // CONTRAPONTO (voto popular) | |
| writeFileSync(`${OUT}/data/usa-winner-market-timeseries.csv`, winner.csv) | |
| writeFileSync(`${OUT}/data/usa-popularvote-market-timeseries.csv`, popvote.csv) | |
| copyFileSync('.cache/usa2024/poly-winner-raw.json', `${OUT}/data/usa-winner-poly-raw.json`) | |
| copyFileSync('.cache/usa2024/poly-popularvote-raw.json', `${OUT}/data/usa-popularvote-poly-raw.json`) | |
| // ---------- 538 national polls (Harris/Trump general 2024) ---------- | |
| const txt = readFileSync('.cache/usa2024/president_polls.csv','utf8') | |
| function parse(line){const out=[];let cur='';let q=false;for(let i=0;i<line.length;i++){const c=line[i];if(c==='"'){if(q&&line[i+1]==='"'){cur+='"';i++}else q=!q}else if(c===','&&!q){out.push(cur);cur=''}else cur+=c}out.push(cur);return out} | |
| const L=txt.split(/\r?\n/); const H=parse(L[0]); const ix=n=>H.indexOf(n) | |
| const C={cycle:ix('cycle'),stage:ix('stage'),state:ix('state'),cand:ix('candidate_name'),pct:ix('pct'),end:ix('end_date'),poll:ix('pollster'),samp:ix('sample_size'),pop:ix('population'),grade:ix('numeric_grade'),meth:ix('methodology'),url:ix('url'),pid:ix('poll_id')} | |
| const norm=d=>{const m=(d||'').match(/^(\d+)\/(\d+)\/(\d+)/);if(!m)return null;return `${2000+ +m[3]}-${String(+m[1]).padStart(2,'0')}-${String(+m[2]).padStart(2,'0')}`} | |
| let polls='poll_id,pollster,end_date,sample_size,population,numeric_grade,methodology,candidate,pct,source_url\n' | |
| const rows=[] | |
| for(let k=1;k<L.length;k++){ | |
| if(!L[k])continue; const f=parse(L[k]) | |
| if(f[C.cycle]!=='2024')continue | |
| if(!/general/i.test(f[C.stage]||''))continue | |
| if((f[C.state]||'').trim()!=='')continue | |
| const cand=f[C.cand]||''; const key=/Harris/.test(cand)?'Harris':(/Trump/.test(cand)?'Trump':null); if(!key)continue | |
| const ed=norm(f[C.end]); if(!ed)continue | |
| const pct=parseFloat(f[C.pct]); if(isNaN(pct))continue | |
| const esc=s=>{s=String(s||'');return /[",\n]/.test(s)?'"'+s.replace(/"/g,'""')+'"':s} | |
| polls+=[f[C.pid],esc(f[C.poll]),ed,f[C.samp],f[C.pop],f[C.grade],esc(f[C.meth]),key,pct,esc(f[C.url])].join(',')+'\n' | |
| rows.push({date:ed,cand:key,pct}) | |
| } | |
| writeFileSync(`${OUT}/polls/usa-national-polls.csv`, polls) | |
| // aggregate: média móvel trailing 7d por data | |
| const datesPoll=[...new Set(rows.map(r=>r.date))].sort() | |
| function trailingAvg(d,cand){ | |
| const lo=new Date(new Date(d)-6*86400000).toISOString().slice(0,10) | |
| const a=rows.filter(r=>r.cand===cand&&r.date<=d&&r.date>=lo).map(r=>r.pct) | |
| return a.length?a.reduce((s,x)=>s+x,0)/a.length:null | |
| } | |
| let aggCsv='date,candidate,poll_vote_share_pct_7dma\n' | |
| for(const d of datesPoll) for(const c of ['Trump','Harris']){const v=trailingAvg(d,c); if(v!=null) aggCsv+=`${d},${c},${v.toFixed(2)}\n`} | |
| writeFileSync(`${OUT}/data/usa-poll-aggregate-timeseries.csv`, aggCsv) | |
| // ---------- DIVERGÊNCIA: EIXO = colégio (P win) × pesquisa (vote share 7dma) ---------- | |
| // só período Harris×Trump (pós-saída de Biden: 2024-07-21). Honestidade: naive_gap = P(win) - vote_share (unidades diferentes) | |
| const START='2024-07-21' | |
| let div='date,candidate,market_win_prob_pct,poll_vote_share_pct,naive_gap_pp\n' | |
| let n=0 | |
| for(const d of winner.dates){ | |
| if(d<START) continue | |
| for(const c of ['Trump','Harris']){ | |
| const mp=winner.byDate[d]?.[c]; const pp=trailingAvg(d,c) | |
| if(mp==null||pp==null)continue | |
| div+=`${d},${c},${mp.toFixed(2)},${pp.toFixed(2)},${(mp-pp).toFixed(2)}\n`; n++ | |
| } | |
| } | |
| writeFileSync(`${OUT}/data/usa-divergence-timeseries.csv`, div) | |
| // ---------- RESUMO (caso validado) ---------- | |
| const eve='2024-11-04' | |
| const summary={ | |
| case:'USA 2024 Presidential Election', | |
| result:{winner:'Donald Trump',electoral_college:'Trump 312 × Harris 226',popular_vote:'Trump 49.8% × Harris 48.3% (Trump +1.5pp)'}, | |
| winner_market:{slug:'presidential-election-winner-2024',total_volume_usd:Math.round(winner.totalVol),eve_2024_11_04:{Trump:winner.byDate[eve]?.Trump,Harris:winner.byDate[eve]?.Harris},verdict:'RIGHT — favored Trump, Trump won'}, | |
| popularvote_market:{slug:'presidential-election-popular-vote-winner-2024',total_volume_usd:Math.round(popvote.totalVol),eve_2024_11_04:{Trump:popvote.byDate[eve]?.Trump,Harris:popvote.byDate[eve]?.Harris},verdict:'WRONG — favored Harris, Trump won the popular vote'}, | |
| polls_final:{Trump:trailingAvg('2024-11-04','Trump')?.toFixed(2),Harris:trailingAvg('2024-11-04','Harris')?.toFixed(2),note:'near-tie / slight Trump in 7dma; within MoE'}, | |
| honesty:'Two markets disagreed: the winner (EC) market called Trump (right) vs the poll near-tie; the popular-vote market favored Harris (wrong). Result vindicated the EC market and refuted the popular-vote market. naive_gap = P(win) − vote_share (different units, not scale-reconciled).' | |
| } | |
| writeFileSync(`${OUT}/data/usa-case-summary.json`, JSON.stringify(summary,null,2)) | |
| // console | |
| console.log('WINNER (EC) US$', (winner.totalVol/1e9).toFixed(2)+'bi | véspera: Trump', winner.byDate[eve].Trump.toFixed(1)+'% Harris', winner.byDate[eve].Harris.toFixed(1)+'% → CERTO') | |
| console.log('POP-VOTE US$', Math.round(popvote.totalVol/1e6)+'M | véspera: Trump', popvote.byDate[eve].Trump.toFixed(1)+'% Harris', popvote.byDate[eve].Harris.toFixed(1)+'% → ERRADO') | |
| console.log('PESQUISAS 7dma véspera: Trump', trailingAvg('2024-11-04','Trump').toFixed(1)+'% Harris', trailingAvg('2024-11-04','Harris').toFixed(1)+'%') | |
| console.log('538 polls:', rows.length, 'linhas |', datesPoll.length, 'datas | divergência (Harris×Trump pós-21/Jul):', n, 'linhas') | |
| console.log('\n=== trajetória DIVERGÊNCIA (colégio P-win Trump × pesquisa voto Trump) ===') | |
| for(const D of ['2024-08-01','2024-09-01','2024-10-01','2024-11-01','2024-11-04']){ | |
| const l=div.split('\n').find(x=>x.startsWith(D+',Trump,')) | |
| if(l){const[,, m,p,g]=l.split(','); console.log(` ${D} mercado P(win)=${m}% pesquisa voto=${p}% gap=${g}pp`)} | |
| } | |