Ejemplo n.º 1
0
def main(args: Namespace):
    load_teams(args.database)
    league = league_register[get_unique_league(args)]
    load_league(args.database, league)

    (row,) = extract_picked_team(args.database, get_unique_team(args), league)
    team = Team.inventory[row[0]]
    seasons = Season.seasons(league)
    this_season = seasons.pop()
    fixtures = get_fixtures(args.database, team, this_season, args.venue)

    if fixtures:
        nrows = 2
        ncols = 1
        fig, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12, 10), squeeze=False, constrained_layout=True)

        team_color = (54 / 255, 104 / 255, 141 / 255)
        other_team_color = (240 / 255, 88 / 255, 55 / 255)
        neutral_color = (1, 1, 1)
        unknown_color = (1, 1, 1)

        create_results_table(axs[0, 0], team, fixtures, team_color, other_team_color, neutral_color, unknown_color)
        create_league_table(axs[1, 0], this_season, team, team_color, neutral_color, args.venue, args.half)

        title = '{} {}: {}'.format(league.country, league.name, team.name)
        if args.venue == Venue.any:
            title = '{} ({} or {})'.format(title, Venue.home.name, Venue.away.name)
        else:
            title = '{} ({} only)'.format(title, args.venue.name)

        fig.suptitle(title, fontweight='bold', fontsize=14)
        plt.show(block=args.block)
    else:
        warning_message("No data to display for {} in {} {}".format(team.name, league.country, league.name))
Ejemplo n.º 2
0
def main(args: Namespace):
    load_teams(args.database)
    league = league_register[get_unique_league(args)]
    load_league(args.database, league)

    seasons = Season.seasons(league)
    if not seasons:
        messages.error_message("No season data found")

    if args.history:
        seasons = seasons[-args.history:]

    (row, ) = extract_picked_team(args.database, get_unique_team(args), league)
    selected_team = Team.inventory[row[0]]

    if args.averages:
        if seasons[-1].current:
            seasons.pop()

        if seasons:
            team_season_stats = []
            collective_season_stats = []
            for season in seasons:
                stats = compute_statistics(season, selected_team, args.venue,
                                           args.game_states)
                team_season_stats.append(stats)

                teams = season.teams()
                if selected_team in teams:
                    this_season_stats = []
                    for team in teams:
                        if team != selected_team:
                            stats = compute_statistics(season, team,
                                                       args.venue,
                                                       args.game_states)
                            this_season_stats.append(stats)
                    collective_season_stats.append(
                        reduce(this_season_stats, median))

            team_stats = reduce(team_season_stats, median,
                                len(collective_season_stats))
            collective_stats = reduce(collective_season_stats, sum)
            display_averages(selected_team, args.venue, seasons, team_stats,
                             collective_stats, args.block)
        else:
            messages.error_message('No historical data to analyse')
    else:
        team_season_stats = []
        for season in seasons:
            stats = compute_statistics(season, selected_team, args.venue,
                                       args.game_states)
            team_season_stats.append(stats)

        team_stats = reduce(team_season_stats, sum)
        display_summations(selected_team, args.venue, seasons, team_stats,
                           args.block)
Ejemplo n.º 3
0
def main(args: Namespace):
    load_teams(args.database)
    league = league_register[get_unique_league(args)]
    load_league(args.database, league)

    seasons = Season.seasons(league)
    if not seasons:
        messages.error_message("No season data found")

    for season in seasons:
        show_results(league, season, args.results)
