Compare commits

..

6 commits

6 changed files with 221 additions and 24 deletions

2
.gitignore vendored
View file

@ -1,3 +1,5 @@
__pycache__
.venv
.env
*.csv
credentials.json

53
app.py
View file

@ -2,6 +2,9 @@ from argparse import ArgumentParser
from config import Config as cfg
from datetime import datetime
from espn_api.football import League
from gspread_dataframe import set_with_dataframe
from service import gc
from tabulate import tabulate
from time import strftime
import pandas as pd
@ -23,29 +26,37 @@ def extract_positional_data(lineup: list, position: str) -> int:
return response
def extract_matchup_box_scores(league: League, week_override: int) -> dict:
matchups = league.box_scores(week=week_override)
def extract_matchup_box_scores(league: League) -> dict:
result = []
for week in range(1, league.current_week + 1):
matchups = league.box_scores(week=week)
for matchup in matchups:
result.append({
'Away Team': matchup.away_team.team_name,
'Away Team Score': matchup.away_score,
'Away Team Kicker Score': extract_positional_data(matchup.away_lineup, 'K'),
'Away Team Bench Score': extract_positional_data(matchup.away_lineup, 'BE'),
'Home Team': matchup.home_team.team_name,
'Home Team Score': matchup.home_score,
'Home Team Kicker Score': extract_positional_data(matchup.home_lineup, 'K'),
'Home Team Bench Score': extract_positional_data(matchup.home_lineup, 'BE')
'WEEK #': week,
'AWAY TEAM': matchup.away_team.team_name,
'AWAY TEAM SCORE': matchup.away_score,
'AWAY TEAM KICKER': extract_positional_data(matchup.away_lineup, 'K'),
'AWAY TEAM BENCH': extract_positional_data(matchup.away_lineup, 'BE'),
'HOME TEAM': matchup.home_team.team_name,
'HOME TEAM SCORE': matchup.home_score,
'HOME TEAM KICKER': extract_positional_data(matchup.home_lineup, 'K'),
'HOME TEAM BENCH': extract_positional_data(matchup.home_lineup, 'BE')
})
return result
def write_to_google_spreadsheet(df: pd.DataFrame):
spreadsheet = gc.open_by_key(cfg.SPREADSHEET_ID)
worksheet = spreadsheet.worksheet("FantasyData")
set_with_dataframe(worksheet, df)
if __name__ == "__main__":
parser = ArgumentParser(description='Weekly Report Generator for Fantasy Football')
parser.add_argument('-wo','--weekly-override', help='Numeric value that overrides which fantasy week to generate data from', required=False)
parser.add_argument('-csv', action='store_true')
parser.add_argument('-gs', action='store_true')
args = vars(parser.parse_args())
timestamp = strftime("%Y%m%d_%H%M%S")
weekly_value = args['weekly_override']
league = League(league_id=cfg.LEAGUE_ID,
year=datetime.now().year,
@ -53,12 +64,14 @@ if __name__ == "__main__":
swid=cfg.SWID,
fetch_league=cfg.FETCH_LEAGUE)
if check_int(weekly_value):
print(f"Override applied, using week {weekly_value}")
else:
weekly_value = league.current_week
print(f'Using current week: {weekly_value}')
matchup = extract_matchup_box_scores(league=league, week_override=int(weekly_value))
matchup = extract_matchup_box_scores(league=league)
df = pd.DataFrame.from_dict(matchup)
df.to_csv(f'espn_fantasy_football_week_{weekly_value}_{timestamp}.csv', index=False, float_format='%.2f')
print(tabulate(df, headers='keys', tablefmt='psql', showindex=False))
if args['csv']:
print("Saving to CSV...")
df.to_csv(f'espn_fantasy_football_weekly_report_{timestamp}.csv', index=False, float_format='%.2f')
if args['gs']:
print("Saving to Google Sheets...")
write_to_google_spreadsheet(df=df)

View file

