コード例 #1
0
 def get_game_results(self, date):
     result = requests.get(self.base_url + '/api/v1/winner?{}'.format(
         'date={}-{}-{}'.format(date.year, date.month, date.day), ))
     if result.status_code > 250:
         print 'Waiting another 5 minutes for scrape to complete'
         print_wait(5)
         result = requests.get(self.base_url + '/api/v1/winner?{}'.format(
             'date={}-{}-{}'.format(date.year, date.month, date.day), ))
     games = []
     for game in result.json():
         if game['GameStatus'] == 'COMPLETE':
             m = Matchup(home_team={
                 'code': '',
                 'name': game['HomeName'].lower()
             },
                         away_team={
                             'code': '',
                             'name': game['AwayName'].lower()
                         },
                         date=date)
             m.result = {
                 'home_score': game['HomeScore'],
                 'away_score': game['AwayScore'],
                 'winner': game['Winner'].lower(),
             }
             games.append(m)
     return games
コード例 #2
0
def balance(players):
    best_score = 1000000
    best_matchup = None
    matchups = list(permutations(range(1, 11)))
    for matchup in matchups:
        new_matchup = Matchup(players, matchup)
        new_score = new_matchup.calculate_heuristic()
        if new_score < best_score:
            best_score = new_score
            best_matchup = new_matchup
            print("current best score: {}").format(best_score)
    return best_matchup
コード例 #3
0
def predictGame(team1, team2, spread):
    matchup = Matchup(team1, team2, spread=spread)
    os.remove('predictionMatchup.csv')
    header = "home_team," + \
             "visitor_team," + \
             "home_points," + \
             "visitor_points," + \
             "winner," + \
             "favorite," + \
             "spread," + \
             "total," + \
             "cover," + \
             "over," + \
             "date," + \
             "age_diff," + \
             "sos_diff," + \
             "srs_diff," + \
             "off_rtg_diff," + \
             "def_rtg_diff," + \
             "net_rtg_diff," + \
             "pace_diff," + \
             "fta_per_fga_pct_diff," + \
             "fg3a_per_fga_pct_diff," + \
             "ts_pct_diff," + \
             "efg_pct_diff," + \
             "tov_pct_diff," + \
             "orb_pct_diff," + \
             "ft_rate_diff," + \
             "opp_efg_pct_diff," + \
             "opp_tov_pct_diff," + \
             "drb_pct_diff," + \
             "opp_ft_rate_diff" + '\n'
    with open('predictionMatchup.csv', 'a') as fd:
        fd.write(header)
        fd.write(matchup.getCSVString())
        fd.write(matchup.getCSVString())
    dataset = pd.read_csv('predictionMatchup.csv', delimiter=',')
    dataset = dataset.drop([
        'home_team', 'visitor_team', 'home_points', 'visitor_points',
        'favorite', 'total', 'cover', 'winner', 'over', 'date'
    ],
                           axis=1)
    dataset = dataset.to_numpy()
    predictions = model.predict_proba(dataset)
    return ('%s %s %s \nPick: %s (%d' %
            (team1.team_name, spread, team2.team_name, team1.team_name
             if predictions[0][0] * 100 > 50 else team2.team_name,
             predictions[0][0] * 100 if predictions[0][0] * 100 > 50 else 100 -
             predictions[0][0] * 100) + "%)\n\n")
コード例 #4
0
def pullMatchups(year, league):
    global urls
    matchups = []
    if year == 2020:
        urls = urls_2020
    elif year == 2012:
        urls = urls_2012
    for url in urls:
        response = requests.get(url % year)
        soup = BeautifulSoup(response.text, "html.parser")
        soup.prettify()
        matchup_table = soup.findAll('div', {"id": "all_schedule"})
        try:
            matchup_table = matchup_table[0].contents[3].contents[1].contents[1].contents[6]
        except IndexError:
            break

        for el in matchup_table.contents:
            if len(el) > 1:
                if el.contents[3].text.strip() != "":
                    visitor_team = findTeam(league, el.contents[2].text.strip())
                    visitor_pts = el.contents[3].text.strip()
                    home_team = findTeam(league, el.contents[4].text.strip())
                    home_pts = el.contents[5].text.strip()
                    date = getDate(el.contents[0].text.strip())
                    matchups.append(Matchup(home_team, visitor_team, home_pts, visitor_pts, date))
    return matchups
