def dump_predictions(league_id):
    manager = bot.ManagerBot(league_id=league_id)

    predictions = pd.read_csv(prediction_csv,
                        converters={"eligible_positions": lambda x: x.strip("[]").replace("'", "").split(", ")})
    predictions['league_id'] = league_id
    predictions.rename(columns={"id": "player_id"}, inplace=True)
    predictions.set_index('player_id', inplace=True)

    scored_categories = manager.lg.scoring_categories() # ["G", "A", "+/-", "PIM", "SOG", "FW", "HIT"]
    d_scored_categories = scored_categories.copy()
    # if FW are in cats, let's ignore them for D.  Keeps D fantasy score close relative to F 
    try:
        d_scored_categories.remove('FW')
    except ValueError:
        pass
    # d_scored_categories = ["G", "A", "+/-", "PIM", "SOG", "HIT"]
    es_colums = ["name", "position","team","preseason_rank","current_rank","fantasy_score","GP", "csh_rank", "league_id", "player_id"]
    def produce_csh_ranking(predictions, scoring_categories, selector):
        """Create ranking by summing standard deviation of each stat, summing, then dividing by num stats."""
        f_mean = predictions.loc[selector,scoring_categories].mean()
        f_std =predictions.loc[selector,scoring_categories].std()
        f_std_performance = (predictions.loc[selector,scoring_categories] - f_mean)/f_std
        for stat in scoring_categories:
            predictions.loc[selector, stat + '_std'] = (predictions[stat] - f_mean[stat])/f_std[stat]
        # predictions = predictions.join(f_std_performance, how='left', rsuffix='_std')
        predictions.loc[selector, 'fantasy_score'] = f_std_performance.sum(axis=1)/len(scoring_categories)
        # predictions.sort_values('fantasy_score', inplace=True,ascending=False)
        # sorted_predictions = predictions.reset_index().sort_values('fantasy_score', ascending=False, ignore_index=True)
        # sorted_predictions['csh_rank'] = sorted_predictions.index + 1
        return predictions
    # the bulk importer for ES can't handled NAN, so let's initialize to 0
    for stat in scored_categories:
            predictions.loc[:, stat + '_std'] = 0
    produce_csh_ranking(predictions, scored_categories, predictions['position'] != 'D')
    produce_csh_ranking(predictions, d_scored_categories, predictions['position'] == 'D')
    # predictions.sort_values('fantasy_score', inplace=True,ascending=False)
    sorted_predictions = predictions.reset_index().sort_values('fantasy_score', ascending=False, ignore_index=True)
    sorted_predictions['csh_rank'] = sorted_predictions.index + 1
    print(sorted_predictions.head(20))

    def filter_keys(document, columns):
        """Return dict as specified by colums list."""
        return {key: document[key] for key in columns}

    def doc_generator_linescores(player_predictions, categories):
        df_iter = player_predictions.iterrows()
        for index, player_prediction in df_iter:
            # game['timestamp'] = game['gameDate']
            # document['player_id'] = index
            yield {
                "_index": 'fantasy-nhl-preseason-predictions-2021',
                "_type": "_doc",
                "_id": f"{player_prediction['league_id']}-{player_prediction['player_id']}",
                "_source": filter_keys(player_prediction, categories + 
                                    [cat + "_std" for cat in categories] + 
                                    es_colums),
            }


    helpers.bulk(es, doc_generator_linescores(sorted_predictions, scored_categories))
    # helpers.bulk(es, doc_generator_linescores(ordinal_d_predictions, d_scored_categories))
    pass
Esempio n. 2
0
import logging
logging.basicConfig(level=logging.INFO)

pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

from elasticsearch import Elasticsearch
from elasticsearch import helpers

es = Elasticsearch(hosts='http://localhost:9200', http_compress=True)

stats = ['G','A','SOG','+/-','HIT','PIM','FW']
weights_series = pd.Series([1, .75, 1, .5, 1, .1, 1], index=stats)

week_number = 1
manager = bot.ManagerBot(week_number)

projections = manager.all_players[manager.all_players.position_type == 'P']
projections.reset_index(inplace=True)

projections = manager.pred_bldr.predict(projections)
projection_date = date(2020,3,8)
projections.loc[:, 'projection_date'] = projection_date
projections['timestamp'] = projection_date
player_projection_columns =['name','eligible_positions','team_id','team_name','projection_date','player_id','timestamp'] + stats


def filter_keys(document, columns):
    return {key: document[key] for key in columns}

Esempio n. 3
0
 def __init__(self, week):
     self.bot = bot.ManagerBot(week, league_id="403.l.18782")
import pandas as pd
import numpy as np
from datetime import datetime, timezone

from yahoo_fantasy_api import League
from csh_fantasy_bot import bot, nhl, roster_change_optimizer

import logging
logging.basicConfig(level=logging.INFO)

pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

from elasticsearch import Elasticsearch
from elasticsearch import helpers