@ -14,6 +14,8 @@ class Config():
LEAGUE_ID = getenv("LEAGUE_ID")
SWID = getenv("SWID")
FETCH_LEAGUE = str2bool(getenv("FETCH_LEAGUE"))
SPREADSHEET_ID = getenv("SPREADSHEET_ID")
WORKSHEET_NAME = getenv("WORKSHEET_NAME")
cfg = Config()

View file

@ -1,3 +1,7 @@
-e git+https://github.com/cwendt94/espn-api@8e131e7ccaa843abac539948c44f9d45bfcee764#egg=espn_api
google-auth-oauthlib==1.2.1
gspread==6.1.2
gspread-dataframe==4.0.0
pandas==2.2.3
python-dotenv==1.0.1
tabulate==0.9.0

4
service.py Normal file
View file

@ -0,0 +1,4 @@
import gspread
gc = gspread.service_account(filename='credentials.json')

172
wip.ipynb Normal file
View file

@ -0,0 +1,172 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [],
"source": [
"from argparse import ArgumentParser\n",
"from config import Config as cfg\n",
"from datetime import datetime\n",
"from espn_api.football import League\n",
"from gspread_dataframe import get_as_dataframe, set_with_dataframe\n",
"from service import gc\n",
"from time import strftime\n",
"\n",
"import pandas as pd\n",
"\n",
"\n",
"def check_int(s):\n",
" if s is None:\n",
" return s\n",
" if s[0] in ('-', '+'):\n",
" return s[1:].isdigit()\n",
" return s.isdigit()\n",
"\n",
"\n",
"def extract_positional_data(lineup: list, position: str) -> int:\n",
" response = 0\n",
" for player in lineup:\n",
" if player.lineupSlot == position:\n",
" response = response + player.points\n",
" return response\n",
"\n",
"\n",
"def extract_matchup_box_scores(league: League) -> dict:\n",
" result = []\n",
" for week in range(1, league.current_week + 1):\n",
" matchups = league.box_scores(week=week)\n",
" for matchup in matchups:\n",
" result.append({\n",
" 'WEEK #': week,\n",
" 'AWAY TEAM': matchup.away_team.team_name,\n",
" 'AWAY TEAM SCORE': matchup.away_score,\n",
" 'AWAY TEAM KICKER': extract_positional_data(matchup.away_lineup, 'K'),\n",
" 'AWAY TEAM BENCH': extract_positional_data(matchup.away_lineup, 'BE'),\n",
" 'HOME TEAM': matchup.home_team.team_name,\n",
" 'HOME TEAM SCORE': matchup.home_score,\n",
" 'HOME TEAM KICKER': extract_positional_data(matchup.home_lineup, 'K'),\n",
" 'HOME TEAM BENCH': extract_positional_data(matchup.home_lineup, 'BE')\n",
" })\n",
" return result\n",
"\n",
"\n",
"def write_to_google_spreadsheet(df: pd.DataFrame):\n",
" spreadsheet = gc.open_by_key(cfg.SPREADSHEET_ID)\n",
" worksheet = spreadsheet.worksheet(\"FantasyData\")\n",
" set_with_dataframe(worksheet, df)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"league = League(league_id=cfg.LEAGUE_ID, \n",
" year=datetime.now().year, \n",
" espn_s2=cfg.ESPN_S2, \n",
" swid=cfg.SWID, \n",
" fetch_league=cfg.FETCH_LEAGUE)"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [],
"source": [
"matchup = extract_matchup_box_scores(league=league)"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"df = pd.DataFrame.from_dict(matchup) "
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"#spreadsheet = gc.open_by_key(cfg.SPREADSHEET_ID)\n",
"spreadsheet = gc.open_by_key('1vBtceabKqc0QAs7MOgeg-q0FSHXIbNf31B8XEgzy6s8')"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"worksheet = spreadsheet.worksheet(\"FantasyData\")"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
"set_with_dataframe(worksheet, df)"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [],
"source": [
"def next_available_row(worksheet):\n",
" str_list = list(filter(None, worksheet.col_values(1)))\n",
" return str(len(str_list)+1)"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'7'"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"next_available_row(worksheet=worksheet)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 2
}