Exemplo n.º 1
0
    def test_risk_too_high(self):
        players = pd.read_csv(self.test_file).set_index('Player Code')

        risk=2
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            with self.assertRaisesRegex(Exception, f'The risk argument has to be between 0 and 1 but is {risk}.'):
                optimiser.get_optimal_team(players, (2, 5, 5, 3), budget=100.0, optimise_team_on='Expected Points Next 5 GWs', optimise_sel_on='Expected Points Next GW', risk=risk)
Exemplo n.º 2
0
    def test_budget_too_low(self):
        players = pd.read_csv(self.test_file).set_index('Player Code')

        budget=70.0
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            with self.assertRaisesRegex(Exception, f'An optimal solution within the max_budget could not be found.'):
                optimiser.get_optimal_team(players, (2, 5, 5, 3), budget=budget, optimise_team_on='Expected Points Next 5 GWs', optimise_sel_on='Expected Points Next GW')
Exemplo n.º 3
0
    def test_optimal_team_include_exclude(self):
        players = pd.read_csv(self.test_file).set_index('Player Code')

        budget=100.0
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            team = optimiser.get_optimal_team(players, (2, 5, 5, 3), budget=budget, optimise_team_on='Expected Points Next 5 GWs', optimise_sel_on='Expected Points Next GW', include=['Mané'], exclude=['Ederson'], risk=1)

        self.__assert_team(team, budget)
        self.assertListEqual(list(team['Name'].values), ['Kelly', 'Alderweireld', 'Walker', 'Ward', 'Alexander-Arnold', 'Ayew', 'Abraham', 'Firmino', 'Whiteman', 'Lloris', 'Kovacic', 'Mount', 'David Silva', 'Mané', 'De Bruyne'])
Exemplo n.º 4
0
    def test_optimal_team_expens_player_count(self):
        players = pd.read_csv(self.test_file).set_index('Player Code')

        budget=100.0
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            team = optimiser.get_optimal_team(players, formation=(2, 5, 5, 3), expens_player_count=11, budget=budget, optimise_team_on='Expected Points Next 5 GWs', optimise_sel_on='Expected Points Next GW', risk=1)

        self.__assert_team(team, budget)

        self.assertListEqual(list(team['Name'].values), ['Walker-Peters', 'Kelly', 'Ward', 'van Aanholt', 'Alexander-Arnold', 'Abraham', 'Firmino', 'Agüero', 'Whiteman', 'Lloris', 'McArthur', 'Wijnaldum', 'Mount', 'David Silva', 'De Bruyne'])
        self.assertTrue(team[team['Name'] == 'Agüero']['Captain?'].iloc[0])
        self.assertTrue(team[team['Name'] == 'De Bruyne']['Vice Captain?'].iloc[0])
Exemplo n.º 5
0
    def test_optimal_team_low_risk(self):
        players = pd.read_csv(self.test_file).set_index('Player Code')

        budget=100.0
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            team = optimiser.get_optimal_team(players, (2, 5, 5, 3), budget=budget, optimise_team_on='Expected Points Next 5 GWs', optimise_sel_on='Expected Points Next GW', risk=0)

        self.__assert_team(team, budget)

        self.assertListEqual(list(team['Name'].values), ['Kelly', 'Alderweireld', 'Ward', 'van Aanholt', 'Alexander-Arnold', 'Origi', 'Abraham', 'Firmino', 'Lloris', 'Ederson', 'Kovacic', 'Son', 'Mount', 'David Silva', 'De Bruyne'])
        self.assertTrue(team[team['Name'] == 'De Bruyne']['Captain?'].iloc[0])
        self.assertTrue(team[team['Name'] == 'Abraham']['Vice Captain?'].iloc[0])

        self.assertListEqual(list(team[team['Selected?'] == True]['Name'].values),  ['Alderweireld', 'Ward', 'van Aanholt', 'Alexander-Arnold', 'Abraham', 'Firmino', 'Ederson', 'Son', 'Mount', 'David Silva', 'De Bruyne'])