Ejemplo n.º 4
0
def main(args: Namespace):
    load_teams(args.database)
    league = league_register[get_unique_league(args)]
    load_league(args.database, league)

    seasons = Season.seasons(league)
    if args.history:
        seasons = seasons[-args.history:]

    this_season = seasons.pop()
    (row, ) = extract_picked_team(args.database, args.team, league)
    team = Team.inventory[row[0]]

    events = [win, loss]
    colors = ['dodgerblue', 'salmon']
    data = []
    for i, func in enumerate(events):
        title = '{} margin (Seasons:{}-{})'.format(Event.name(func, False),
                                                   seasons[0].year,
                                                   seasons[-1].year)
        container_a = BarContainer(colors[i], title)
        for season in seasons:
            populate(season, team, args.venue, args.half, container_a.data,
                     func)

        title = '{} margin (Season:{})'.format(Event.name(func, False),
                                               this_season.year)
        container_b = BarContainer(colors[i], title)
        populate(this_season, team, args.venue, args.half, container_b.data,
                 func)
        data.append([container_a, container_b])

    fig, axs = plt.subplots(nrows=2,
                            ncols=2,
                            figsize=(10, 10),
                            squeeze=False,
                            constrained_layout=True)
    for row in range(len(events)):
        containers = data[row]
        for col, container in enumerate(containers):
            ax = axs[row, col]
            add_bar_chart(ax, container)

    title = '{} {}: {}'.format(league.country, league.name, team.name)
    if args.venue == Venue.any:
        title = '{} ({} or {})'.format(title, Venue.home.name, Venue.away.name)
    else:
        title = '{} ({} only)'.format(title, args.venue.name)

    if args.half != Half.both:
        title = '{} ({} half)'.format(title, args.half.name)

    fig.suptitle(title, fontweight='bold', fontsize=14)
    plt.show(block=args.block)
Ejemplo n.º 5
0
def main(args: Namespace):
    load_teams(args.database)
    league = league_register[get_unique_league(args)]
    load_league(args.database, league)

    seasons = Season.seasons(league)
    if not seasons:
        messages.error_message("No season data found")

    if args.history:
        seasons = seasons[-args.history:]

    selected_team = None
    if args.team:
        (row, ) = extract_picked_team(args.database, get_unique_team(args),
                                      league)
        selected_team = Team.inventory[row[0]]

    intervals = []
    create_intervals(intervals, args.intervals, 0)
    create_intervals(intervals, args.intervals, 45)

    season_to_summary = OrderedDict()
    with ThreadPoolExecutor(max_workers=8) as executor:
        future_to_data = {
            executor.submit(compute_summaries, args.database, season,
                            intervals, selected_team, args.venue): season
            for season in seasons
        }
        for future in as_completed(future_to_data):
            season = future_to_data[future]
            overall, for_team, against_team = future.result()
            if overall:
                season_to_summary[season] = (overall, for_team, against_team)

    title = 'Goal times: {} {}'.format(league.country, league.name)
    if selected_team:
        title = '{} and {}'.format(title, selected_team.name)
        if args.venue == Venue.any:
            title = '{} ({} or {})'.format(title, Venue.home.name,
                                           Venue.away.name)
        else:
            title = '{} ({} only)'.format(title, args.venue.name)

    show(title, season_to_summary, args.block)
Ejemplo n.º 6
0
def main(args: Namespace):
    load_teams(args.database)
    league = league_register[get_unique_league(args)]
    load_league(args.database, league)

    seasons = Season.seasons(league)
    if args.history:
        seasons = seasons[-args.history:]

    head_season = seasons[-1]
    head_table = LeagueTable(head_season, args.half)
    table_map = head_table.group(args.chunks)
    predicates = predicate_table[args.analysis]
    matrix = np.zeros(shape=(table_map.number_of_chunks(),
                             len(predicates.functions)),
                      dtype=np.int32)

    for season in seasons:
        table = LeagueTable(season, args.half)
        table_map = table.group(args.chunks)
        fill_matrix(matrix, table_map, table, predicates, args.half)

    datum = pd.DataFrame(matrix)
    datum.columns = [
        Event.name(func, negate=False, short=True)
        for func in predicates.functions
    ]
    datum.index = create_chunk_labels(table_map)

    fig, ax = plt.subplots(nrows=1,
                           ncols=1,
                           figsize=(10, 10),
                           constrained_layout=True)
    heatmap(datum, cmap='coolwarm', linewidth=0.5, annot=True, fmt='d', ax=ax)
    ax.set_ylabel('Positions')
    ax.set_xlabel(args.analysis.name.capitalize())

    sublists = split_into_contiguous_groups(
        [season.year for season in seasons])
    title = '{} {} Seasons:{}'.format(league.country, league.name,
                                      to_string(sublists))
    if args.half != Half.both:
        title = '{} ({} half)'.format(title, args.half.name)
    fig.suptitle(title, fontweight='bold', fontsize=14)
    plt.show(block=args.block)
