コード例 #1
0
ファイル: show_projection.py プロジェクト: abetts155/Projects
def compute_relative_performance(args: Namespace,
                                 league: League,
                                 seasons: List[Season],
                                 team_names: List[str],
                                 positions: List[int]):
    this_season = seasons[-1]
    team_summaries = {}
    for name in team_names:
        (row,) = extract_picked_team(args.database, name, league)
        team = Team.inventory[row[0]]
        team_summaries[team] = compute_summary(team, [this_season], args.venue, args.half)

    summaries = []
    for season in seasons:
        if not season.current:
            table = LeagueTable(season, args.half)
            teams = table.teams_by_position(positions)
            for team in teams:
                summary = []
                summaries.append(summary)
                compute_statistics(season, team, args.venue, args.half, summary)

    combined_summary = []
    for summary in summaries:
        for week, stat in enumerate(summary):
            if week >= len(combined_summary):
                combined_summary.append([])
            combined_summary[week].append(stat)

    color = Color()
    sublists = split_into_contiguous_groups(positions)
    label = 'Positions: {}'.format(to_string(sublists))
    label = '{} ({}-{})'.format(label, seasons[0].year, seasons[-2].year)
    average_summary = compute_average(combined_summary)
    data = [Datum(average_summary, label, color.next())]

    for name in team_names:
        (row,) = extract_picked_team(args.database, name, league)
        team = Team.inventory[row[0]]
        summary = team_summaries[team][this_season]
        data.append(Datum(summary, team.name, color.next()))

    title = 'Relative performance comparison {}-{}'.format(seasons[0].year, seasons[-2].year)
    title = add_venue_and_half_to_title(title, args.venue, args.half)
    display(title, data, args.block)
コード例 #2
0
ファイル: show_form.py プロジェクト: abetts155/Projects
def create_league_table(ax,
                        this_season: Season,
                        team: Team,
                        team_color: Tuple[float, float, float],
                        other_color: Tuple[float, float, float],
                        venue: Venue,
                        half: Half):
    league_table = LeagueTable(this_season, half)
    display_table = []
    colors = []
    team_length = 1
    for i, league_row in enumerate(league_table, start=1):
        display_row = [league_row.TEAM.name]
        if venue == Venue.home:
            display_row.extend([league_row.HW + league_row.HD + league_row.HL,
                                league_row.HW, league_row.HD, league_row.HL, league_row.HF, league_row.HA])
            wins = league_row.HW
            draws = league_row.HD
        elif venue == Venue.away:
            display_row.extend([league_row.AW + league_row.AD + league_row.AL,
                                league_row.AW, league_row.AD, league_row.AL, league_row.AF, league_row.AA])
            wins = league_row.AW
            draws = league_row.AD
        else:
            display_row.extend([league_row.W + league_row.D + league_row.L,
                                league_row.W, league_row.D, league_row.L, league_row.F, league_row.A])
            wins = league_row.W
            draws = league_row.D
        pts = wins * 3 + draws
        display_row.append(pts)
        display_table.append(display_row)
        team_length = max(team_length, len(league_row.TEAM.name))

    display_table.sort(key=lambda row: row[-1], reverse=True)

    for display_row in display_table:
        if display_row[0] == team.name:
            colors.append([team_color] * len(display_row))
        else:
            colors.append([other_color] * len(display_row))

    df = pd.DataFrame(display_table)
    df.columns = ['Team', 'Played', 'W', 'D', 'L', 'F', 'A', 'PTS']

    ax.table(cellText=df.values,
             colLabels=df.columns,
             colLoc='left',
             colWidths=[0.3, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
             cellColours=colors,
             cellLoc='left',
             loc='upper center')
    title = 'League table'
    if half:
        title = '{} ({} half)'.format(title, half.name)
    ax.set_title(title)
    ax.axis('off')
コード例 #3
0
def compute_chunked_data(seasons: List[Season], func: Callable, negate: bool,
                         venue: Venue, half: Half, chunk_size: int):
    chunk_to_chart = OrderedDict()
    for season in seasons:
        table = LeagueTable(season, half)
        table_map = table.group(chunk_size)

        for chunk_id in range(table_map.number_of_chunks()):
            if chunk_id not in chunk_to_chart:
                chart = DataUnit(Counter(),
                                 seasons,
                                 positions=table_map.get_rows(chunk_id))
                chunk_to_chart[chunk_id] = chart

            chart = chunk_to_chart[chunk_id]
            for row_id in table_map.get_rows(chunk_id):
                team = table[row_id].TEAM
                count_events(season, team, venue, half, func, negate, chart)

    return list(chunk_to_chart.values())
コード例 #4
0
def show_results(league: League, season: Season, results: List[str]):
    matched = []
    for fixture in season.fixtures():
        result = fixture.full_time()
        if result:
            for given_result in results:
                left, right = map(int, given_result.split('-'))
                if left == result.left and right == result.right:
                    matched.append(fixture)
        else:
            messages.warning_message('Ignoring {}'.format(fixture))

    if matched:
        table = LeagueTable(season, Half.both)
        print('>' * 40, season.year, '<' * 40)
        for fixture in matched:
            print('{:<2} vs {:<2}: {}'.format(
                table.team_position(fixture.home_team) + 1,
                table.team_position(fixture.away_team) + 1, fixture))
        print()
コード例 #5
0
ファイル: show_projection.py プロジェクト: abetts155/Projects
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)
コード例 #6
0
ファイル: show_matrix.py プロジェクト: abetts155/Projects
def fill_matrix(func: Callable, symmetry: bool, matrix: np.ndarray,
                table_map: TableMap, table: LeagueTable, half: Half):
    verbose_message('Filling matrix for season {}'.format(table.season))
    for fixture in table.season.fixtures():
        home_team_position = table.team_position(fixture.home_team)
        home_team_chunk_id = table_map.get_chunk(home_team_position)
        away_team_position = table.team_position(fixture.away_team)
        away_team_chunk_id = table_map.get_chunk(away_team_position)

        if half == Half.both:
            result = fixture.full_time()
        elif half == Half.first:
            result = fixture.first_half()
        elif half == Half.second:
            result = fixture.second_half()
        else:
            assert False

        if result:
            if func(result):
                matrix[home_team_chunk_id][away_team_chunk_id] += 1
                if symmetry:
                    matrix[away_team_chunk_id][home_team_chunk_id] += 1
コード例 #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:]

    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)
コード例 #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")

    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)
コード例 #9
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))
コード例 #10
0
ファイル: show_matrix.py プロジェクト: abetts155/Projects
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)