Exemplo n.º 6
0
    def test_recommend_transfer(self):
        players = pd.read_csv(self.test_file).set_index('Player Code')

        budget = 100.0
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            team = optimiser.get_optimal_team(players, (2, 5, 5, 3), budget=budget, optimise_team_on='Expected Points Next 5 GWs', optimise_sel_on='Expected Points Next GW', recommend=2)

        self.assertEqual(team.shape[0], 17, msg='Row count must be 17.')

        new_team = team[lambda df: df['Recommendation'] != 'Transfer out']
        position_counts = new_team[['Field Position', 'Name']].groupby('Field Position').count()['Name'].to_dict()
        self.assertDictEqual(position_counts, {'DEF': 5, 'FWD': 3, 'GK': 2, 'MID': 5}, msg='Team composition incorrect.')
        self.assertListEqual(list(new_team['Name'].values), ['Kelly', 'Alderweireld', 'Ward', 'van Aanholt', 'Alexander-Arnold', 'Origi', 'Abraham', 'Firmino', 'Lloris', 'Ederson', 'Kovacic', 'Son', 'Mount', 'David Silva', 'De Bruyne'])
        self.assertLessEqual(new_team['Current Cost'].sum(), budget)
        self.assertGreaterEqual(new_team['Current Cost'].sum(), budget*0.95)

        out_players = team[lambda df: df['Recommendation'] == 'Transfer out']
        self.assertListEqual(list(out_players['Name'].values),  ['Matip', 'Ayew'])

        in_players = team[lambda df: df['Recommendation'] == 'Transfer in']
        self.assertListEqual(list(in_players['Name'].values), ['van Aanholt', 'Origi'])
Exemplo n.º 7
0
def display_optimal_team(players_df: DF,
                         ctx: Context,
                         formation: Tuple[int] = (2, 5, 5, 3),
                         expens_player_count: int = None,
                         budget: float = 100.0,
                         optimise_team_on: str = 'Total Points',
                         optimise_sel_on: str = None,
                         recommend: int = None,
                         include: Tuple[str] = (),
                         exclude: Tuple[str] = (),
                         risk: float = 0.2) -> DF:
    """
    For the given formation and player data frame tries to maximise the total in the given column so that
    the current cost is with the given max_budget. It also adds the ``Captain/Vice Captain`` column to indicate whether a specific player
    should be captain or vice captain.

    Args:
        players_df: Player data frame with at least the following columns: ``Current Cost``, ``News And Date``, ``Field Position``, ``Player Team ID`` and the column specified in ``optimise_on``.
            If ``recommend`` is specified, the ``Selected?`` column must also be specified.
        formation: The formation to optimise, e.g, (2, 5, 5, 3) means 2 goal keepers, 5 defender, 5 mid fielders and 3 forwards.
        expens_player_count: Number of expensive players in a biased, optimised team. The number of players must be equal or less than the number of players in the formation if the formation is specified.
        If not specified, the optimised team will not be biased towards more expensive players. Biasing a team can be useful if you are unlikely to need bench players, e.g. for a free hit.
        budget: Budget that the sum of the team player's ``Current Cost`` should not exceed.
        optimise_team_on: Column in ``players`` to use to optimise the team composition, e.g. ``Expected Points Next 5 GWs``.
            This is different to ``optimise_sel_on`` because the match team selection should be based on the short term where as the team composition should be based on the long term.
        optimise_sel_on: Column in ``players`` to use to optimise the team selection.
        recommend: Number of players to recommend transfers for. If specified, ``players`` has to include ``Selected?`` to indicate the current squad selection.
        include: List of player names that must be in the optimised team.
        exclude: List of player names that must NOT be in the optimised team.
        risk: Amount of risk to take when evaluating the column to optimise on. This number has to be between 0 and 1.
            The lower the numbers, the lower the risk. If risk is 1, the completeness of the data that the values in the optimisation columns is based on
            is completely ignored. If risk is 0, the values in the optimisation columns is multiplied by the completeness of the data.
            If risk is between 0 and 1 the completeness of the data is take into account in a way that is proportionate to the risk.

    Returns:
        The players from ``players`` with the highest value in the ``optimise_on`` column for the given formation that is within the max_budget.
    """
    new_team = (
        get_optimal_team(
            players_df,
            optimise_team_on=
            optimise_team_on,  # Name of the column to use for optimising the whole team.
            optimise_sel_on=
            optimise_sel_on,  # Name of the column to use for optimising the selection of the team.
            formation=
            formation,  # Formation of the team in format GKP-DEF-MID-FWD.
            expens_player_count=
            expens_player_count,  # Number of expensive players. A number between 14 and 11 will bias the team towards more expensive players.
            budget=
            budget,  # Maximum max_budget available for optimising the team.
            include=
            include,  # List of player names that must be in the team, e.g. ['De Bruyne', 'Mané']
            exclude=
            exclude,  # List of player names that must NOT be in the team.
            recommend=recommend,
            risk=risk
        )  # The amount of risk to take when evaluating the column to optimise on. This number has to be between 0 and 1.
        .pipe(ctx.dd.reorder))

    has_in_team = 'In Team?' in new_team.columns
    current_team = players_df[
        lambda df: df['In Team?'] == True] if has_in_team else None
    return display_team(new_team, current_team, ctx, has_in_team,
                        [optimise_sel_on, optimise_team_on])