week_number = 19

es = Elasticsearch(hosts='http://192.168.1.20:9200', http_compress=True)

manager: bot.ManagerBot = bot.ManagerBot(league_id="403.l.18782") #league_id=266295

league :League  = manager.lg


pass

            }

    helpers.bulk(es, doc_generator_team_results(data))


week_number = 5

league_id = '403.l.41177'
# league_id = "403.l.18782"

simulation_mode = False
manager: bot.ManagerBot = None
if 'YAHOO_OAUTH_FILE' in os.environ:
    auth_file = os.environ['YAHOO_OAUTH_FILE']
    manager = bot.ManagerBot(week_number,
                             oauth_file=auth_file,
                             league_id=league_id,
                             simulation_mode=simulation_mode)
else:
    manager = bot.ManagerBot(week_number,
                             league_id=league_id,
                             simulation_mode=simulation_mode)

my_team_id = manager.tm.team_key.split('.')[-1]

my_opponent_id = manager.opp_team_key
my_scores = manager.my_team.scores()
# print("My team has {} roster changes available.".format(manager.roster_changes_allowed))
# print("Scoring no roster changes:")
# print(my_scores.sum())

# Date: 2021-02-17, in: Adam Pelech(5756), out: Nazem Kadri(4687)
Esempio n. 6
0
import datetime
import logging
import pandas as pd

from csh_fantasy_bot import bot

pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

logger = logging.getLogger(__name__)

game_week = 17
mgr = bot.ManagerBot(week=game_week)

# what are days for this week matchup
(week_start, week_end) = mgr.lg.week_date_range(game_week)
week = pd.date_range(week_start, week_end)
# get opponent
opp_team_key = mgr.tm.matchup(game_week)
opp_team = mgr.lg.to_team(opp_team_key)

opp_team_2 = mgr.game_week().opponent
opp_scores = opp_team_2.scores()
# for days in week that have passed, lets load roster used and find stats
today = datetime.datetime.now()


def get_team_results(team):
    opp_daily_rosters = pd.DataFrame()
    for game_day in week:
        if today > game_day:
Esempio n. 7
0
import logging
logging.basicConfig(level=logging.INFO)

pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

from elasticsearch import Elasticsearch
from elasticsearch import helpers

es = Elasticsearch(hosts='http://192.168.1.20:9200', http_compress=True)

# league_id = "403.l.18782"
league_id = "411.l.85094"

manager: bot.ManagerBot = bot.ManagerBot(league_id=league_id)


class JsonLoggingYHandler(yhandler.YHandler):
    def __init__(self, sc):
        super().__init__(sc)
        self.num_players_picked = -1

    def get_draft_results(self, league_id):
        raw = super().get_draft_results(league_id)
        t = objectpath.Tree(raw)
        elems = t.execute('$..draft_result')
        num_drafted = 0
        for ele in elems:
            if 'player_key' in ele.keys():
                num_drafted += 1
from csh_fantasy_bot.config import ELASTIC_URL

pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

if 'YAHOO_OAUTH_FILE' in os.environ:
    oauth_file = os.environ['YAHOO_OAUTH_FILE']
else:
    oauth_file = 'oauth2.json'

es = Elasticsearch(hosts=ELASTIC_URL, http_compress=True)

league_id = '396.l.53432'
league_id = "403.l.18782"

manager = bot.ManagerBot(1,league_id=league_id)
lg = manager.lg
sc = lg.sc

teams = lg.teams()
roster_positions = lg.positions()
all_players = manager.all_players
# player_stats = manager.stat_categories
# weights_series = pd.Series([1, 1, .5, .5, 1, .1, .7], index=player_stats)
projected_player_stats = ['proj_{}'.format(stat) for stat in manager.stat_categories]
# player_projection_columns =['name','eligible_positions','team_id','team_name','game_date','player_id'] + player_stats


def filter_keys(document, columns):
    return {key: document[key] for key in columns}
Esempio n. 9
0
import pandas as pd
import numpy as np

from csh_fantasy_bot import bot

simulation_mode = False
week_number = 9
l_id = '411.l.85094'
# league_id = "403.l.18782"
manager = bot.ManagerBot(league_id=l_id,
                         week=week_number,
                         simulation_mode=simulation_mode)
league_scorer = manager.game_week().score_comparer

predictions = manager.game_week().all_player_predictions
print(predictions.head())


def display_sort_ftps(df, ascending=False):
    return df.sort_values('fpts', ascending=ascending)[[
        'name', 'eligible_positions', 'status', 'fantasy_status', 'fpts'
    ]]


rest_season_predictions = manager.game_week().all_player_predictions

my_team = rest_season_predictions[rest_season_predictions.fantasy_status == 8]
print(display_sort_ftps(my_team))

print(my_team[[
    'name', 'eligible_positions', 'G', 'A', 'HIT', 'SOG', 'fantasy_status',