Keep a growing record of every draw in the excel sheets

- records.py: merge new draws into each sheet instead of replacing it, so
  history older than what the WV lottery site keeps is not lost. Cash Pop
  rows are matched by draw id (several draws a day share Date+Numbers).
- All scrapers use records.draw_day() for the draw date and merge_save()
  for the sheet; cash pop now keeps its own cash_pop.xlsx.
- Sheets updated with the latest draws, including the backfilled 10/10
  Powerball and Lotto America draws.
- Ignore __pycache__, cron logs, sheet lock files and server-side backups.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
williedynamiteandClaude Opus 5.5 committed 2026-10-12 07:12:55 -04:00
1 parent f52dd964ad
commit a8698c88d3
16 files changed
+153 -13

No files matched your search

+6
View File
@@ -4,3 +4,9 @@ dump.rdb
*.csv
# Git
.git/*
# Python cache, cron output, lock files and pre-change sheet backups made on the server
__pycache__/
cron.log*
excel_lotto_records/.*.lock
*.pre-recording
*.pre-ny-backfill
+4 -2
View File
@@ -2,6 +2,7 @@
from fractions import Fraction as frac
from math import comb
import pandas as pd
import records
import requests
from collections import Counter
import csv
@@ -22,7 +23,7 @@ def get_data():
r = requests.get(url + str(page), headers=header)
data = r.json()
for x in data['content']:
web['Date'].append(x['drawingDate'])
web['Date'].append(records.draw_day(x))
web['Numbers'].append('–'.join(str(n['data']) for n in x['resultData'] if n['type'] == 'REGULAR'))
if data['last']:
break
@@ -30,7 +31,8 @@ def get_data():
dfs = [pd.DataFrame(web)]
pd.set_option('display.max_rows', None)
# Specifies no max rows, otherwise only shows 10 records
df = pd.concat([dfs[0], salvaged], ignore_index=True)
# Adds any draw not in the sheet yet, so the excel record keeps growing
df = records.merge_save('./excel_lotto_records/cash25.xlsx', dfs[0], fallback=salvaged)
df2 = df[['Date', 'Numbers']]
date = list(df2['Date'])
nums = list(df2['Numbers'].astype('str'))
+7 -1
View File
@@ -1,6 +1,7 @@
# WVLottopy: Matteo DiBiagio
from fractions import Fraction as frac
import pandas as pd
import records
import requests
from collections import Counter
import csv
@@ -12,17 +13,22 @@ def get_data():
}
# Get web data, cash pop draws every 15 min so only use the last ~3000 draws (about a month)
web = {'Date': [], 'Numbers': []}
ids, times = [], []
page = 0
while page < 6:
r = requests.get(url + str(page), headers=header)
data = r.json()
for x in data['content']:
web['Date'].append(x['drawingDate'])
web['Date'].append(records.draw_day(x))
web['Numbers'].append('–'.join(str(n['data']) for n in x['resultData'] if n['type'] == 'REGULAR'))
ids.append(x['externalId'])
times.append(x['drawDate'])
if data['last']:
break
page += 1
df2 = pd.DataFrame(web)
# The site only keeps a year of cash pop draws, keep our own record of every draw
records.merge_save('./excel_lotto_records/cash_pop.xlsx', df2, ids=ids, times=times)
date = list(df2['Date'])
nums = list(df2['Numbers'].astype('str'))
return date, nums
+4 -2
View File
@@ -1,6 +1,7 @@
# WVLottopy: Matteo DiBiagio
from fractions import Fraction as frac
import pandas as pd
import records
import requests
from collections import Counter
import csv
@@ -21,7 +22,7 @@ def get_data():
r = requests.get(url + str(page), headers=header)
data = r.json()
for x in data['content']:
web['Date'].append(x['drawingDate'])
web['Date'].append(records.draw_day(x))
web['Numbers'].append('–'.join(str(n['data']) for n in x['resultData'] if n['type'] == 'REGULAR'))
if data['last']:
break
@@ -29,7 +30,8 @@ def get_data():
dfs = [pd.DataFrame(web)]
pd.set_option('display.max_rows', None)
# Specifies no max rows, otherwise only shows 10 records
df = pd.concat([dfs[0], salvaged], ignore_index=True)
# Adds any draw not in the sheet yet, so the excel record keeps growing
df = records.merge_save('./excel_lotto_records/daily3.xlsx', dfs[0], fallback=salvaged)
df2 = df[['Date', 'Numbers']]
date = list(df2['Date'])
nums = list(df2['Numbers'].astype('str'))
+4 -2
View File
@@ -1,6 +1,7 @@
# WVLottopy: Matteo DiBiagio
from fractions import Fraction as frac
import pandas as pd
import records
import requests
from collections import Counter
import csv
@@ -21,7 +22,7 @@ def get_data():
r = requests.get(url + str(page), headers=header)
data = r.json()
for x in data['content']:
web['Date'].append(x['drawingDate'])
web['Date'].append(records.draw_day(x))
web['Numbers'].append('–'.join(str(n['data']) for n in x['resultData'] if n['type'] == 'REGULAR'))
if data['last']:
break
@@ -29,7 +30,8 @@ def get_data():
dfs = [pd.DataFrame(web)]
pd.set_option('display.max_rows', None)
# Specifies no max rows, otherwise only shows 10 records
df = pd.concat([dfs[0], salvaged], ignore_index=True)
# Adds any draw not in the sheet yet, so the excel record keeps growing
df = records.merge_save('./excel_lotto_records/daily4.xlsx', dfs[0], fallback=salvaged)
df2 = df[['Date', 'Numbers']]
date = list(df2['Date'])
nums = list(df2['Numbers'].astype('str'))
Executable → Regular
BIN
View File
Binary file not shown.
Binary file not shown.
Executable → Regular
BIN
View File
Binary file not shown.
Executable → Regular
BIN
View File
Binary file not shown.
Executable → Regular
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+4 -2
View File
@@ -2,6 +2,7 @@
from fractions import Fraction as frac
from math import comb
import pandas as pd
import records
import requests
from collections import Counter
import csv
@@ -22,7 +23,7 @@ def get_data():
r = requests.get(url + str(page), headers=header)
data = r.json()
for x in data['content']:
web['Date'].append(x['drawingDate'])
web['Date'].append(records.draw_day(x))
web['Numbers'].append('–'.join(str(n['data']) for n in x['resultData'] if n['type'] == 'REGULAR'))
web['SB'].append([n['data'] for n in x['resultData'] if n['type'] == 'SPECIAL'][0])
if data['last']:
@@ -31,7 +32,8 @@ def get_data():
dfs = [pd.DataFrame(web)]
pd.set_option('display.max_rows', None)
# Specifies no max rows, otherwise only shows 10 records
df = pd.concat([dfs[0], salvaged], ignore_index=True)
# Adds any draw not in the sheet yet, so the excel record keeps growing
df = records.merge_save('./excel_lotto_records/lotto_america.xlsx', dfs[0], fallback=salvaged)
df2 = df[['Date', 'Numbers', 'SB']]
date = list(df2['Date'])
nums = list(df2['Numbers'].astype('str'))
+4 -2
View File
@@ -2,6 +2,7 @@
from fractions import Fraction as frac
from math import comb
import pandas as pd
import records
import requests
from collections import Counter
import csv
@@ -22,7 +23,7 @@ def get_data():
r = requests.get(url + str(page), headers=header)
data = r.json()
for x in data['content']:
web['Date'].append(x['drawingDate'])
web['Date'].append(records.draw_day(x))
web['Numbers'].append('–'.join(str(n['data']) for n in x['resultData'] if n['type'] == 'REGULAR'))
web['PB'].append([n['data'] for n in x['resultData'] if n['type'] == 'SPECIAL'][0])
if data['last']:
@@ -31,7 +32,8 @@ def get_data():
dfs = [pd.DataFrame(web)]
pd.set_option('display.max_rows', None)
# Specifies no max rows, otherwise only shows 10 records
df = pd.concat([dfs[0], salvaged], ignore_index=True)
# Adds any draw not in the sheet yet, so the excel record keeps growing
df = records.merge_save('./excel_lotto_records/lotto.xlsx', dfs[0], fallback=salvaged)
df2 = df[['Date', 'Numbers', 'PB']]
date = list(df2['Date'])
nums = list(df2['Numbers'].astype('str'))
+4 -2
View File
@@ -2,6 +2,7 @@
from fractions import Fraction as frac
from math import comb
import pandas as pd
import records
import requests
from collections import Counter
import csv
@@ -23,7 +24,7 @@ def get_data():
r = requests.get(url + str(page), headers=header)
data = r.json()
for x in data['content']:
web['Date'].append(x['drawingDate'])
web['Date'].append(records.draw_day(x))
web['Numbers'].append('–'.join(str(n['data']) for n in x['resultData'] if n['type'] == 'REGULAR'))
web['MB'].append([n['data'] for n in x['resultData'] if n['type'] == 'SPECIAL'][0])
if data['last']:
@@ -32,7 +33,8 @@ def get_data():
dfs = [pd.DataFrame(web)]
pd.set_option('display.max_rows', None)
# Specifies no max rows, otherwise only shows 10 records
df = pd.concat([dfs[0], salvaged], ignore_index=True)
# Adds any draw not in the sheet yet, so the excel record keeps growing
df = records.merge_save('./excel_lotto_records/lotto_megamil.xlsx', dfs[0], fallback=salvaged)
df2 = df[['Date', 'Numbers', 'MB']]
date = list(df2['Date'])
nums = list(df2['Numbers'].astype('str'))
+116
View File
@@ -0,0 +1,116 @@
# WVLottopy records: keeps the excel history files growing as draws happen
# wvlottery.com only keeps ~3 years of results (Cash Pop one year), so every run appends any draw that is
# not in the sheet yet. Nothing is ever removed or rewritten, existing rows stay exactly as they are.
import fcntl
import os
import shutil
from collections import Counter
import pandas as pd
def draw_day(x):
# the site's drawingDate is the UTC date, so late evening draws (powerball, mega millions, lotto america at ~11pm ET)
# come out a day late. The real draw day is drawDate converted to Eastern time.
try:
from datetime import datetime
from zoneinfo import ZoneInfo
t = datetime.fromisoformat(str(x['drawDate']).replace('Z', '+00:00'))
return t.astimezone(ZoneInfo('America/New_York')).strftime('%Y-%m-%d')
except Exception:
return x['drawingDate']
def _fmt_date(d):
# site gives 2026-10-09, the sheets use 10/09/2026
s = str(d)[:10]
if len(s) == 10 and s[4] == '-':
return f'{s[5:7]}/{s[8:10]}/{s[0:4]}'
return s
def _fmt_nums(n):
# site numbers come split by an en dash, the sheets use a hyphen
return str(n).replace('–', '-').strip()
def _newer_first(df):
# some sheets are oldest first, some newest first
d = pd.to_datetime(df['Date'], errors='coerce').dropna()
return len(d) > 1 and d.iloc[0] > d.iloc[-1]
def merge_save(path, web_df, fallback=None, ids=None, times=None):
# recording must never break the forecast: if anything goes wrong the old behaviour (site + sheet) is used
try:
return _merge_save(path, web_df, ids, times)
except Exception as e:
print(f'records: could not update {os.path.basename(path)}: {e!r}')
if fallback is not None:
return pd.concat([web_df, fallback], ignore_index=True)
return None
def _merge_save(path, web_df, ids=None, times=None):
"""Append draws from the site (web_df: Date, Numbers[, bonus col]) that the sheet at path does not have yet.
ids: optional list of site draw ids, same length as web_df. Returns the whole sheet as Date/Numbers/[bonus]
so callers can keep counting from one source. If the site gave nothing the sheet is left alone."""
bonus = [c for c in web_df.columns if c not in ('Date', 'Numbers')]
if os.path.exists(path):
old = pd.read_excel(path)
else:
old = pd.DataFrame(columns=['Unnamed: 0', 'Date', 'Numbers'] + bonus)
if len(web_df) == 0:
return old[['Date', 'Numbers'] + bonus].copy()
web = web_df.copy()
web['Date'] = web['Date'].map(_fmt_date)
web['Numbers'] = web['Numbers'].map(_fmt_nums)
if ids is not None:
web['DrawID'] = [str(i) for i in ids]
if times is not None:
web['DrawTime'] = [str(t) for t in times]
def key(r):
return (str(r['Date']), _fmt_nums(r['Numbers'])) + tuple(str(int(r[c])) if str(r[c]) not in ('nan', 'None', '') else '' for c in bonus)
have_ids = set(old['DrawID'].dropna().astype(str)) if 'DrawID' in old.columns else set()
# Rows that carry a draw id are matched by id only. The Date+Numbers match is just for old rows without an id:
# cash pop draws one number out of 15 about 90 times a day, so other draws on the same day share Date+Numbers.
no_id = old['DrawID'].isna() if 'DrawID' in old.columns else pd.Series(True, index=old.index)
have = Counter(key(r) for _, r in old[no_id].iterrows())
keep = []
for _, r in web.iterrows():
if 'DrawID' in web.columns and str(r['DrawID']) in have_ids:
continue
k = key(r)
if have[k] > 0:
have[k] -= 1
continue
keep.append(r)
new = pd.DataFrame(keep, columns=web.columns)
if len(new):
lock = open(os.path.join(os.path.dirname(path) or '.', '.' + os.path.basename(path) + '.lock'), 'w')
fcntl.flock(lock, fcntl.LOCK_EX)
try:
backup = path + '.pre-recording'
if os.path.exists(path) and not os.path.exists(backup):
shutil.copy2(path, backup)
new['_d'] = pd.to_datetime(new['Date'], errors='coerce')
desc = _newer_first(old) if len(old) else True
new = new.sort_values('_d', ascending=not desc, kind='stable').drop(columns='_d')
start = int(pd.to_numeric(old['Unnamed: 0'], errors='coerce').max() + 1) if len(old) and 'Unnamed: 0' in old.columns else 0
new.insert(0, 'Unnamed: 0', range(start, start + len(new)))
full = pd.concat([new, old], ignore_index=True) if desc else pd.concat([old, new], ignore_index=True)
tmp = path[:-5] + '.tmp.xlsx'
full.to_excel(tmp, index=False, engine='openpyxl')
os.replace(tmp, path)
finally:
fcntl.flock(lock, fcntl.LOCK_UN)
lock.close()
print(f'records: {os.path.basename(path)} +{len(new)} new draws')
else:
full = old
out = full[['Date', 'Numbers'] + bonus].copy()
return out