|
| 1 | +{ |
| 2 | + "cells": [ |
| 3 | + { |
| 4 | + "cell_type": "code", |
| 5 | + "execution_count": 1, |
| 6 | + "metadata": {}, |
| 7 | + "outputs": [], |
| 8 | + "source": [ |
| 9 | + "# Import libraries\n", |
| 10 | + "import nba_api.stats.endpoints\n", |
| 11 | + "from nba_api.stats.endpoints import leaguegamefinder, playbyplayv2\n", |
| 12 | + "from nba_api.stats.static import teams\n", |
| 13 | + "import pandas as pd\n", |
| 14 | + "from tqdm import tqdm\n", |
| 15 | + "import time\n", |
| 16 | + "import datetime\n", |
| 17 | + "import numpy as np\n", |
| 18 | + "from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\n", |
| 19 | + "from sklearn.naive_bayes import MultinomialNB\n", |
| 20 | + "from sklearn.neighbors import KNeighborsClassifier\n", |
| 21 | + "from sklearn.cluster import KMeans\n", |
| 22 | + "from sklearn.linear_model import LinearRegression, LogisticRegression\n", |
| 23 | + "from sklearn.model_selection import train_test_split\n", |
| 24 | + "from sklearn.preprocessing import normalize, MinMaxScaler, StandardScaler\n", |
| 25 | + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", |
| 26 | + "from imblearn.over_sampling import RandomOverSampler\n", |
| 27 | + "import requests, sqlalchemy\n", |
| 28 | + "from bs4 import BeautifulSoup\n", |
| 29 | + "import itertools\n", |
| 30 | + "\n", |
| 31 | + "# connect to postgres database\n", |
| 32 | + "engine = sqlalchemy.create_engine('postgresql://postgres:password@localhost:5432/NBA')\n", |
| 33 | + "\n", |
| 34 | + "pd.set_option('display.max_rows', 500)\n", |
| 35 | + "pd.set_option('display.max_columns', 500)\n", |
| 36 | + "pd.set_option('display.width', 1000)" |
| 37 | + ] |
| 38 | + }, |
| 39 | + { |
| 40 | + "cell_type": "markdown", |
| 41 | + "metadata": {}, |
| 42 | + "source": [ |
| 43 | + "# Score difference" |
| 44 | + ] |
| 45 | + }, |
| 46 | + { |
| 47 | + "cell_type": "code", |
| 48 | + "execution_count": 3, |
| 49 | + "metadata": {}, |
| 50 | + "outputs": [], |
| 51 | + "source": [ |
| 52 | + "# read training data from database\n", |
| 53 | + "work = pd.read_sql_query(\"select * from train\", con=engine)\n", |
| 54 | + "\n", |
| 55 | + "# playoffs dummy variable\n", |
| 56 | + "work['playoff'] = work['season_id'].str.extract(r'(\\d)\\d{4}').astype(int)\n", |
| 57 | + "work['playoff'] = work['playoff'].replace(2,0)\n", |
| 58 | + "work['playoff'] = work['playoff'].replace(4,1)\n", |
| 59 | + "work['season_id'] = work['season_id'].str.replace('^\\d','2')\n", |
| 60 | + "\n", |
| 61 | + "# Get season after 1995\n", |
| 62 | + "work = work[work['season_id'] >= '21996']" |
| 63 | + ] |
| 64 | + }, |
| 65 | + { |
| 66 | + "cell_type": "code", |
| 67 | + "execution_count": 7, |
| 68 | + "metadata": {}, |
| 69 | + "outputs": [], |
| 70 | + "source": [ |
| 71 | + "# drop columns we dont need\n", |
| 72 | + "train = work.drop(columns=['team_id','team_abbreviation','game_date','matchup','min','days'])\n", |
| 73 | + "\n", |
| 74 | + "# compute difference in stats\n", |
| 75 | + "train['blk_diff'] = train['blk'] - train['blk_oppos']\n", |
| 76 | + "train['oreb_diff'] = train['oreb'] - train['oreb_oppos']\n", |
| 77 | + "train['reb_diff'] = train['reb'] - train['reb_oppos']\n", |
| 78 | + "train['ast_diff'] = train['ast'] - train['ast_oppos']\n", |
| 79 | + "train['stl_diff'] = train['stl'] - train['stl_oppos']\n", |
| 80 | + "train['tov_diff'] = train['tov'] - train['tov_oppos']\n", |
| 81 | + "train['pf_diff'] = train['pf'] - train['pf_oppos']" |
| 82 | + ] |
| 83 | + }, |
| 84 | + { |
| 85 | + "cell_type": "code", |
| 86 | + "execution_count": 8, |
| 87 | + "metadata": {}, |
| 88 | + "outputs": [], |
| 89 | + "source": [ |
| 90 | + "# read in the play-by-play data from database\n", |
| 91 | + "plays = pd.read_sql_query(\"select * from playbyplay\", con=engine)" |
| 92 | + ] |
| 93 | + }, |
| 94 | + { |
| 95 | + "cell_type": "code", |
| 96 | + "execution_count": 9, |
| 97 | + "metadata": {}, |
| 98 | + "outputs": [], |
| 99 | + "source": [ |
| 100 | + "# Cluster the play-by-play data \n", |
| 101 | + "kmeans = KMeans(6, random_state=0).fit(plays.drop(columns=['game_id']))\n", |
| 102 | + "\n", |
| 103 | + "# new feature as cluster\n", |
| 104 | + "plays['clusters'] = kmeans.labels_" |
| 105 | + ] |
| 106 | + }, |
| 107 | + { |
| 108 | + "cell_type": "code", |
| 109 | + "execution_count": 10, |
| 110 | + "metadata": {}, |
| 111 | + "outputs": [], |
| 112 | + "source": [ |
| 113 | + "# merge to training data\n", |
| 114 | + "train = train.merge(plays, left_on=['game_id'], right_on=['game_id'])" |
| 115 | + ] |
| 116 | + }, |
| 117 | + { |
| 118 | + "cell_type": "code", |
| 119 | + "execution_count": null, |
| 120 | + "metadata": {}, |
| 121 | + "outputs": [], |
| 122 | + "source": [ |
| 123 | + "# Get dummy variables\n", |
| 124 | + "final = pd.concat([\n", |
| 125 | + " pd.get_dummies(train['season_id']), \n", |
| 126 | + " pd.get_dummies(train['wl'],drop_first=True), \n", |
| 127 | + " pd.get_dummies(train['clusters'],prefix='cluster'),\n", |
| 128 | + " train.drop(columns=['awayteam','season_id','wl','hometeam','game_id'])], axis=1)\n", |
| 129 | + "\n", |
| 130 | + "# Split into train and test data\n", |
| 131 | + "tr, te = train_test_split(final,test_size=0.1,random_state=0)" |
| 132 | + ] |
| 133 | + }, |
| 134 | + { |
| 135 | + "cell_type": "markdown", |
| 136 | + "metadata": {}, |
| 137 | + "source": [ |
| 138 | + "## Model training" |
| 139 | + ] |
| 140 | + }, |
| 141 | + { |
| 142 | + "cell_type": "code", |
| 143 | + "execution_count": 13, |
| 144 | + "metadata": {}, |
| 145 | + "outputs": [], |
| 146 | + "source": [ |
| 147 | + "# Random forest\n", |
| 148 | + "rfr = RandomForestRegressor(max_depth=12, min_samples_split=64, n_jobs=-1, random_state=0)" |
| 149 | + ] |
| 150 | + }, |
| 151 | + { |
| 152 | + "cell_type": "code", |
| 153 | + "execution_count": 14, |
| 154 | + "metadata": {}, |
| 155 | + "outputs": [ |
| 156 | + { |
| 157 | + "data": { |
| 158 | + "text/plain": [ |
| 159 | + "RandomForestRegressor(max_depth=12, min_samples_split=64, n_jobs=-1,\n", |
| 160 | + " random_state=0)" |
| 161 | + ] |
| 162 | + }, |
| 163 | + "execution_count": 14, |
| 164 | + "metadata": {}, |
| 165 | + "output_type": "execute_result" |
| 166 | + } |
| 167 | + ], |
| 168 | + "source": [ |
| 169 | + "# Fit model\n", |
| 170 | + "rfr.fit(tr.drop(columns=['2diff']), tr['2diff'])" |
| 171 | + ] |
| 172 | + }, |
| 173 | + { |
| 174 | + "cell_type": "code", |
| 175 | + "execution_count": 15, |
| 176 | + "metadata": {}, |
| 177 | + "outputs": [ |
| 178 | + { |
| 179 | + "data": { |
| 180 | + "text/plain": [ |
| 181 | + "9.373045180192985" |
| 182 | + ] |
| 183 | + }, |
| 184 | + "execution_count": 15, |
| 185 | + "metadata": {}, |
| 186 | + "output_type": "execute_result" |
| 187 | + } |
| 188 | + ], |
| 189 | + "source": [ |
| 190 | + "# MAE on testing\n", |
| 191 | + "mean_absolute_error(te['2diff'],rfr.predict(te.drop(columns=['2diff'])))" |
| 192 | + ] |
| 193 | + }, |
| 194 | + { |
| 195 | + "cell_type": "code", |
| 196 | + "execution_count": 16, |
| 197 | + "metadata": {}, |
| 198 | + "outputs": [ |
| 199 | + { |
| 200 | + "data": { |
| 201 | + "text/plain": [ |
| 202 | + "8.3139611855241" |
| 203 | + ] |
| 204 | + }, |
| 205 | + "execution_count": 16, |
| 206 | + "metadata": {}, |
| 207 | + "output_type": "execute_result" |
| 208 | + } |
| 209 | + ], |
| 210 | + "source": [ |
| 211 | + "# MAE on training\n", |
| 212 | + "mean_absolute_error(tr['2diff'],rfr.predict(tr.drop(columns=['2diff'])))" |
| 213 | + ] |
| 214 | + }, |
| 215 | + { |
| 216 | + "cell_type": "code", |
| 217 | + "execution_count": 17, |
| 218 | + "metadata": {}, |
| 219 | + "outputs": [], |
| 220 | + "source": [ |
| 221 | + "# Team abbreviation conversion between our data and MSN\n", |
| 222 | + "team_dict = {'ATL': 'ATL',\n", |
| 223 | + " 'BKN': 'BKN',\n", |
| 224 | + " 'BOS': 'BOS',\n", |
| 225 | + " 'CHA': 'CHA',\n", |
| 226 | + " 'CHI': 'CHI',\n", |
| 227 | + " 'CLE': 'CLE',\n", |
| 228 | + " 'DAL': 'DAL',\n", |
| 229 | + " 'DEN': 'DEN',\n", |
| 230 | + " 'DET': 'DET',\n", |
| 231 | + " 'GS': 'GSW',\n", |
| 232 | + " 'HOU': 'HOU',\n", |
| 233 | + " 'IND': 'IND',\n", |
| 234 | + " 'LAC': 'LAC',\n", |
| 235 | + " 'LAL': 'LAL',\n", |
| 236 | + " 'MEM': 'MEM',\n", |
| 237 | + " 'MIA': 'MIA',\n", |
| 238 | + " 'MIL': 'MIL',\n", |
| 239 | + " 'MIN': 'MIN',\n", |
| 240 | + " 'NO': 'NOP',\n", |
| 241 | + " 'NY': 'NYK',\n", |
| 242 | + " 'OKC': 'OKC',\n", |
| 243 | + " 'ORL': 'ORL',\n", |
| 244 | + " 'PHI': 'PHI',\n", |
| 245 | + " 'PHO': 'PHX',\n", |
| 246 | + " 'POR': 'POR',\n", |
| 247 | + " 'SA': 'SAS',\n", |
| 248 | + " 'SAC': 'SAC',\n", |
| 249 | + " 'TOR': 'TOR',\n", |
| 250 | + " 'UTA': 'UTA',\n", |
| 251 | + " 'WAS': 'WAS'}" |
| 252 | + ] |
| 253 | + }, |
| 254 | + { |
| 255 | + "cell_type": "markdown", |
| 256 | + "metadata": {}, |
| 257 | + "source": [ |
| 258 | + "# Get game schedule tomorrrow" |
| 259 | + ] |
| 260 | + }, |
| 261 | + { |
| 262 | + "cell_type": "code", |
| 263 | + "execution_count": 18, |
| 264 | + "metadata": {}, |
| 265 | + "outputs": [], |
| 266 | + "source": [ |
| 267 | + "# webscrape from MSN\n", |
| 268 | + "headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}\n", |
| 269 | + "today = str(int(str(datetime.date.today()).replace('-','')))\n", |
| 270 | + "games_today = requests.get('https://www.msn.com/en-us/sports/nba/schedule', headers=headers)\n", |
| 271 | + "html_soup = BeautifulSoup(games_today.content, 'html.parser')" |
| 272 | + ] |
| 273 | + }, |
| 274 | + { |
| 275 | + "cell_type": "code", |
| 276 | + "execution_count": 19, |
| 277 | + "metadata": {}, |
| 278 | + "outputs": [], |
| 279 | + "source": [ |
| 280 | + "# convert date to the number of days after the first game\n", |
| 281 | + "def convert_days(date):\n", |
| 282 | + " d = pd.Timestamp(1983,10,28)\n", |
| 283 | + " return (date - d).days" |
| 284 | + ] |
| 285 | + }, |
| 286 | + { |
| 287 | + "cell_type": "code", |
| 288 | + "execution_count": 20, |
| 289 | + "metadata": {}, |
| 290 | + "outputs": [], |
| 291 | + "source": [ |
| 292 | + "# get the predictors from past data\n", |
| 293 | + "teamstoday = []\n", |
| 294 | + "page = html_soup.find_all('div',{'id':today})[0].find_all('td')\n", |
| 295 | + "for i in range (len(page)):\n", |
| 296 | + " if i % 5 == 2:\n", |
| 297 | + " teamstoday.append(page[i].text.split('\\n')[1].strip())\n", |
| 298 | + " \n", |
| 299 | + "all_games = pd.read_sql_query(\"select * from raw\", con=engine)\n", |
| 300 | + "s = \"\" # email string\n", |
| 301 | + "for i in range (0, len(teamstoday), 2):\n", |
| 302 | + " away = team_dict[teamstoday[i]]\n", |
| 303 | + " home = team_dict[teamstoday[i+1]]\n", |
| 304 | + " s += away + ',' + home + '\\n'\n", |
| 305 | + " all_games['days'] = pd.to_datetime(all_games['game_date']).apply(convert_days)\n", |
| 306 | + " all_games['hometeam'] = all_games['matchup'].str.extract(r'\\w* @ (\\w*)')\n", |
| 307 | + " thiscomp1 = all_games[(all_games['team_abbreviation'] == away) & (all_games['hometeam'] == home)].reset_index(drop=True)\n", |
| 308 | + " thiscomp2 = all_games[(all_games['team_abbreviation'] == home) & (all_games['hometeam'] == away)].reset_index(drop=True)\n", |
| 309 | + " target = pd.concat([thiscomp1, thiscomp2]).sort_values('days').iloc[-1].drop(labels=['team_id','team_name','game_date','matchup','min'])\n", |
| 310 | + " daysdiff = (pd.Timestamp.today() - pd.Timestamp(1983,10,28)).days - target['days']\n", |
| 311 | + " \n", |
| 312 | + " data = pd.Series([0]*final.shape[1], index = final.drop(columns=['2diff']).columns)\n", |
| 313 | + " data['playoff'] = 0\n", |
| 314 | + " data['22020'] = 1\n", |
| 315 | + " if target['hometeam'] == home:\n", |
| 316 | + " data['opposite'] = 0\n", |
| 317 | + " else:\n", |
| 318 | + " data['opposite'] = 1\n", |
| 319 | + "\n", |
| 320 | + " if target['wl'] == 'W':\n", |
| 321 | + " data['W'] = 1\n", |
| 322 | + " else:\n", |
| 323 | + " data['W'] = 0\n", |
| 324 | + " \n", |
| 325 | + " # compute the predictors\n", |
| 326 | + " data['1diff'] = target['pts'] - target['pts_oppos']\n", |
| 327 | + " data['daysdiff'] = daysdiff\n", |
| 328 | + " data[28:64] = target[4:-2]\n", |
| 329 | + " data[66:115] = team[(team['season'] == target['season_id']) & (team['team_abbreviation'] == target['team_abbreviation'])].drop(columns=['season_id','team_abbreviation','team_name','TEAM_ID','TEAM_NAME','GP','W','L','CFID','CFPARAMS','season']).iloc[0]\n", |
| 330 | + " data[115:-7] = team[(team['season'] == target['season_id']) & (team['team_abbreviation'] == target['hometeam'])].drop(columns=['season_id','team_abbreviation','team_name','TEAM_ID','TEAM_NAME','GP','W','L','CFID','CFPARAMS','season']).iloc[0]\n", |
| 331 | + " data['blk_diff'] = data['blk'] - data['blk_oppos']\n", |
| 332 | + " data['oreb_diff'] = data['oreb'] - data['oreb_oppos']\n", |
| 333 | + " data['reb_diff'] = data['reb'] - data['reb_oppos']\n", |
| 334 | + " data['ast_diff'] = data['ast'] - data['ast_oppos']\n", |
| 335 | + " data['stl_diff'] = data['stl'] - data['stl_oppos']\n", |
| 336 | + " data['tov_diff'] = data['tov'] - data['tov_oppos']\n", |
| 337 | + " data['pf_diff'] = data['pf'] - data['pf_oppos']\n", |
| 338 | + " \n", |
| 339 | + " # prediction\n", |
| 340 | + " s += str(rfr.predict(data.values.reshape(1,-1))) + '\\n' # email string" |
| 341 | + ] |
| 342 | + }, |
| 343 | + { |
| 344 | + "cell_type": "markdown", |
| 345 | + "metadata": {}, |
| 346 | + "source": [ |
| 347 | + "## Over/Under" |
| 348 | + ] |
| 349 | + }, |
| 350 | + { |
| 351 | + "cell_type": "code", |
| 352 | + "execution_count": 21, |
| 353 | + "metadata": {}, |
| 354 | + "outputs": [], |
| 355 | + "source": [ |
| 356 | + "# Read in data training data from database\n", |
| 357 | + "work = pd.read_sql_query(\"select * from train_total\", con=engine)\n", |
| 358 | + "\n", |
| 359 | + "# playoffs indicator\n", |
| 360 | + "work['playoff'] = work['season_id'].str.extract(r'(\\d)\\d{4}').astype(int)\n", |
| 361 | + "work['playoff'] = work['playoff'].replace(2,0)\n", |
| 362 | + "work['playoff'] = work['playoff'].replace(4,1)\n", |
| 363 | + "\n", |
| 364 | + "# Get season after 1995\n", |
| 365 | + "work['season_id'] = work['season_id'].str.replace('^\\d','2')\n", |
| 366 | + "work = work[work['season_id'] >= '21996']\n", |
| 367 | + "\n", |
| 368 | + "# drop columns we dont need\n", |
| 369 | + "train = work.drop(columns=['team_id','team_abbreviation','game_date','matchup','min','days'])\n", |
| 370 | + "\n", |
| 371 | + "# compute stat difference\n", |
| 372 | + "train['blk_diff'] = train['blk'] - train['blk_oppos']\n", |
| 373 | + "train['oreb_diff'] = train['oreb'] - train['oreb_oppos']\n", |
| 374 | + "train['reb_diff'] = train['reb'] - train['reb_oppos']\n", |
| 375 | + "train['ast_diff'] = train['ast'] - train['ast_oppos']\n", |
| 376 | + "train['stl_diff'] = train['stl'] - train['stl_oppos']\n", |
| 377 | + "train['tov_diff'] = train['tov'] - train['tov_oppos']\n", |
| 378 | + "train['pf_diff'] = train['pf'] - train['pf_oppos']" |
| 379 | + ] |
| 380 | + }, |
| 381 | + { |
| 382 | + "cell_type": "code", |
| 383 | + "execution_count": 22, |
| 384 | + "metadata": {}, |
| 385 | + "outputs": [], |
| 386 | + "source": [ |
| 387 | + "# dummy variables\n", |
| 388 | + "final = pd.concat([\n", |
| 389 | + " pd.get_dummies(train['season_id']), \n", |
| 390 | + " pd.get_dummies(train['wl'],drop_first=True), \n", |
| 391 | + " train.drop(columns=['awayteam','season_id','wl','hometeam','game_id'])], axis=1)\n", |
| 392 | + "\n", |
| 393 | + "# split into train and test dataset\n", |
| 394 | + "tr, te = train_test_split(final,test_size=0.1,random_state=0)" |
| 395 | + ] |
| 396 | + }, |
| 397 | + { |
| 398 | + "cell_type": "markdown", |
| 399 | + "metadata": {}, |
| 400 | + "source": [ |
| 401 | + "# Model training" |
| 402 | + ] |
| 403 | + }, |
| 404 | + { |
| 405 | + "cell_type": "code", |
| 406 | + "execution_count": 23, |
| 407 | + "metadata": {}, |
| 408 | + "outputs": [], |
| 409 | + "source": [ |
| 410 | + "# random forest\n", |
| 411 | + "rfr = RandomForestRegressor(max_depth=12, min_samples_split=64, n_jobs=-1, random_state=0)" |
| 412 | + ] |
| 413 | + }, |
| 414 | + { |
| 415 | + "cell_type": "code", |
| 416 | + "execution_count": 24, |
| 417 | + "metadata": {}, |
| 418 | + "outputs": [ |
| 419 | + { |
| 420 | + "data": { |
| 421 | + "text/plain": [ |
| 422 | + "RandomForestRegressor(max_depth=12, min_samples_split=64, n_jobs=-1,\n", |
| 423 | + " random_state=0)" |
| 424 | + ] |
| 425 | + }, |
| 426 | + "execution_count": 24, |
| 427 | + "metadata": {}, |
| 428 | + "output_type": "execute_result" |
| 429 | + } |
| 430 | + ], |
| 431 | + "source": [ |
| 432 | + "# fit the model\n", |
| 433 | + "rfr.fit(tr.drop(columns=['2diff']), tr['2diff'])" |
| 434 | + ] |
| 435 | + }, |
| 436 | + { |
| 437 | + "cell_type": "code", |
| 438 | + "execution_count": 25, |
| 439 | + "metadata": {}, |
| 440 | + "outputs": [ |
| 441 | + { |
| 442 | + "data": { |
| 443 | + "text/plain": [ |
| 444 | + "14.881988864855604" |
| 445 | + ] |
| 446 | + }, |
| 447 | + "execution_count": 25, |
| 448 | + "metadata": {}, |
| 449 | + "output_type": "execute_result" |
| 450 | + } |
| 451 | + ], |
| 452 | + "source": [ |
| 453 | + "# MAE for testing\n", |
| 454 | + "mean_absolute_error(te['2diff'],rfr.predict(te.drop(columns=['2diff'])))" |
| 455 | + ] |
| 456 | + }, |
| 457 | + { |
| 458 | + "cell_type": "code", |
| 459 | + "execution_count": 26, |
| 460 | + "metadata": {}, |
| 461 | + "outputs": [ |
| 462 | + { |
| 463 | + "data": { |
| 464 | + "text/plain": [ |
| 465 | + "13.022569548413044" |
| 466 | + ] |
| 467 | + }, |
| 468 | + "execution_count": 26, |
| 469 | + "metadata": {}, |
| 470 | + "output_type": "execute_result" |
| 471 | + } |
| 472 | + ], |
| 473 | + "source": [ |
| 474 | + "# MAE for training\n", |
| 475 | + "mean_absolute_error(tr['2diff'],rfr.predict(tr.drop(columns=['2diff'])))" |
| 476 | + ] |
| 477 | + }, |
| 478 | + { |
| 479 | + "cell_type": "markdown", |
| 480 | + "metadata": {}, |
| 481 | + "source": [ |
| 482 | + "## Get game schedule tomorrow" |
| 483 | + ] |
| 484 | + }, |
| 485 | + { |
| 486 | + "cell_type": "code", |
| 487 | + "execution_count": 27, |
| 488 | + "metadata": {}, |
| 489 | + "outputs": [], |
| 490 | + "source": [ |
| 491 | + "# webscrape from MSN\n", |
| 492 | + "teamstoday = []\n", |
| 493 | + "page = html_soup.find_all('div',{'id':today})[0].find_all('td')\n", |
| 494 | + "for i in range (len(page)):\n", |
| 495 | + " if i % 5 == 2:\n", |
| 496 | + " teamstoday.append(page[i].text.split('\\n')[1].strip())\n", |
| 497 | + "\n", |
| 498 | + "# get raw data from database\n", |
| 499 | + "all_games = pd.read_sql_query(\"select * from raw\", con=engine)\n", |
| 500 | + "\n", |
| 501 | + "# get predictors from past data\n", |
| 502 | + "for i in range (0, len(teamstoday), 2):\n", |
| 503 | + " away = team_dict[teamstoday[i]]\n", |
| 504 | + " home = team_dict[teamstoday[i+1]]\n", |
| 505 | + " s += away + ',' + home + '\\n' # email string\n", |
| 506 | + " all_games['days'] = pd.to_datetime(all_games['game_date']).apply(convert_days)\n", |
| 507 | + " all_games['hometeam'] = all_games['matchup'].str.extract(r'\\w* @ (\\w*)')\n", |
| 508 | + " thiscomp1 = all_games[(all_games['team_abbreviation'] == away) & (all_games['hometeam'] == home)].reset_index(drop=True)\n", |
| 509 | + " thiscomp2 = all_games[(all_games['team_abbreviation'] == home) & (all_games['hometeam'] == away)].reset_index(drop=True)\n", |
| 510 | + " target = pd.concat([thiscomp1, thiscomp2]).sort_values('days').iloc[-1].drop(labels=['team_id','team_name','game_date','matchup','min'])\n", |
| 511 | + " daysdiff = (pd.Timestamp.today() - pd.Timestamp(1983,10,28)).days - target['days']\n", |
| 512 | + " \n", |
| 513 | + " data = pd.Series([0]*final.shape[1], index = final.drop(columns=['2diff']).columns)\n", |
| 514 | + " data['playoff'] = 0\n", |
| 515 | + " data['22020'] = 1\n", |
| 516 | + " if target['hometeam'] == home:\n", |
| 517 | + " data['opposite'] = 0\n", |
| 518 | + " else:\n", |
| 519 | + " data['opposite'] = 1\n", |
| 520 | + "\n", |
| 521 | + " if target['wl'] == 'W':\n", |
| 522 | + " data['W'] = 1\n", |
| 523 | + " else:\n", |
| 524 | + " data['W'] = 0\n", |
| 525 | + " \n", |
| 526 | + " # compute the predictors\n", |
| 527 | + " data['1diff'] = target['pts'] - target['pts_oppos']\n", |
| 528 | + " data['daysdiff'] = daysdiff\n", |
| 529 | + " data[28:64] = target[4:-2]\n", |
| 530 | + " data[66:115] = team[(team['season'] == target['season_id']) & (team['team_abbreviation'] == target['team_abbreviation'])].drop(columns=['season_id','team_abbreviation','team_name','TEAM_ID','TEAM_NAME','GP','W','L','CFID','CFPARAMS','season']).iloc[0]\n", |
| 531 | + " data[115:-7] = team[(team['season'] == target['season_id']) & (team['team_abbreviation'] == target['hometeam'])].drop(columns=['season_id','team_abbreviation','team_name','TEAM_ID','TEAM_NAME','GP','W','L','CFID','CFPARAMS','season']).iloc[0]\n", |
| 532 | + " data['blk_diff'] = data['blk'] - data['blk_oppos']\n", |
| 533 | + " data['oreb_diff'] = data['oreb'] - data['oreb_oppos']\n", |
| 534 | + " data['reb_diff'] = data['reb'] - data['reb_oppos']\n", |
| 535 | + " data['ast_diff'] = data['ast'] - data['ast_oppos']\n", |
| 536 | + " data['stl_diff'] = data['stl'] - data['stl_oppos']\n", |
| 537 | + " data['tov_diff'] = data['tov'] - data['tov_oppos']\n", |
| 538 | + " data['pf_diff'] = data['pf'] - data['pf_oppos']\n", |
| 539 | + " \n", |
| 540 | + " # prediction\n", |
| 541 | + " s += str(rfr.predict(data.values.reshape(1,-1))) + '\\n' # email string" |
| 542 | + ] |
| 543 | + }, |
| 544 | + { |
| 545 | + "cell_type": "markdown", |
| 546 | + "metadata": {}, |
| 547 | + "source": [ |
| 548 | + "# Email the predictions" |
| 549 | + ] |
| 550 | + }, |
| 551 | + { |
| 552 | + "cell_type": "code", |
| 553 | + "execution_count": 29, |
| 554 | + "metadata": {}, |
| 555 | + "outputs": [], |
| 556 | + "source": [ |
| 557 | + "import smtplib, ssl\n", |
| 558 | + "\n", |
| 559 | + "port = 465 # For SSL\n", |
| 560 | + "smtp_server = \"smtp.gmail.com\"\n", |
| 561 | + "sender_email = \"leowei08@gmail.com\"\n", |
| 562 | + "receiver_email1 = \"leowei08@gmail.com\" \n", |
| 563 | + "password = 'password'\n", |
| 564 | + "message = \"\"\"\\\n", |
| 565 | + "Subject: Predictions Today {today}\n", |
| 566 | + "\n", |
| 567 | + "\n", |
| 568 | + "{content}.\"\"\"\n", |
| 569 | + "\n", |
| 570 | + "context = ssl.create_default_context()\n", |
| 571 | + "with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:\n", |
| 572 | + " server.login(sender_email, password)\n", |
| 573 | + " server.sendmail(sender_email, receiver_email1, message.format(today=str(datetime.date.today()).replace('-',''), content=s))" |
| 574 | + ] |
| 575 | + } |
| 576 | + ], |
| 577 | + "metadata": { |
| 578 | + "kernelspec": { |
| 579 | + "display_name": "Python 3", |
| 580 | + "language": "python", |
| 581 | + "name": "python3" |
| 582 | + }, |
| 583 | + "language_info": { |
| 584 | + "codemirror_mode": { |
| 585 | + "name": "ipython", |
| 586 | + "version": 3 |
| 587 | + }, |
| 588 | + "file_extension": ".py", |
| 589 | + "mimetype": "text/x-python", |
| 590 | + "name": "python", |
| 591 | + "nbconvert_exporter": "python", |
| 592 | + "pygments_lexer": "ipython3", |
| 593 | + "version": "3.7.11" |
| 594 | + } |
| 595 | + }, |
| 596 | + "nbformat": 4, |
| 597 | + "nbformat_minor": 4 |
| 598 | +} |
0 commit comments