Ejemplo n.º 7
0
def main(args: Namespace):
    load_teams(args.database)
    league = league_register[get_unique_league(args)]
    load_league(args.database, league)
    seasons = Season.seasons(league)

    if args.history:
        seasons = seasons[-args.history:]

    if args.relative:
        team_names = get_multiple_teams(args)
        table = LeagueTable(seasons[-1], args.half)
        lower, upper = table.positions(Position.from_string(args.relative))
        positions = [i for i in range(lower, upper)]
        compute_relative_performance(args, league, seasons, team_names, positions)
    elif args.position:
        team_names = get_multiple_teams(args)
        compute_relative_performance(args, league, seasons, team_names, args.position)
    elif args.average:
        team_name = get_unique_team(args)
        compute_average_performance(args, league, seasons, team_name)
    else:
        compute_individual_performance(args, league, seasons)
Ejemplo n.º 8
0
def main(args: Namespace):
    load_teams(args.database)
    league = league_register[get_unique_league(args)]
    load_league(args.database, league)

    seasons = Season.seasons(league)
    if not seasons:
        messages.error_message("No season data found")

    season_to_summary = OrderedDict()
    ylim = 0
    for season in seasons:
        summary = compute_summary(season, args.half)
        if summary:
            season_to_summary[season] = summary
            ylim = max(ylim, season_to_summary[season].home_goals,
                       season_to_summary[season].away_goals)
    ylim += 25

    title = '{} {}'.format(league.country, league.name)
    if args.half != Half.both:
        title += ' ({} half)'.format(args.half.name)

    show(title, season_to_summary, ylim, args.block)
Ejemplo n.º 9
0
def main(args: Namespace):
    load_teams(args.database)
    league = league_register[get_unique_league(args)]
    load_league(args.database, league)

    seasons = Season.seasons(league)
    if not seasons:
        messages.error_message("No season data found")

    if args.history:
        seasons = seasons[-args.history:]

    if args.team:
        (row, ) = extract_picked_team(args.database, args.team, league)
        selected_team = Team.inventory[row[0]]
    else:
        selected_team = None

    func = Event.get(get_unique_event(args))
    if args.chunks:
        data = compute_chunked_data(seasons, func, args.negate, args.venue,
                                    args.half, args.chunks)

        nrows = len(data)
        if selected_team is not None:
            ncols = 3
        else:
            ncols = 1

        fig, axes = plt.subplots(nrows=len(data),
                                 ncols=ncols,
                                 figsize=(20, 13),
                                 squeeze=False,
                                 constrained_layout=True)

        x_limit, _ = find_limits(data)
        for i, datum in enumerate(data):
            ax = axes[i, 0]
            plot(ax, datum, x_limit, args.lines)

        if selected_team is not None:
            golden_season = seasons[-1]
            golden_table = LeagueTable(golden_season, args.half)
            golden_map = golden_table.group(args.chunks)

            chunk_to_seasons = OrderedDict()
            for chunk_id in range(golden_map.number_of_chunks()):
                if chunk_id not in chunk_to_seasons:
                    chunk_to_seasons[chunk_id] = []

            for season in seasons:
                if season != golden_season:
                    table = LeagueTable(season, args.half)
                    table_map = table.group(args.chunks)
                    if selected_team in season.teams():
                        position = table.team_position(selected_team)
                        chunk_id = table_map.get_chunk(position)
                        chunk_to_seasons[chunk_id].append(season)

            chunk_to_datum = OrderedDict()
            for chunk_id, chunk_seasons in chunk_to_seasons.items():
                if chunk_seasons:
                    datum = DataUnit(Counter(),
                                     chunk_seasons,
                                     team=selected_team,
                                     positions=golden_map.get_rows(chunk_id))
                    chunk_to_datum[chunk_id] = datum

            for season in seasons:
                if season == golden_season:
                    position = golden_table.team_position(selected_team)
                    datum = DataUnit(Counter(), [golden_season],
                                     team=selected_team,
                                     positions=[position],
                                     highlight=True)
                    golden_datum = datum
                else:
                    if selected_team in season.teams():
                        table = LeagueTable(season, args.half)
                        table_map = table.group(args.chunks)
                        position = table.team_position(selected_team)
                        chunk_id = table_map.get_chunk(position)
                        datum = chunk_to_datum[chunk_id]

                count_events(season, selected_team, args.venue, args.half,
                             func, args.negate, datum)

            position = golden_table.team_position(selected_team)
            chunk_id = golden_map.get_chunk(position)
            ax = axes[chunk_id, 1]
            plot(ax, golden_datum, x_limit, args.lines)
            used = {(chunk_id, 1)}

            for chunk_id, datum in chunk_to_datum.items():
                ax = axes[chunk_id, 2]
                plot(ax, datum, x_limit, args.lines)
                used.add((chunk_id, 2))

            for i in range(0, nrows):
                for j in range(1, 3):
                    if (i, j) not in used:
                        fig.delaxes(axes[i, j])
    else:
        data = compute_aggregated_data(seasons, selected_team, func,
                                       args.negate, args.venue, args.half)
        x_limit, _ = find_limits(data)
        display = DisplayGrid(len(data), 2)
        fig, axes = plt.subplots(nrows=display.nrows,
                                 ncols=display.ncols,
                                 figsize=(20, 10),
                                 squeeze=False)
        for i, datum in enumerate(data):
            cell_x, cell_y = display.index(i)
            ax = axes[cell_x, cell_y]
            plot(ax, datum, x_limit, args.lines)

    title = construct_title(league, func, args.negate, args.venue, args.half)
    fig.suptitle(title, fontweight='bold', fontsize=14)
    plt.show(block=args.block)
