Esempio n. 1
0
    def _pushData(self, prediction):
        with DOConnect() as tunnel:
            c, conn = connection(tunnel)
            try:
                c.execute('''delete from modelData.modelResults
                            where modelYear = %d and modelWeek = %d
                            and modelPlayerPosition = '%s' ''' %
                          (self.season, self.week, self.position))
            except Exception as e:
                print(str(e))
            try:
                query = '''insert into modelData.modelResults values '''
                for i, row in prediction.iterrows():
                    query += (
                        "(%d, %d, %d, '%s', '%s', %s, %s, current_timestamp()),"
                        %
                        (self.season, self.week, row.playerId, row.Name,
                         self.position, str(row.prediction), str(row.predVar)))

                query = query[:-1]
            except Exception as e:
                print(str(e))
            try:
                c.execute(query)
            except Exception as e:
                print(str(e))
            conn.commit()

            conn.close()
def buildWeeklyModels(season, week):
    with DOConnect() as tunnel:
        c, conn = connection(tunnel)
        c.execute(
            "delete from leagueSims.modelPredictions where modelSeason = %d and predictionWeek = %d"
            % (season, week))
        conn.commit()
        conn.close()

        for pos in ['DST', 'K', 'QB', 'RB', 'WR', 'TE']:
            print(str(season) + "-" + str(week) + "-" + pos)
            c, conn = connection(tunnel)
            modelData = meth.pullModelData(season, week, pos, conn)
            conn.close()

            trainIndex = ((modelData.predictionSeason < season) &
                          (modelData.predictionWeek == week))

            predictIndex = ((modelData.predictionSeason == season) &
                            (modelData.predictionWeek == week))

            treeCount = 200

            try:
                leagueModel = leaguePredictionTree(modelData[trainIndex],
                                                   treeCount)
                predResults = leagueModel.returnSimsModels(
                    modelData[predictIndex])
            except:
                traceback.print_exc()

            c, conn = connection(tunnel)
            sqlInsert = "insert into leagueSims.modelPredictions values "
            for i, row in predResults.iterrows():
                sqlAdd = "(%d, %d, %d, %d, '%s', %f, '%s', %f),"

                sqlInsert += sqlAdd % (row['modelSeason'],
                                       row['predictedWeek'],
                                       row['predictionWeek'], row['playerId'],
                                       pos, row['modelPrediction'],
                                       row['predRange'], row['modelPlayProb'])
            try:
                c.execute(sqlInsert[:-1])
                conn.commit()
            except Exception as e:
                print(str(e))
            conn.close()
            print('end')

            del predResults
            del leagueModel
            del sqlInsert
            del modelData
Esempio n. 3
0
    def _pullData(self, position):
        with DOConnect() as tunnel:
            c, conn = connection(tunnel)
            if position == 'DST':
                query = '''select * from modelData.%sData
                where playerSeason >= 2014''' % position.lower()
            else:
                query = '''select * from modelData.%sData
                where chartPosition is not null and playerRating is not null and age is not null and experience is not null
                and playerSeason >= 2014''' % position.lower()

            table = pd.read_sql(query, con=conn)

            conn.close()

            return table
Esempio n. 4
0
import sys
sys.path.insert(0, '..')
sys.path.insert(0, '..\..')

from DOConn import connection
from DOsshTunnel import DOConnect
from references import errorSQL

week = 1
year = 2018

with DOConnect() as tunnel:
    c, conn = connection(tunnel)

    conn.close()