コード例 #5
0
def create_matchup_from_schedule_line(schedule_line, league):
    game_list_line = schedule_line.strip().split(",")
    game_time_str = "".join(game_list_line[:2])
    # subtract an hour to get to central time
    game_time = datetime.strptime(game_time_str,
                                  '%m/%d/%Y %H:%M') - timedelta(hours=1)
    matchup = Matchup(league[game_list_line[2].strip()],
                      league[game_list_line[3].strip()], game_time)
    return matchup
コード例 #6
0
ファイル: runner.py プロジェクト: Nolan-Ramsden/MlbPredict
def _get_previous_matchups():
    today = datetime.date.today()
    for i in range(1, 10):
        filename = _create_file_path(today + datetime.timedelta(days=-i))
        if os.path.isfile(filename):
            print 'Found recent data: {}'.format(filename)
            with open(filename, 'r') as f:
                return [Matchup.from_json(jobj) for jobj in json.load(f)]
    print 'Found no recent data'
    return []
コード例 #7
0
ファイル: bracket.py プロジェクト: rohatd/RedTeamMarchMadness
    def evaluate_bracket(self):
        """evaluates bracket

            Uses a random forest regressor to find the result of each matchup.
            Appends winner of each matchup to the original matchup queue until
            no more teams can be added and queue is empty

            Lists bracket order into matchup list

        """
        while len(self.matchup_queue) != 1:
            team1 = self.matchup_queue.pop(0)
            team2 = self.matchup_queue.pop(0)
            team_matchup = Matchup(team1, team2)
            winner = team_matchup.random_forest_regressor(2019)
            self.matchup_queue.append(winner)
            self.matchup_list.append(winner)
            print("{0} played {1} and the winner is: {2}".format(team1.get_team_name()\
                .replace(" NCAA", "").replace(" ", "-"), team2.get_team_name().replace(" NCAA", "")\
                .replace(" ", "-"), winner.get_team_name().replace(" NCAA", "").replace(" ", "-")))
コード例 #8
0
 def new_matchup(self, team1, team2):
     """creates and adds a matchup to queue
     
     args:
         team1 (str or team obj):    team1
         team2 (str or team obj):    team2
     """
     if isinstance(team1, str):
         team1 = self.get_team(team1)
     if isinstance(team2, str):
         team2 = self.get_team(team2)
     self.add_matchup(Matchup(team1, team2))
コード例 #9
0
ファイル: runner.py プロジェクト: Nolan-Ramsden/MlbPredict
def _combine_matchup_sets(data_matchups, odds_matchups, odds=True):
    for data_matchup in data_matchups:
        match_found = False
        for odds_matchup in odds_matchups:
            if Matchup.same_game(data_matchup, odds_matchup):
                data_matchup.merge(odds_matchup)
                match_found = True
        if match_found is False:
            if odds:
                data_matchup.no_odds()
            else:
                data_matchup.no_result()
    return data_matchups
