Skip to content

Commit

Permalink
Merge power rankings
Browse files Browse the repository at this point in the history
  • Loading branch information
cwendt94 committed Aug 9, 2019
2 parents c66c097 + c09af3d commit 61f8a34
Show file tree
Hide file tree
Showing 7 changed files with 100 additions and 4 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,13 @@ Team(Team 1)
>>> matchups[0].away_team
Team(Team 10)
```
### Get power rankings
```python
>>> from ff_espn_api import League
>>> league = League(1234, 2018)
>>> league.power_rankings(week=13)
[('70.85', Team(Team 7)), ('65.20', Team(Team 1)), ('62.45', Team(Team 8)), ('57.70', Team(THE KING)), ('45.10', Team(Team Mizrachi)), ('42.80', Team(Team 10)), ('40.65', Team(Team Viking Queen)), ('37.30', Team(Team 2)), ('27.85', Team(Team 5)), ('20.40', Team(FANTASY GOD))]
```

### Get box score of current/specific weel
```python
Expand Down
23 changes: 22 additions & 1 deletion ff_espn_api/league.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from .matchup import Matchup
from .pick import Pick
from .box_score import BoxScore
from .utils import power_points, two_step_dominance


def checkRequestStatus(status: int) -> None:
Expand Down Expand Up @@ -307,4 +308,24 @@ def box_scores(self, week: int = None) -> List[BoxScore]:
elif matchup.away_team == team.team_id:
matchup.away_team = team
return box_data


def power_rankings(self, week):
'''Return power rankings for any week'''

if week <= 0 or week > self.current_week:
week = self.current_week
# calculate win for every week
win_matrix = []
teams_sorted = sorted(self.teams, key=lambda x: x.team_id,
reverse=False)

for team in teams_sorted:
wins = [0]*32
for mov, opponent in zip(team.mov[:week], team.schedule[:week]):
opp = int(opponent.team_id)-1
if mov > 0:
wins[opp] += 1
win_matrix.append(wins)
dominance_matrix = two_step_dominance(win_matrix)
power_rank = power_points(dominance_matrix, teams_sorted, week)
return power_rank
4 changes: 3 additions & 1 deletion ff_espn_api/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ def __init__(self, data):
self.team_count = data['size']
self.playoff_team_count = data['scheduleSettings']['playoffTeamCount']
self.keeper_count = data['draftSettings']['keeperCount']
self.trade_deadline = data['tradeSettings']['deadlineDate']
self.trade_deadline = 0
if 'deadlineDate' in data['tradeSettings']:
self.trade_deadline = data['tradeSettings']['deadlineDate']
self.name = data['name']
self.tie_rule = data['scoringSettings']['matchupTieRule']
self.playoff_seed_tie_rule = data['scoringSettings']['playoffMatchupTieRule']
Expand Down
51 changes: 51 additions & 0 deletions ff_espn_api/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Helper functions for power rankings

def square_matrix(X):
'''Squares a matrix'''
result = [[0.0 for x in range(len(X))] for y in range(len(X))]

# iterate through rows of X
for i in range(len(X)):

# iterate through columns of X
for j in range(len(X)):

# iterate through rows of X
for k in range(len(X)):
result[i][j] += X[i][k] * X[k][j]

return result


def add_matrix(X, Y):
'''Adds two matrices'''
result = [[0.0 for x in range(len(X))] for y in range(len(X))]

for i in range(len(X)):

# iterate through columns
for j in range(len(X)):
result[i][j] = X[i][j] + Y[i][j]

return result


def two_step_dominance(X):
'''Returns result of two step dominance formula'''
matrix = add_matrix(square_matrix(X), X)
result = [sum(x) for x in matrix]
return result


def power_points(dominance, teams, week):
'''Returns list of power points'''
power_points = []
for i, team in zip(dominance, teams):
avg_score = sum(team.scores[:week]) / week
avg_mov = sum(team.mov[:week]) / week

power = '{0:.2f}'.format((int(i)*0.8) + (int(avg_score)*0.15) +
(int(avg_mov)*0.05))
power_points.append(power)
power_tup = [(i, j) for (i, j) in zip(power_points, teams)]
return sorted(power_tup, key=lambda tup: float(tup[0]), reverse=True)
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
setup(
name='ff_espn_api',
packages=['ff_espn_api'],
version='1.0.3',
version='1.0.4',
author='Christian Wendt',
description='Fantasy Football ESPN API',
install_requires=['requests>=2.0.0,<3.0.0'],
Expand Down
1 change: 0 additions & 1 deletion tests/unit/data/league_settings_2018.json
Original file line number Diff line number Diff line change
Expand Up @@ -629,7 +629,6 @@
"size": 10,
"tradeSettings": {
"allowOutOfUniverse": false,
"deadlineDate": 1543395600000,
"max": -1,
"revisionHours": 24,
"vetoVotesRequired": 5
Expand Down
16 changes: 16 additions & 0 deletions tests/unit/test_league.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,4 +195,20 @@ def test_box_score(self, m):

self.assertEqual(repr(box_scores[0].home_team), 'Team(Rollin\' With Mahomies)')
self.assertEqual(repr(box_scores[0].home_lineup[1]), 'Player(Christian McCaffrey, points:31, projected:23)')

@requests_mock.Mocker()
def test_power_rankings(self, m):
self.mock_setUp(m)

league = League(self.league_id, self.season)

invalid_week = league.power_rankings(0)
current_week = league.power_rankings(league.current_week)
self.assertEqual(invalid_week, current_week)

valid_week = league.power_rankings(13)
self.assertEqual(valid_week[0][0], '71.70')
self.assertEqual(repr(valid_week[0][1]), 'Team(Misunderstood Mistfits )')



0 comments on commit 61f8a34

Please sign in to comment.