Ejemplo n.º 10
0
def main(args: Namespace):
    league = league_register[get_unique_league(args)]
    load_database(args.database, league)

    seasons = Season.seasons(league)
    this_season = seasons.pop()
    assert this_season.current

    func = Event.get(get_unique_event(args))
    for i in range(1, 38):
        prediction = Prediction(func, i)
        penalties = Counter()
        for season in seasons:
            table = LeagueTable(season, Half.both)
            states = {team: TeamState() for team in season.teams()}
            season.sort_fixtures()

            fixture: Fixture
            for fixture in season.fixtures():
                if args.half == Half.both:
                    result = fixture.full_time()
                elif args.half == Half.first:
                    result = fixture.first_half()
                elif args.half == Half.second:
                    result = fixture.second_half()

                if result:
                    home_result = fixture.canonicalise_result(
                        fixture.home_team, result)
                    home_outcome = prediction.func(home_result)
                    home_state = states[fixture.home_team]

                    if not home_outcome:
                        home_state.fixtures.append(fixture)
                    else:
                        if home_state.alive:
                            index = len(
                                home_state.fixtures) - prediction.minimum + 1
                            penalties[index] += 1
                        states[fixture.home_team] = TeamState()

                    if len(home_state.fixtures) == prediction.minimum:
                        final_position = table.team_position(fixture.home_team)
                        if final_position not in [
                                0, 1, len(table) - 2,
                                len(table) - 1
                        ]:
                            home_state.alive = True

                    away_result = fixture.canonicalise_result(
                        fixture.away_team, result)
                    away_outcome = prediction.func(away_result)
                    away_state = states[fixture.away_team]
                    if not away_outcome:
                        away_state.fixtures.append(fixture)
                    else:
                        if away_state.alive:
                            index = len(
                                away_state.fixtures) - prediction.minimum + 1
                            penalties[index] += 1
                        states[fixture.away_team] = TeamState()

                        away_state.fixtures.append(fixture)

                    if len(away_state.fixtures) == prediction.minimum:
                        final_position = table.team_position(fixture.away_team)
                        if final_position not in [
                                0, 1, len(table) - 2,
                                len(table) - 1
                        ]:
                            away_state.alive = True

        total_penalty = 0
        total_correct = 0
        for distance, correct in penalties.items():
            exponent = distance
            this_penalty = 2**exponent - 1
            total_penalty += this_penalty * correct
            total_correct += correct
        if total_penalty:
            print(
                'Betting from sequences of {} returns {} right with a penalty of {}'
                .format(i, total_correct, total_penalty))