コード例 #10
0
def get_todays_odds():
    result = requests.get(
        'http://io.oddsshark.com/ticker/mlb',
        headers={
            'Origin':
            'http://www.oddsshark.com',
            'Referer':
            'http://www.oddsshark.com/mlb/odds',
            'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
        })
    games = []
    result_json = result.json()
    for matchup in result_json['matchups']:
        if matchup['type'] == 'matchup':
            if matchup['home_odds'] and matchup['away_odds']:
                m = Matchup.create_from_odds(
                    home_team={
                        'code': matchup['home_short_name'].upper(),
                        'name': matchup['home_name'].lower(),
                    },
                    away_team={
                        'code': matchup['away_short_name'].upper(),
                        'name': matchup['away_name'].lower(),
                    },
                    home_odds={
                        'money_line':
                        int(matchup['home_odds']),
                        'minimum_confidence':
                        _confidence(int(matchup['home_odds']))
                    },
                    away_odds={
                        'money_line':
                        int(matchup['away_odds']),
                        'minimum_confidence':
                        _confidence(int(matchup['away_odds']))
                    },
                    date=datetime.datetime.strptime(
                        matchup['event_date'].split(' ')[0], "%Y-%m-%d"))
            if matchup['status'] == 'FINAL':
                home_score = int(matchup['home_score'])
                away_score = int(matchup['home_score'])
                m.result = {
                    'home_score': home_score,
                    'away_score': away_score,
                    'winner': 'home' if home_score > away_score else 'away'
                }
            games.append(m)
    return games
コード例 #11
0
ファイル: playoff.py プロジェクト: wmacevoy/ai-wmacevoy
 def play(self):
     for goatAgentName in self._goatAgents:
         for tigerAgentName in self._tigerAgents:
             goatAgent: Agent = self._goatAgents[goatAgentName]
             tigerAgent: Agent = self._tigerAgents[tigerAgentName]
             matchup: Matchup = Matchup(self._verbose, self._fast)
             matchup.tigerAgent = tigerAgent
             matchup.goatAgent = goatAgent
             stats: Stats = Stats(matchup, self._trials)
             try:
                 stats.playAll()
                 print(f"{goatAgentName} vs. {tigerAgentName}: ")
                 stats.summarize()
             except:
                 print(f"{goatAgentName} vs. {tigerAgentName}: failed")
                 raise
コード例 #12
0
ファイル: fiftyfifty.py プロジェクト: ez-p/madness
    def _play(self, madness):
        # See if superclass wants to handle the matchup
        status, winner, loser = Matchup.base_play(self.teams[0], self.teams[1])
        if status:
            # Superclass handled the matchup
            self.winner = winner
            self.loser = loser
            return (self.winner, self.loser)

        seq = [1,2]
        val = random.choice(seq)
        if val == 1:
            self.winner = self.teams[0]
            self.loser = self.teams[1]
        else:
            self.winner = self.teams[1]
            self.loser = self.teams[0]
        return (self.winner, self.loser)
コード例 #13
0
ファイル: seedodds.py プロジェクト: ez-p/madness
    def _play(self, madness):
        # See if superclass wants to handle the matchup
        status, self.winner, self.loser = Matchup.base_play(self.team1['team'],
                                                            self.team2['team'])
        if status:
            # Superclass handled the matchup
            return (self.winner, self.loser)

        # High seed is seed with larger number (worse)
        # Low seed is seed with smaller number (better team)
        highseed = self.team1
        lowseed = self.team2
        
        if lowseed['mad_seed'] > highseed['mad_seed']:
            highseed = self.team2
            lowseed = self.team1

        # Seeds are the same, coin flip
        if highseed['mad_seed'] == lowseed['mad_seed']:
            self.winner,self.loser = self._coin_flip(highseed,lowseed)
            return (self.winner, self.loser)

        # Seeds are off by one, coin flip
        if highseed['mad_seed'] - lowseed['mad_seed'] == 1:
            self.winner,self.loser = self._coin_flip(highseed,lowseed)
            return (self.winner, self.loser)

        if madness:
            # Adjust lowseed (which is the better team) up a notch
            lowseed['mad_seed'] = lowseed['mad_seed'] + 1
            return self._play(madness-1)

        highrange = range(lowseed['mad_seed'],highseed['mad_seed'])
        r = random.randrange(lowseed['mad_seed'],highseed['mad_seed']+1)

        if r in highrange:
            self.winner = lowseed['team']
            self.loser = highseed['team']
        else:
            self.winner = highseed['team']
            self.loser = lowseed['team']

        return (self.winner, self.loser)