Esempio n. 5
0
def runSims(season, week, runCount=50):
    while True:
        print(season, week)
        with DOConnect() as tunnel:
            c, conn = connection(tunnel)
            c.execute('''select standRunCount
                         from leagueSims.standings
                         where standYear = %d
                         and standWeek = %d''' % (season, week))
            result = c.fetchone()
            if result is None:
                None
            elif result[0] >= 5000:
                conn.close()
                break

            try:
                results = meth.pullResults(season, week, conn)
            except Exception as e:
                print(str(e))

            try:
                currentRosters = meth.pullCurrentRosters(season, week, conn)
                currentRosters['predictionDistr'] = currentRosters.apply(
                    lambda x: x['predictionDistr'].split(','), axis=1)
                positions = [{
                    'key': 'QB',
                    'allow': ['QB']
                }, {
                    'key': 'RB',
                    'allow': ['RB']
                }, {
                    'key': 'WR',
                    'allow': ['WR']
                }, {
                    'key': 'TE',
                    'allow': ['TE']
                }, {
                    'key': 'D/ST',
                    'allow': ['D/ST']
                }, {
                    'key': 'K',
                    'allow': ['K']
                }, {
                    'key': 'RBWR',
                    'allow': ['RB', 'WR']
                }, {
                    'key': 'Flex',
                    'allow': ['RB', 'WR', 'TE']
                }]

                rostersDict = {}
                for weekNum in currentRosters['predictedWeek'].dropna().unique(
                ):
                    for team in currentRosters['playerTeam'].unique():
                        rostersDict[team + "-" + str(int(weekNum))] = {}
                        rostersDict[team + "-" + str(
                            int(weekNum))]['totalRoster'] = currentRosters.loc[
                                (currentRosters['playerTeam'] == team) &
                                (currentRosters['predictedWeek'] == weekNum), [
                                    'playerId', 'playerPosition',
                                    'predictionValue', 'predictionDistr',
                                    'playProb'
                                ]]
                        rostersDict[team + "-" + str(
                            int(weekNum))]['totalRoster']['randNum'] = None
            except Exception as e:
                traceback.print_exc()

            try:
                replaceValues = meth.pullReplacementNumbers(season, week, conn)
                replaceValues['replaceDistr'] = replaceValues.apply(lambda x: [
                    float(y) if y != '' else 0
                    for y in x['replaceDistr'].split(',')
                ],
                                                                    axis=1)
                replaceDict = {}
                for replaceWeek in replaceValues['predictedWeek'].unique():
                    replaceDict[replaceWeek] = replaceValues[
                        replaceValues['predictedWeek'] ==
                        replaceWeek].set_index('playerPosition').to_dict(
                            orient='index')
            except Exception as e:
                traceback.print_exc()

            conn.close()

        print('start sims')
        start = time.process_time()
        sim = leagueSimulation(season, rostersDict, replaceDict, results, week)
        status = True
        fails = 0
        try:
            sim.simSeason()
        except Exception as e:
            fails += 1
            traceback.print_exc()

        results = sim.leagueResults()
        resultsTable = results.copy()
        table2 = pd.DataFrame(
            data={
                'Names': resultsTable.index,
                'Points': None,
                'Wins': None,
                'Losses': None,
                'HighPoints': None
            })
        table2['Points'] = [[round(x, 2)] for x in results['winPoints']]
        table2['Wins'] = [[x] for x in results['winWin']]
        table2['Losses'] = [[x] for x in results['winLoss']]
        table2['HighPoints'] = [[x] for x in results['weeklyHighPoints']]
        print(time.process_time() - start)
        for i in range(1, runCount):
            start = time.process_time()
            status = True
            try:
                sim.simSeason()
                status = False
            except Exception as e:
                fails += 1
                with DOConnect() as tunnel:
                    c, conn = connection(tunnel)
                    c.execute(
                        '''insert into leagueSims.simErrors
                                  values (%d, %d, %d, %d, '%s', current_timestamp());'''
                        % (season, week, fails, i, str(e).replace("'", "\'")))
                    conn.commit()
                    conn.close()

            results = sim.leagueResults()
            resultsTable = resultsTable.add(results, fill_value=0)
            table2['Points'] = table2.apply(lambda x: x['Points'] + [
                round(
                    results.loc[results.index == x['Names']].iloc[0][
                        'winPoints'], 2)
            ],
                                            axis=1)
            table2['Wins'] = table2.apply(
                lambda x: x['Wins'] +
                [results.loc[results.index == x['Names']].iloc[0]['winWin']],
                axis=1)
            table2['Losses'] = table2.apply(
                lambda x: x['Losses'] +
                [results.loc[results.index == x['Names']].iloc[0]['winLoss']],
                axis=1)
            table2['HighPoints'] = table2.apply(lambda x: x['HighPoints'] + [
                results.loc[results.index == x['Names']].iloc[0][
                    'weeklyHighPoints']
            ],
                                                axis=1)
            print(time.process_time() - start)

        sqlStatement = '''insert into leagueSims.standings values %s
                        on duplicate key update
                        standRunCount = standRunCount + values(StandRunCount),
                        standWins = standWins + values(standWins),
                        standWinsArray = concat(standWinsArray,',',values(standWinsArray)),
                        standLosses = standLosses + values(standLosses),
                        standLossesArray = concat(standLossesArray,',',values(standLossesArray)),
                        standPoints = standPoints + values(standPoints),
                        standPointsArray = concat(standPointsArray,',',values(standPointsArray)),
                        standPointsRemain = standPointsRemain + values(standPointsRemain),
                        standPlayoffs = standPlayoffs + values(standPlayoffs),
                        standChamp = standChamp + values(standChamp),
                        standHighPoints = standHighPoints + values(standHighPoints),
                        standLowPoints = standLowPoints + values(standLowPoints),
                        standFirstPlace = standFirstPlace + values(standFirstPlace),
                        standThirdPlace = standThirdPlace + values(standThirdPlace),
                        standBye = standBye + values(standBye),
                        standWeeklyHighPoints = standWeeklyHighPoints + values(standWeeklyHighPoints),
                        standWeeklyHighPointsArray = concat(standWeeklyHighPointsArray,',',values(standWeeklyHighPointsArray)),
                        updateTime = current_timestamp();


                    '''

        sqlAdd = ''
        for i, row in resultsTable.iterrows():
            sqlAdd += (
                '''(%d,%d,%d,'%s',%d,'%s',%d,'%s',%f,
                            '%s',%f, %d,%d,%d,%d,%d,%d,%d,%d,%d,'%s',current_timestamp()),'''
                % (season, week, runCount, row.name, row['winWin'], ','.join([
                    str(int(x))
                    for x in table2.loc[table2['Names'] == i].iloc[0]['Wins']
                ]), row['winLoss'], ','.join([
                    str(int(x))
                    for x in table2.loc[table2['Names'] == i].iloc[0]['Losses']
                ]), round(row['winPoints'], 2), ','.join([
                    str(round(x, 1))
                    for x in table2.loc[table2['Names'] == i].iloc[0]['Points']
                ]), round(row['winPointsRemain'], 2), row['playoffs'],
                   row['champ'], row['runnerup'], row['thirdPlace'],
                   row['highPoints'], row['lowPoints'], row['firstPlace'],
                   row['bye'], row['weeklyHighPoints'], ','.join([
                       str(int(x)) for x in table2.loc[table2['Names'] ==
                                                       i].iloc[0]['HighPoints']
                   ])))

        with DOConnect() as tunnel:
            c, conn = connection(tunnel)
            try:
                c.execute(sqlStatement % sqlAdd[:-1])
            except:
                traceback.print_exc()

            conn.commit()
            conn.close()
