diff --git a/.gitignore b/.gitignore index 6b70535..d6cbda8 100755 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/cash25.py b/cash25.py index d0ccd88..9967e70 100755 --- a/cash25.py +++ b/cash25.py @@ -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')) diff --git a/cashpop.py b/cashpop.py index 11bf633..8fabe81 100755 --- a/cashpop.py +++ b/cashpop.py @@ -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 diff --git a/daily3.py b/daily3.py index 5871cf6..f747040 100755 --- a/daily3.py +++ b/daily3.py @@ -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')) diff --git a/daily4.py b/daily4.py index 643e854..72cf602 100755 --- a/daily4.py +++ b/daily4.py @@ -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')) diff --git a/excel_lotto_records/cash25.xlsx b/excel_lotto_records/cash25.xlsx old mode 100755 new mode 100644 index 630547b..2a324b4 Binary files a/excel_lotto_records/cash25.xlsx and b/excel_lotto_records/cash25.xlsx differ diff --git a/excel_lotto_records/cash_pop.xlsx b/excel_lotto_records/cash_pop.xlsx new file mode 100644 index 0000000..f307aa7 Binary files /dev/null and b/excel_lotto_records/cash_pop.xlsx differ diff --git a/excel_lotto_records/daily3.xlsx b/excel_lotto_records/daily3.xlsx old mode 100755 new mode 100644 index 4eeba68..cece31e Binary files a/excel_lotto_records/daily3.xlsx and b/excel_lotto_records/daily3.xlsx differ diff --git a/excel_lotto_records/daily4.xlsx b/excel_lotto_records/daily4.xlsx old mode 100755 new mode 100644 index dbf7351..014679b Binary files a/excel_lotto_records/daily4.xlsx and b/excel_lotto_records/daily4.xlsx differ diff --git a/excel_lotto_records/lotto.xlsx b/excel_lotto_records/lotto.xlsx old mode 100755 new mode 100644 index 3b9a588..e23cb22 Binary files a/excel_lotto_records/lotto.xlsx and b/excel_lotto_records/lotto.xlsx differ diff --git a/excel_lotto_records/lotto_america.xlsx b/excel_lotto_records/lotto_america.xlsx old mode 100755 new mode 100644 index 4e5279a..5710a43 Binary files a/excel_lotto_records/lotto_america.xlsx and b/excel_lotto_records/lotto_america.xlsx differ diff --git a/excel_lotto_records/lotto_megamil.xlsx b/excel_lotto_records/lotto_megamil.xlsx old mode 100755 new mode 100644 index 31e5961..98ea52c Binary files a/excel_lotto_records/lotto_megamil.xlsx and b/excel_lotto_records/lotto_megamil.xlsx differ diff --git a/lotto_america.py b/lotto_america.py index 026d89b..c7c8d37 100755 --- a/lotto_america.py +++ b/lotto_america.py @@ -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')) diff --git a/lottopy_pb.py b/lottopy_pb.py index 910fddb..058f1c5 100755 --- a/lottopy_pb.py +++ b/lottopy_pb.py @@ -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')) diff --git a/megamil.py b/megamil.py index 16edf1d..0ed358e 100755 --- a/megamil.py +++ b/megamil.py @@ -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')) diff --git a/records.py b/records.py new file mode 100644 index 0000000..0584413 --- /dev/null +++ b/records.py @@ -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