def results_summary(season_elo_ratings_list, scaling=100000):
    """
    Based on a set of ratings (in team, rating, year format)
    print out the best and worst teams for that season.

    Parameters
    ----------
    season_elo_ratings_list : TYPE
        DESCRIPTION.
    scaling : TYPE, optional
        DESCRIPTION. The default is 100000.

    Returns
    -------
    None.

    """
    print_list = []

    for i, r in enumerate(season_elo_ratings_list):
        rtg = float(r[0] * scaling)
        team = team_abbreviation(i + 1)
        print_list.append([rtg, team])

    print_list = sorted(print_list, key=lambda x: -x[0])
    top_list = print_list[0:10]
    bottom_list = print_list[21:30]
    print("Top 10 teams for the season ending in " + str(season_year) + ":")
    for t in top_list:
        rating = "%.1f" % t[0]
        print(t[1] + ": " + rating)
    print("Bottom 10 teams for the season ending in " + str(season_year) + ":")
    for t in bottom_list:
        rating = "%.1f" % t[0]
        print(t[1] + ": " + rating)
    spread = print_list[0][0] - print_list[29][0]
    spread_string = "%.1f" % spread
    print("Max spread is: " + spread_string)

    return
Exemple #2
0
    end = min(datetime(season_year, 5, 30),datetime.today() - timedelta(days=1))
else:
    a = datetime(season_year - 1, 10, 1)
    b = datetime(season_year - 1, 11, 15)
    end = min(datetime(season_year, 4, 30), datetime.today() - timedelta(days=1))


# Python Moving Average, taken by:
# https://stackoverflow.com/questions/13728392/moving-average-or-running-mean
# note that there's a faster version using pandas but NO PANDAS.
def running_mean(x, N):
    cumsum = np.cumsum(np.insert(x, 0, 0))
    return (cumsum[N:] - cumsum[:-N]) / N


team_labels = [team_abbreviation(i) for i in range(1, 30)]

# Team ID
# Possible divisions are Southeast, Atlantic, Central
# Pacific, Southwest, Northwest
print("Divisions are as follows: ")
print(" 1: Atlantic \n 2: Central \n 3: Southeast \n 4: Southwest \n 5: Pacific \n 6: Northwest")
dn = input("Please select a division: ")

try:
    division_number = int(dn)-1
except:
    print("invalid input for division number, not integer")
    sys.exit(1)
try:
    division_name = division_name_list[division_number]
from nba_database.queries import team_abbreviation

for team_id in range(1, 31):
    conn = sqlite3.connect("nba_data.sqlite")
    query = "SELECT datetime,elo_rating FROM nba_team_elo_data where team_id = " + str(
        team_id)

    df = pd.read_sql_query(query, conn)

    df["datetime"] = pd.to_datetime(df["datetime"], unit="s")

    # get the appropriate colours
    cursor = conn.cursor()
    cursor.execute(
        "SELECT primary_color from pro_api_teams where bball_ref_id=" +
        str(team_id))
    s = cursor.fetchall()

    plt.plot(
        df["datetime"],
        df["elo_rating"].rolling(41).mean(),
        label="41 game moving avg.",
        color=s[0][0],
    )
    plt.xticks(rotation=45)
    plt.legend()
    plt.title("Elo rating history of " + team_abbreviation(team_id))
    plt.show()

    time.sleep(3)
               home_team_adv=home_team_adv,
               win_floor=win_floor)

elo_list = elo_ratings_list(epochtime(end_datetime))

form_list = [form_query(i) for i in range(1, 31)]

lpw_results.sort(key=lambda x: x[0])

results = list(zip(lpw_results, srs_list, wins_list, elo_list, form_list))

results = [[x[0][0], x[0][1], x[1], x[2][0], x[2][1], x[2][2], x[3], x[4]]
           for x in results]

results_tuples = [(
    team_abbreviation(x[0]),
    round(x[1], 0),
    round(x[2] * 100.0 / 100.0, 3),
    x[6],
    x[3],
    x[4],
    x[5],
    x[7],
) for x in results]

results_tuples.sort(key=lambda x: -x[2])

results_table = tabulate(
    results_tuples,
    headers=[
        "Team",
def season_elo_calc(_analysis_list, previous_ratings=None, new_season=True):
    """
    Based on a series of games provided in
    [away id, away pts, home id, home pts]
    format, previous ratings (if applicable),
    and if a previous iteration is being used
    return both the final ratings and a continuous set of ratings
    for the entire season.

    Parameters
    ----------
    _analysis_list : TYPE
        DESCRIPTION.
    previous_ratings : TYPE, optional
        DESCRIPTION. The default is None.
    new_season : TYPE, optional
        DESCRIPTION. The default is True.

    Returns
    -------
    season_elo_ratings_list : TYPE
        DESCRIPTION.
    list_of_ratings : TYPE
        DESCRIPTION.

    """

    default_rating = DEFAULT_RATING  # 1 gives good results.
    rating_scaling = 10  # 10 gives good spread
    default_K = default_rating / rating_scaling

    if new_season == True:
        season_elo_ratings_list = default_rating * np.ones((30, 1))
    else:
        season_elo_ratings_list = previous_ratings

    # create a list of ratings to return and store the first ratings set
    list_of_ratings = []
    initial_date = _analysis_list[0][4]  # first entry, first date
    season_year = analysis_list[0][5]
    for i, z in enumerate(season_elo_ratings_list):
        rd = {}  # ratings_dict
        rd["team_id"] = i + 1
        rd["team_abbreviation"] = team_abbreviation(rd["team_id"])
        rd["elo_rating"] = z[0] * 100000
        rd["datetime"] = initial_date
        rd["season_year"] = season_year
        list_of_ratings.append(rd)

    for g in _analysis_list:

        # get previous elo ratings
        away_rating = season_elo_ratings_list[g[0] - 1]
        home_rating = season_elo_ratings_list[g[2] - 1]
        # get expected DoS value, compare it to the real one
        expected_dos = predicted_dos_formula(away_rating, home_rating)
        actual_dos = (g[1] - g[3]) / (g[1] + g[3])
        dos_difference = actual_dos - expected_dos
        # adjust ratings
        change_factor = default_K * dos_difference
        season_elo_ratings_list[g[0] - 1] = (
            season_elo_ratings_list[g[0] - 1] + change_factor
        )
        season_elo_ratings_list[g[2] - 1] = (
            season_elo_ratings_list[g[2] - 1] - change_factor
        )
        # add the date and then add the new ratings to the list of ratings
        cur_date = g[4]
        list_of_ratings.append(
            {
                "team_id": g[0],
                "elo_rating": season_elo_ratings_list[g[0] - 1][0] * 100000,
                "datetime": cur_date,
                "season_year": season_year,
                "team_abbreviation": team_abbreviation(g[0]),
            }
        )
        list_of_ratings.append(
            {
                "team_id": g[2],
                "elo_rating": season_elo_ratings_list[g[2] - 1][0] * 100000,
                "datetime": cur_date,
                "season_year": season_year,
                "team_abbreviation": team_abbreviation(g[2]),
            }
        )

    print(
        "Final set of Elo ratings after season "
        + str(season_year)
        + " presented below."
    )

    return season_elo_ratings_list, list_of_ratings