Exemplo n.º 8
0
    def test_optimal_team_include_invalid_name(self):
        players = pd.read_csv(self.test_file).set_index('Player Code')

        with self.assertRaisesRegex(ValueError, r'\[\'Marc Maier\'\] in include is not in the Name column of players.'):
            optimiser.get_optimal_team(players, (2, 5, 5, 3), budget=100.0, optimise_team_on='Expected Points Next 5 GWs', optimise_sel_on='Expected Points Next GW', include=['Marc Maier'])
Exemplo n.º 9
0
 def test_player_df_invalid_with_recommend(self):
     with self.assertRaisesRegex(ValueError, "'Current Cost', 'News And Date', 'Field Position', 'Player Team Code', 'Stats Completeness Percent', 'Expected Points Next 5 GWs', 'Expected Points Next GW', 'In Team\?', 'Expected Points Next GW'"):
         optimiser.get_optimal_team(pd.DataFrame(), (2, 5, 5, 3), budget=100.0, optimise_team_on='Expected Points Next 5 GWs', optimise_sel_on='Expected Points Next GW', recommend=2)
Exemplo n.º 10
0
 def test_player_formation_invalid(self):
     players = pd.read_csv(self.test_file).set_index('Player Code')
     with self.assertRaisesRegex(ValueError, 'is not a subset of the maximum formation'):
         optimiser.get_optimal_team(players, (2, 6, 5, 3), budget=100.0, optimise_team_on='Expected Points Next 5 GWs', optimise_sel_on='Expected Points Next GW')
Exemplo n.º 11
0
    def test_optimal_team_nan_in_optimise_sel_on(self):
        players = pd.read_csv(self.test_file).set_index('Player Code')
        players.at[526, 'Expected Points Next GW'] = np.nan

        with self.assertRaisesRegex(ValueError, r'At least on of the entries in the Expected Points Next GW column of the players data frame is NaN. The Expected Points Next GW must be set for all players.'):
            optimiser.get_optimal_team(players, (2, 5, 5, 3), budget=100.0, optimise_team_on='Expected Points Next 5 GWs', optimise_sel_on='Expected Points Next GW')
Exemplo n.º 12
0
    def test_optimal_team_expens_player_count_too_many(self):
        players = pd.read_csv(self.test_file).set_index('Player Code')

        with self.assertRaisesRegex(ValueError, r'must be greater or equal to the number of the players in the expensive team'):
            team = optimiser.get_optimal_team(players, formation=(2, 5, 5, 3), expens_player_count=16, budget=100.0, optimise_team_on='Expected Points Next 5 GWs', optimise_sel_on='Expected Points Next GW', risk=1)