Ejemplo n.º 11
0
def main(args: Namespace):
    load_teams(args.database)

    if args.league:
        league = league_register[get_unique_league(args)]
        load_league(args.database, league)

    nrows = 2
    ncols = 4
    fig, axs = plt.subplots(nrows=nrows,
                            ncols=ncols,
                            figsize=(20, 13.5),
                            squeeze=False,
                            constrained_layout=True)

    left_name, right_name = get_multiple_teams(args)
    (row, ) = extract_picked_team(args.database, left_name, league)
    left_team = Team.inventory[row[0]]
    (row, ) = extract_picked_team(args.database, right_name, league)
    right_team = Team.inventory[row[0]]

    left_team_color = (54 / 255, 104 / 255, 141 / 255)
    right_team_color = (240 / 255, 88 / 255, 55 / 255)
    neutral_color = (1, 1, 1)
    unknown_color = (0, 0, 0)
    halves = [Half.first, Half.second, Half.both]

    left_fixtures = get_fixtures(args.database, left_team, right_team)
    right_fixtures = get_fixtures(args.database, right_team, left_team)

    if not left_fixtures and not right_fixtures:
        warning_message("No head-to-head between {} and {}".format(
            left_team.name, right_team.name))
    else:
        if left_fixtures:
            first_half_stats, second_half_stats, full_time_stats = compute_records(
                left_fixtures)
            data = [first_half_stats, second_half_stats, full_time_stats]
            for i, (half, stats) in enumerate(zip(halves, data)):
                create_single_bar(axs[0, i], left_team, left_team_color,
                                  right_team_color, neutral_color, stats)

            create_results_table(axs[0, ncols - 1], left_fixtures, left_team,
                                 left_team_color, right_team_color,
                                 neutral_color, unknown_color)
        else:
            for i in range(ncols):
                fig.delaxes(axs[0, i])

        if right_fixtures:
            first_half_stats, second_half_stats, full_time_stats = compute_records(
                right_fixtures)
            data = [first_half_stats, second_half_stats, full_time_stats]
            for i, (half, stats) in enumerate(zip(halves, data)):
                create_single_bar(axs[1, i], right_team, right_team_color,
                                  left_team_color, neutral_color, stats)
            create_results_table(axs[1, ncols - 1], right_fixtures, right_team,
                                 right_team_color, left_team_color,
                                 neutral_color, unknown_color)
        else:
            for i in range(ncols):
                fig.delaxes(axs[1, i])

        fig.suptitle('Head-to-head: {} vs {}'.format(left_team.name,
                                                     right_team.name),
                     fontweight='bold',
                     fontsize=14)
        plt.show(block=args.block)
Ejemplo n.º 12
0
def main(args: Namespace):
    load_teams(args.database)
    league = league_register[get_unique_league(args)]
    load_league(args.database, league)

    seasons = Season.seasons(league)
    if args.history:
        seasons = seasons[-args.history:]

    event = Event.get(get_unique_event(args))

    head_season = seasons[-1]
    head_table = LeagueTable(head_season, args.half)
    if head_table.played() == 0:
        head_season = seasons[-2]
        head_table = LeagueTable(head_season, args.half)
        nrows = 1
    else:
        nrows = 2

    head_map = head_table.group(args.chunks)
    shape = (head_map.number_of_chunks(), head_map.number_of_chunks())

    historical_matrix = np.zeros(shape=shape, dtype=np.int32)
    historical_seasons = seasons[:-1]
    for season in historical_seasons:
        table = LeagueTable(season, args.half)
        fill_matrix(event, args.symmetry, historical_matrix, head_map, table,
                    args.half)

    display = DisplayGrid(nrows, 1)
    fig, axs = plt.subplots(nrows=display.nrows,
                            ncols=display.ncols,
                            figsize=(15, 12),
                            squeeze=False,
                            constrained_layout=True)

    datum = pd.DataFrame(historical_matrix)
    sublists = split_into_contiguous_groups(
        [season.year for season in historical_seasons])
    title = 'Seasons:{}'.format(to_string(sublists))
    cell_x, cell_y = display.index(0)
    ax = axs[cell_x, cell_y]
    populate_axis(head_map, datum, ax, title)

    if nrows == 2:
        now_matrix = np.zeros(shape=shape, dtype=np.int32)
        fill_matrix(event, args.symmetry, now_matrix, head_map, head_table,
                    args.half)
        datum = pd.DataFrame(now_matrix)
        title = 'Season:{}'.format(head_season.year)
        cell_x, cell_y = display.index(1)
        ax = axs[cell_x, cell_y]
        populate_axis(head_map, datum, ax, title)

    title = '{} {}: {}'.format(league.country, league.name,
                               Event.name(event, args.negate))
    if args.half != Half.both:
        title = '{} ({} half)'.format(title, args.half.name)
    fig.suptitle(title, fontweight='bold', fontsize=14)
    plt.show(block=args.block)