コード例 #14
0
    def get_matchups(self, date):
        print 'Fetching scoreboard for {0}'.format(date)
        request_body = {
            'StartDate': '{}-{}-{}'.format(date.year, date.month, date.day),
            'EndDate': '{}-{}-{}'.format(date.year, date.month, date.day),
            'FilePath': 'NotNeeded',
            'RequireTarget': False,
        }
        if self.fields is not None:
            request_body['Features'] = self.fields

        result = requests.post(self.base_url + '/api/v1/csv/single',
                               json=request_body)
        if result.status_code != 200:
            print 'Request timed out, giving time to complete scrape before retry'
            print_wait(5)
            result = requests.post(self.base_url + '/api/v1/csv/single',
                                   json=request_body)

        res = result.json()
        print res
        return [
            Matchup.create_from_data_row(home_team={
                'code': g['Home']['Code'].upper(),
                'name': g['Home']['FullName'].lower(),
                'full': g['Home']['FullName'],
                'city': g['Home']['City']
            },
                                         away_team={
                                             'code': g['Away']['Code'].upper(),
                                             'name':
                                             g['Away']['FullName'].lower(),
                                             'full': g['Away']['FullName'],
                                             'city': g['Away']['City']
                                         },
                                         data_row=g['DataRow'],
                                         summary=g['Summary'],
                                         date=datetime.datetime.strptime(
                                             g['Date'].split(' ')[0],
                                             '%m/%d/%Y')) for g in res
        ]
コード例 #15
0
def load_matchups(file):
    with open(file, 'r') as f:
        return [Matchup.from_json(m) for m in json.load(f)]
コード例 #16
0
ファイル: main.py プロジェクト: andrewcp54/ai-acpiechota
from hungrytigeragent import HungryTigerAgent
from game import Game
import random
from matchup import Matchup
from hungrytigeragent import HungryTigerAgent
from stats import Stats

matchup = Matchup()
# matchup.tigerAgent = HungryTigerAgent(matchup.game)
stats = Stats(matchup, 1000)
stats.playAll()
stats.summarize()
コード例 #17
0
from elusiveGoatAgent import elusiveGoatAgent
from hungrytigeragent import HungryTigerAgent
from game import Game
import random
from matchup import Matchup
from hungrytigeragent import HungryTigerAgent
from stats import Stats

matchup = Matchup()
#matchup.tigerAgent = HungryTigerAgent(matchup.game)
matchup.goatAgent = elusiveGoatAgent(matchup.game)
stats = Stats(matchup, 1000)
stats.playAll()
stats.summarize()
コード例 #18
0
import json
from matchup import Matchup
from emailer import send_email

with open('history/2017-05-02.json', 'r') as f:
    games = [Matchup.from_json(g) for g in json.load(f)]

with open('history/2017-season.json', 'r') as f:
    totals = json.load(f)

send_email(games, games, totals, {
    'email_template': './email_template.html',
    'email_to': '*****@*****.**',
    'email_from': '*****@*****.**',
    'email_from': '*****@*****.**',
    'email_password': '******',
    'email_cc': ['*****@*****.**', '*****@*****.**'],
})
コード例 #19
0
from hungrytigeragent import HungryTigerAgent
from game import Game
import random
from matchup import Matchup
from hungrytigeragent import HungryTigerAgent
from stats import Stats
from sidehugginggoat import SideHuggingGoat

matchup = Matchup()
#matchup.tigerAgent = HungryTigerAgent(matchup.game)
matchup.goatAgent = SideHuggingGoat(matchup.game)
while not matchup.game.over:
    matchup.turn()
    print(matchup.game)

#stats = Stats(matchup, 1000)
#stats.playAll()
#stats.summarize()