Esempio n. 6
0
def runWeeklyData(weekVariable):
    with DOConnect() as tunnel:
        c, conn = connection(tunnel)
        weekRun = weekVariable

        data = pd.read_sql("""select avg(a.winPoints)
     as donePoints, 
     avg(weightPoints) as weightPoints,
     avg(ifnull(preDraftCapital,(select avg(preDraftCapital) from analysis.preDraftCapital))) as preDraftCapital,
     avg(b.winPoints) as predictPoints, lcase(ifnull(a.winTeam,preDraftTeam)) as winTeam, 
     ifnull(a.winSeason,preDraftYear) as winSeason,
     max(a.winWeek) as maxWeek
     from analysis.preDraftCapital
    left join (select winSeason, winTeam, avg(winPoints) as winPoints, max(winWeek) as winWeek,
    sum(winPoints*(1-.05*((select max(winWeek) from la_liga_data.wins where winSeason = 2018 and winWeek <= replaceVar and winWeek <= 13)-winWeek)))/
    sum((1-.05*((select max(winWeek) from la_liga_data.wins where winSeason = 2018 and winWeek <= replaceVar and winWeek <= 13)-winWeek))) as weightPoints
    from la_liga_data.wins
    where winWeek <= (select max(winWeek) from la_liga_data.wins where winSeason = 2018 and winWeek <= replaceVar and winWeek <= 13)
    group by 1,2) a on a.winSeason = preDraftYear and a.winTeam = preDraftTeam
    left join la_liga_data.wins b on  ifnull(a.winSeason,preDraftYear) = b.winSeason and b.winWeek > ifnull(a.winWeek,0) and ifnull(a.winTeam,preDraftTeam) = b.winTeam
            and b.winWeek <= 13
    group by winTeam, winSeason""".replace('replaceVar', str(weekRun)),
                           con=conn)

        matchups = pd.read_sql(
            """select matchYear, lcase(matchTeam) as matchTeam,
        group_concat(lcase(matchOpp) order by matchWeek asc) as matchOpp from la_liga_data.matchups
        group by 1,2;""",
            con=conn)

        standings = pd.read_sql(
            """select lcase(winTeam) as winTeam, ifnull(count(distinct(winWeek)),0) as weekNumber,
                sum(winWin) as win,
                sum(winLoss) as loss,
                sum(winTie) as ties,
                sum(winPoints) as points,
                count(
                                    case when winPoints = 
                    (select max(winPoints) from la_liga_data.wins a 
                     where a.winSeason = b.winSeason and a.winWeek = b.winWeek)
                                    then 1 end) as highPoints
                from la_liga_data.wins b
                where winSeason = 2018 and winWeek <= %d
                group by 1""" % weekRun,
            con=conn)

        pointTotals = pd.read_sql(
            """select winPoints from la_liga_data.wins where winWeek <= 13""",
            con=conn)

        pointAverages = pd.read_sql(
            """select winSeason, winTeam, avg(winPoints) as avgPoints
                from la_liga_data.wins where winWeek <= 13 group by 1,2""",
            con=conn)
        data2 = data.loc[data['winSeason'] <= 2017]

        pointsMean = np.mean(pointTotals['winPoints'])
        pointsSd = np.std(pointTotals['winPoints'])

        randseasonMean = np.mean(pointAverages['avgPoints'])
        randseasonSd = np.std(pointAverages['avgPoints'])
        if weekRun == 0:
            weekStart = weekRun
        else:
            weekStart = standings.iloc[0]['weekNumber'].item()
        models = ['recentPoints', 'coin', 'draft', 'points', 'all']

        def randModel(preDraftCap, pointsAvg, weightPoints):
            result = (np.random.normal(randseasonMean, randseasonSd, 1))

            return result

        def draftModel(preDraftCap, pointsAvg, weightPoints):
            result = (
                np.random.normal(coefs['const'], se['const'], 1) +
                (np.random.normal(coefs['preDraftCapital'],
                                  se['preDraftCapital'], 1)) * preDraftCap)
            return result

        def pointsModel(preDraftCap, pointsAvg, weightPoints):
            result = (
                np.random.normal(coefs['const'], se['const'], 1) +
                (np.random.normal(coefs['donePoints'], se['donePoints'], 1)) *
                pointsAvg)
            return result

        def recentPointsModel(preDraftCap, pointsAvg, weightPoints):
            result = (np.random.normal(coefs['const'], se['const'], 1) +
                      (np.random.normal(coefs['weightPoints'],
                                        se['weightPoints'], 1)) * weightPoints)
            return result

        def allModel(preDraftCap, pointsAvg, weightPoints):
            result = (
                np.random.normal(coefs['const'], se['const'], 1) +
                (np.random.normal(coefs['preDraftCapital'],
                                  se['preDraftCapital'], 1)) * preDraftCap +
                (np.random.normal(coefs['donePoints'], se['donePoints'], 1)) *
                pointsAvg)
            return result

        def weeklyResults(seasonMean2, n):
            result = (np.random.normal(seasonMean2, pointsSd, n))
            return result

        X2 = data2[['preDraftCapital', 'donePoints', 'weightPoints']]
        Y2 = data2['predictPoints']
        X2 = sm.add_constant(X2)

        predictData = data.loc[data['winSeason'] == 2018]

        for model in models:
            if model == 'coin' or (
                (model == 'points' or model == 'recentPoints')
                    and weekRun == 0):
                usedModel = randModel
                reg = sm.OLS(Y2, X2[['preDraftCapital', 'const']]).fit()
            elif model == 'draft' or (model == 'all' and weekRun == 0):
                usedModel = draftModel
                reg = sm.OLS(Y2, X2[['preDraftCapital', 'const']]).fit()
            elif model == 'points':
                usedModel = pointsModel
                reg = sm.OLS(Y2, X2[['donePoints', 'const']]).fit()
            elif model == 'recentPoints':
                usedModel = recentPointsModel
                reg = sm.OLS(Y2, X2[['weightPoints', 'const']]).fit()
            elif model == 'all':
                usedModel = allModel
                reg = sm.OLS(Y2, X2[['donePoints', 'preDraftCapital',
                                     'const']]).fit()

            #print(reg.summary())
            summaryData = {}
            for index, row in predictData.iterrows():
                summaryData[row['winTeam']] = {}
                summaryData[row['winTeam']]['wins'] = []
                summaryData[row['winTeam']]['losses'] = []
                summaryData[row['winTeam']]['ties'] = []
                summaryData[row['winTeam']]['points'] = []
                summaryData[row['winTeam']]['playoffs'] = []
                summaryData[row['winTeam']]['champ'] = []
                summaryData[row['winTeam']]['highpoints'] = []
                summaryData[row['winTeam']]['lowpoints'] = []
                summaryData[row['winTeam']]['firstplace'] = []
                summaryData[row['winTeam']]['bye'] = []
                summaryData[row['winTeam']]['weekHigh'] = []
                summaryData[row['winTeam']]['money'] = []

            coefs = reg.params
            se = reg.bse

            print('start sim:', model)

            start = time.time()
            for j in range(0, 10000):
                teamDict = {}

                for index, row in predictData.iterrows():
                    teamDict[row['winTeam']] = {}

                    teamDict[row['winTeam']]['pointTotals'] = []

                    teamDict[row['winTeam']]['matchup'] = []

                    teamDict[row['winTeam']]['oppPoints'] = []

                    teamDict[row['winTeam']]['wins'] = []

                    teamDict[row['winTeam']]['losses'] = []

                    teamDict[row['winTeam']]['ties'] = []

                    teamDict[row['winTeam']]['weekHigh'] = []

                    teamDict[row['winTeam']]['money'] = []

                    teamDict[row['winTeam']]['seasonMean'] = usedModel(
                        row['preDraftCapital'], row['donePoints'],
                        row['weightPoints'])
                for key, value in teamDict.items():
                    value['pointTotals'] = weeklyResults(
                        value['seasonMean'], 13 - weekStart).tolist()
                    value['matchup'] = matchups.loc[
                        matchups['matchTeam'] == key]['matchOpp'].item().split(
                            ',')[weekStart:]
                seq = []
                for key, value in teamDict.items():
                    seq.append(value['pointTotals'])

                #print(seq)
                prior = time.time()
                for key, value in teamDict.items():
                    for i, matchup in enumerate(value['matchup']):
                        value['oppPoints'].append(
                            teamDict[matchup]['pointTotals'][i])
                        value['wins'].append(
                            value['pointTotals'][i] > value['oppPoints'][i])
                        value['losses'].append(
                            value['pointTotals'][i] < value['oppPoints'][i])
                        value['ties'].append(
                            value['pointTotals'][i] == value['oppPoints'][i])
                        if max(map(lambda x: x[i],
                                   seq)) == value['pointTotals'][i]:
                            value['weekHigh'].append(1)
                            value['money'].append(20)
                        else:
                            value['weekHigh'].append(0)
                            value['money'].append(0)

                if weekRun > 0:
                    for key, value in teamDict.items():
                        standTeam = standings.loc[standings['winTeam'] == key]
                        value['pointTotals'].append(standTeam['points'].item())
                        value['wins'].append(standTeam['win'].item())
                        value['losses'].append(standTeam['loss'].item())
                        value['ties'].append(standTeam['ties'].item())
                        value['weekHigh'].append(
                            standTeam['highPoints'].item())
                        value['money'].append(standTeam['highPoints'].item() *
                                              20)

                teams = []
                winArray = []
                lossArray = []
                tieArray = []
                pointArray = []
                for key, value in teamDict.items():
                    wins = sum(value['wins'])
                    losses = sum(value['losses'])
                    ties = sum(value['ties'])
                    points = sum(value['pointTotals'])
                    weekHigh = sum(value['weekHigh'])
                    money = sum(value['money'])

                    teams.append(key)
                    winArray.append(wins)
                    lossArray.append(losses)
                    tieArray.append(ties)
                    pointArray.append(points)
                    summaryData[key]['wins'].append(wins)
                    summaryData[key]['losses'].append(losses)
                    summaryData[key]['ties'].append(ties)
                    summaryData[key]['points'].append(points)
                    summaryData[key]['weekHigh'].append(weekHigh)

                d = {
                    'team': teams,
                    'wins': winArray,
                    'losses': lossArray,
                    'ties': tieArray,
                    'points': pointArray
                }

                df = pd.DataFrame(data=d)

                #high and low points
                df = df.sort_values(['points'], ascending=[0])
                df = df.reset_index(drop=True)
                for index, row in df.iterrows():
                    if index < 1:
                        highpoints = 1
                        teamDict[row['team']]['money'].append(225)
                    else:
                        highpoints = 0
                    if index == 13:
                        lowpoints = 1
                    else:
                        lowpoints = 0
                    summaryData[row['team']]['highpoints'].append(highpoints)
                    summaryData[row['team']]['lowpoints'].append(lowpoints)
                #playoffs
                df = df.sort_values(['wins', 'losses', 'points'],
                                    ascending=[0, 1, 0])
                df = df.reset_index(drop=True)
                df['firstplace'] = df.index < 1
                df['bye'] = df.index < 2
                df['playoffs'] = df.index < 5
                df = df.sort_values(['playoffs', 'points'], ascending=[0, 0])
                df = df.reset_index(drop=True)
                df['playoffs'] = df.index < 6
                for index, row in df.iterrows():
                    if index < 6:
                        playoff = 1
                    else:
                        playoff = 0
                    if row['firstplace'] == True:
                        firstplace = 1
                        teamDict[row['team']]['money'].append(225)
                    else:
                        firstplace = 0
                    if row['bye'] == True:
                        bye = 1
                    else:
                        bye = 0

                    summaryData[row['team']]['playoffs'].append(playoff)
                    summaryData[row['team']]['firstplace'].append(firstplace)
                    summaryData[row['team']]['bye'].append(bye)

                df = df.sort_values(['playoffs', 'wins', 'losses', 'points'],
                                    ascending=[0, 0, 1, 0])
                df = df.reset_index(drop=True)

                #round 1
                scores = []
                teams = []
                for index, row in df[2:6].iterrows():
                    teams.append(index)
                    seasonMean = teamDict[row['team']]['seasonMean']
                    scores.append(weeklyResults(seasonMean, 1))
                advanceTeams = []

                if scores[3] > scores[0]:
                    advanceTeams.append(teams[3])
                else:
                    advanceTeams.append(teams[0])

                if scores[2] > scores[1]:
                    advanceTeams.append(teams[2])
                else:
                    advanceTeams.append(teams[1])

                #round 2

                scores = []
                teams = []
                for index, row in df[0:2].iterrows():
                    teams.append(index)
                    seasonMean = teamDict[row['team']]['seasonMean']
                    scores.append(weeklyResults(seasonMean, 1))
                for index, row in df[advanceTeams[0]:advanceTeams[0] +
                                     1].iterrows():
                    teams.append(index)
                    seasonMean = teamDict[row['team']]['seasonMean']
                    scores.append(weeklyResults(seasonMean, 1))
                for index, row in df[advanceTeams[1]:advanceTeams[1] +
                                     1].iterrows():
                    teams.append(index)
                    seasonMean = teamDict[row['team']]['seasonMean']
                    scores.append(weeklyResults(seasonMean, 1))

                advanceTeams = []
                thirdPlaceTeams = []
                if scores[3] > scores[0]:
                    advanceTeams.append(teams[3])
                    thirdPlaceTeams.append(teams[0])
                else:
                    advanceTeams.append(teams[0])
                    thirdPlaceTeams.append(teams[3])

                if scores[2] > scores[1]:
                    advanceTeams.append(teams[2])
                    thirdPlaceTeams.append(teams[1])
                else:
                    advanceTeams.append(teams[1])
                    thirdPlaceTeams.append(teams[2])
                #champ
                scores = []
                teams = []
                for index, row in df[advanceTeams[0]:advanceTeams[0] +
                                     1].iterrows():
                    teams.append(index)
                    seasonMean = teamDict[row['team']]['seasonMean']
                    scores.append(weeklyResults(seasonMean, 1))
                for index, row in df[advanceTeams[1]:advanceTeams[1] +
                                     1].iterrows():
                    teams.append(index)
                    seasonMean = teamDict[row['team']]['seasonMean']
                    scores.append(weeklyResults(seasonMean, 1))

                if scores[0] > scores[1]:
                    champ = teams[0]
                    second = teams[1]
                else:
                    champ = teams[1]
                    second = teams[0]
                #3rd place
                scores = []
                teams = []
                for index, row in df[thirdPlaceTeams[0]:thirdPlaceTeams[0] +
                                     1].iterrows():
                    teams.append(index)
                    seasonMean = teamDict[row['team']]['seasonMean']
                    scores.append(weeklyResults(seasonMean, 1))
                for index, row in df[thirdPlaceTeams[1]:thirdPlaceTeams[1] +
                                     1].iterrows():
                    teams.append(index)
                    seasonMean = teamDict[row['team']]['seasonMean']
                    scores.append(weeklyResults(seasonMean, 1))

                if scores[0] > scores[1]:
                    third = teams[0]
                else:
                    third = teams[1]

                for index, row in df.iterrows():
                    if index == champ:
                        summaryData[row['team']]['champ'].append(1)
                        teamDict[row['team']]['money'].append(900)
                    elif index == second:
                        teamDict[row['team']]['money'].append(340)
                        summaryData[row['team']]['champ'].append(0)
                    elif index == third:
                        teamDict[row['team']]['money'].append(150)
                        summaryData[row['team']]['champ'].append(0)
                    else:
                        summaryData[row['team']]['champ'].append(0)

                    summaryData[row['team']]['money'].append(
                        sum(teamDict[row['team']]['money']))

                print(j, time.time() - start, model)
            print(time.time() - start)

            for index, row in predictData.iterrows():
                if weekStart > 0:
                    standTeam = standings.loc[standings['winTeam'] ==
                                              row['winTeam']]
                    currentWins = standTeam['win'].item()
                    currentLosses = standTeam['loss'].item()
                    currentTies = standTeam['ties'].item()
                    currentPoints = standTeam['points'].item()
                    currentHighPoints = standTeam['highPoints'].item()
                else:
                    currentWins = 0
                    currentLosses = 0
                    currentTies = 0
                    currentPoints = 0
                    currentHighPoints = 0
                wins = np.mean(summaryData[row['winTeam']]['wins'])
                losses = np.mean(summaryData[row['winTeam']]['losses'])
                ties = np.mean(summaryData[row['winTeam']]['ties'])
                points = np.mean(summaryData[row['winTeam']]['points'])
                playoffs = np.mean(summaryData[row['winTeam']]['playoffs'])
                highpoints = np.mean(summaryData[row['winTeam']]['highpoints'])
                lowpoints = np.mean(summaryData[row['winTeam']]['lowpoints'])
                champ = np.mean(summaryData[row['winTeam']]['champ'])
                firstplace = np.mean(summaryData[row['winTeam']]['firstplace'])
                bye = np.mean(summaryData[row['winTeam']]['bye'])
                exWeekHigh = np.mean(summaryData[row['winTeam']]['weekHigh'])
                exMoney = np.mean(summaryData[row['winTeam']]['money'])

                print(row['winTeam'], wins, losses, ties, points, playoffs,
                      highpoints, lowpoints, champ, firstplace, bye,
                      exWeekHigh, exMoney)

                sql = """insert into analysis.standings
                    (standWeek, standType, standTeam, wins, losses, tie, weekHigh,
                    pointsScored, exPointAverage,
                    exWins, playoffsOdds, champOdds, highpoints, lowpoints,firstplace,bye,
                    exWeekHigh, exMoney)
                    values (%s)
                    on duplicate key update
                    wins = values(wins),
                    losses = values(losses),
                    tie = values(tie),
                    weekHigh = values(weekHigh),
                    pointsScored = values(pointsScored),
                    exPointAverage = values(exPointAverage),
                    exWins = values(exWins),
                    playoffsOdds = values(playoffsOdds),
                    champOdds = values(champOdds),
                    highpoints = values(highpoints),
                    lowpoints = values(lowpoints),
                    firstplace = values(firstplace),
                    bye = values(bye),
                    exWeekHigh = values(exWeekHigh),
                    exMoney = values(exMoney);"""

                sqlString = (str(weekStart) + "," + "'" + model + "'," + "'" +
                             row['winTeam'] + "'," + str(currentWins) + "," +
                             str(currentLosses) + "," + str(currentTies) +
                             "," + str(currentHighPoints) + "," +
                             str(currentPoints) + "," + str(points) + "," +
                             str(wins) + "," + str(playoffs) + "," +
                             str(champ) + "," + str(highpoints) + "," +
                             str(lowpoints) + "," + str(firstplace) + "," +
                             str(bye) + "," + str(exWeekHigh) + "," +
                             str(exMoney))

                c.execute(sql % sqlString)

                conn.commit()

        conn.close()