Beispiel #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))
def main(args: Namespace):
    load_teams(args.database)

    leagues = []
    if args.country:
        for country in args.country:
            leagues.extend([
                code for code, league in league_register.items()
                if league.country == country.capitalize()
            ])

    if args.league:
        leagues.extend(list(args.league))

    if not args.country and not args.league:
        leagues.extend(list(league_register.keys()))

    for league_code in leagues:
        league = league_register[league_code]
        load_league(args.database, league)

        seasons = Season.seasons(league)
        if not seasons:
            messages.warning_message("No season data found")
        else:
            if args.history:
                seasons = seasons[-args.history:]

            if seasons[-1].current:
                this_season = seasons.pop()

                if args.team:
                    teams = []
                    for team_name in get_multiple_teams(args):
                        (row, ) = extract_picked_team(args.database, team_name,
                                                      league)
                        team = Team.inventory[row[0]]
                        teams.append(team)
                else:
                    teams = this_season.teams()

                events = [Event.get(event) for event in args.event]
                historical_data = {}
                for event in events:
                    historical_data[event] = DataUnit(Counter(), seasons)
                    for season in seasons:
                        for team in season.teams():
                            count_events(season, team, args.venue, args.half,
                                         event, args.negate,
                                         historical_data[event])

                analyse_teams(args, league, seasons, this_season, teams,
                              historical_data)
            else:
                messages.error_message(
                    "The current season has not yet started")
Beispiel #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")

    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)
Beispiel #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 not seasons:
        messages.error_message("No season data found")

    for season in seasons:
        show_results(league, season, args.results)
Beispiel #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 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)
Beispiel #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 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)
Beispiel #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)
Beispiel #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 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)
Beispiel #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")

    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)
Beispiel #10
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)
Beispiel #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)
Beispiel #12
0
def main(args: Namespace):
    load_teams(args.database)

    func = Event.get(get_unique_event(args))
    train_data = []
    train_history = []
    for code in args.league:
        league = league_register[code]
        load_league(args.database, league)

        seasons = Season.seasons(league)
        *seasons, _ = seasons
        collect_data(seasons, func, train_data, train_history)

    dependent_variable = Event.name(func, False)
    df = pd.DataFrame.from_records(train_data)
    cols = []
    for x in HistorySummary.__slots__:
        cols.extend(['H({})'.format(x), 'A({})'.format(x)])
    cols.append(dependent_variable)
    df.columns = cols

    plt.figure()

    y_train = df[dependent_variable]
    x_train = df.drop([dependent_variable], axis=1)

    rf = RandomForestClassifier()
    rf.fit(x_train, y_train)
    print("Features sorted by their score:")
    print(
        sorted(zip(map(lambda x: round(x, 4), rf.feature_importances_),
                   x_train),
               reverse=True))

    model = RandomForestClassifier()
    # Fit the model
    model.fit(x_train, y_train)
    # Accuracy
    score = model.score(x_train, y_train)
    print(score)

    test_data = []
    test_history = []
    for code in args.league:
        league = league_register[code]
        load_league(args.database, league)

        seasons = Season.seasons(league)
        *_, this_season = seasons
        collect_data([this_season], func, test_data, test_history)

    df = pd.DataFrame.from_records(test_data)
    cols = []
    for x in HistorySummary.__slots__:
        cols.extend(['H({})'.format(x), 'A({})'.format(x)])
    cols.append(dependent_variable)
    df.columns = cols

    y_test = df[dependent_variable]
    x_test = df.drop([dependent_variable], axis=1)

    predicted = list(model.predict(x_test))

    true_positives = []
    true_negatives = []
    false_positives = []
    false_negatives = []
    for i in range(len(y_test)):
        if y_test[i] and predicted[i]:
            true_positives.append(test_history[i])
        elif not y_test[i] and not predicted[i]:
            true_negatives.append(test_history[i])
        elif not y_test[i] and predicted[i]:
            false_positives.append(test_history[i])
        elif y_test[i] and not predicted[i]:
            false_negatives.append(test_history[i])

    print()

    print('>>>>>>>>>>>>>>>>>>> True positives')
    for fixture in true_positives:
        print(fixture)

    print()

    print('>>>>>>>>>>>>>>>>>>> True negatives')
    for fixture in true_negatives:
        print(fixture)

    print()

    print('>>>>>>>>>>>>>>>>>>> False positives')
    for fixture in false_positives:
        print(fixture)

    print()

    print('>>>>>>>>>>>>>>>>>>> False negatives')
    for fixture in false_negatives:
        print(fixture)

    print('TP={}  TN={}  FP={}  FN={}'.format(len(true_positives),
                                              len(true_negatives),
                                              len(false_positives),
                                              len(false_negatives)))
Beispiel #13
0
        elif event == event_matrix_submit.Key:
            run_event_matrix_analysis(values)
        elif event == league_analysis_submit.Key:
            run_league_analysis(values)
        elif event in [performance_individual.Key, performance_average.Key]:
            performance_positions_choice.update(disabled=True)
            performance_relative_choice.update(disabled=True)
        elif event == performance_positions.Key:
            performance_positions_choice.update(disabled=False)
            performance_relative_choice.update(disabled=True)
        elif event == performance_relative.Key:
            performance_positions_choice.update(disabled=True)
            performance_relative_choice.update(disabled=False)
        elif event == team_analysis_summary.Key:
            team_analysis_game_states.update(disabled=False)
        elif event in [
                team_analysis_form.Key, team_analysis_margins.Key,
                team_analysis_goals.Key
        ]:
            team_analysis_game_states.update(disabled=True)
        elif event == expression.Key:
            run_expression_evaluation(values)


if __name__ == '__main__':
    theme('DarkBlue')
    load_teams(database)
    window = make()
    run(window)
    window.close()
Beispiel #14
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)