### Install the application from source Source: https://github.com/spilchen/yahoo_fantasy_bot/blob/master/README.rst Clone the repository and install dependencies within a virtual environment. ```bash git clone https://github.com/spilchen/yahoo_fantasy_bot.git cd yahoo_fantasy_bot virtualenv --python=python3.7 env source env/bin/activate pip install -r requirements.txt pip install -e . ``` -------------------------------- ### Run the setup wizard Source: https://github.com/spilchen/yahoo_fantasy_bot/blob/master/README.rst Initialize the configuration file and OAuth credentials using your Yahoo API consumer key and secret. ```bash ybot_setup -k -s oauth2.json my.cfg ``` -------------------------------- ### Install Yahoo! Fantasy Bot Source: https://context7.com/spilchen/yahoo_fantasy_bot/llms.txt Installation instructions for setting up the bot via PyPI or from the source repository. ```bash # Install from PyPI pip install yahoo-fantasy-bot # Or install from source git clone https://github.com/spilchen/yahoo_fantasy_bot.git cd yahoo_fantasy_bot virtualenv --python=python3.7 env source env/bin/activate pip install -r requirements.txt pip install -e . ``` -------------------------------- ### Install the package via pip Source: https://github.com/spilchen/yahoo_fantasy_bot/blob/master/README.rst Install the bot directly using the Python package manager. ```bash pip install yahoo-fantasy-bot ``` -------------------------------- ### Configure Bot with Setup Wizard Source: https://context7.com/spilchen/yahoo_fantasy_bot/llms.txt Initialize the configuration file by authenticating with Yahoo! OAuth and selecting league parameters. ```bash # First, get your API credentials from https://developer.yahoo.com/apps/create # Request read and write access for roster modifications # Run the setup wizard with your consumer key and secret ybot_setup -k YOUR_CONSUMER_KEY -s YOUR_CONSUMER_SECRET oauth2.json my_league.cfg # Interactive prompts will ask for: # - Sport code (mlb or nhl) # - Year # - League selection from your joined leagues # - Stat projection source (Yahoo! stats or CSV) # Example session output: # Available sport codes: # - mlb # - nhl # Enter the sport code: nhl # Enter the year: 2024 # List of league IDs you have joined: # 0 - My Hockey League 403.l.12345 # Pick a league from the above list (0 - 0): 0 # Choose source for stat projections: # 1 - Yahoo! # 2 - CSV manually downloaded from fangraphs.com ``` -------------------------------- ### Sample execution output Source: https://github.com/spilchen/yahoo_fantasy_bot/blob/master/README.rst Example output showing the bot evaluating trades and optimizing a hockey lineup. ```text $> ybot hockey.cfg Evaluating trades Adjusting lineup for player status Optimizing open lineup spots using available free agents 100%|################################################################################################################| Optimizing lineup using players available from bench 100%|################################################################################################################| Optimized lineup B : WK_G G/A/PPP/SOG/PIM C : Aleksander Barkov 3 38.0/63.0/32.0/241.0/10.0 C : Brayden Point 3 38.0/55.0/38.0/223.0/26.0 LW : Andrei Svechnikov 3 30.0/25.0/12.0/261.0/72.0 LW : Evander Kane 4 31.0/26.0/12.0/279.0/132.0 RW : David Pastrnak 3 44.0/53.0/39.0/281.0/40.0 RW : Alexander Radulov 3 28.0/45.0/24.0/212.0/64.0 D : Tyson Barrie 3 13.0/44.0/24.0/191.0/30.0 D : Thomas Chabot 3 15.0/43.0/15.0/197.0/36.0 D : P.K. Subban 4 12.0/40.0/16.0/174.0/70.0 D : Aaron Ekblad 3 14.0/25.0/11.0/186.0/55.0 G : WK_G W/SV% G : Ben Bishop 3 31.0/0.922 G : Connor Hellebuyck 3 36.0/0.916 Bench Jeff Skinner Patrice Bergeron ``` -------------------------------- ### Execute the bot Source: https://github.com/spilchen/yahoo_fantasy_bot/blob/master/README.rst Run the bot using a previously generated configuration file. ```bash ybot ``` -------------------------------- ### Configure Genetic Algorithm Optimizer Source: https://context7.com/spilchen/yahoo_fantasy_bot/llms.txt Configure the genetic algorithm parameters for lineup optimization via the lineup_optimizer module. ```python from yahoo_fantasy_bot.lineup_optimizer import optimize_with_genetic_algorithm # The optimizer is typically called internally by ManagerBot # Direct usage requires setting up the score_comparer and roster_bldr # Configuration parameters in config file: # [LineupOptimizer] # generations=250 # Number of generations to evolve # initialPopulationSize=24 # Starting lineup population # tournamentParticipants=4 # Selection tournament size (power of 2) # numOffspring=6 # Children per mating pair # mutationPct=10 # Chance of gene mutation (0-100) # minPctOwned=10 # Minimum ownership % to consider player # lockPlayersAbovePctOwn=80 # Lock players above this ownership % # The algorithm works as follows: # 1. Generate initial population of random valid lineups # 2. Score each lineup against opponent using standard deviation method # 3. Tournament selection picks best lineups for mating # 4. Crossover combines genes (players) from two parent lineups # 5. Mutation randomly swaps players with free agents # 6. Repeat for N generations # 7. Return best scoring lineup ``` -------------------------------- ### Execute Bot Operations Source: https://context7.com/spilchen/yahoo_fantasy_bot/llms.txt Run the bot using the configuration file to perform lineup optimizations and roster changes. ```bash # Dry run mode (preview changes without applying) ybot my_league.cfg # Apply roster changes to Yahoo! ybot --apply my_league.cfg # Full lineup optimization (evaluates all players, may cause roster churn) ybot --apply --full my_league.cfg # Apply changes automatically without confirmation prompts ybot --apply --assumeyes my_league.cfg # Custom number of optimization generations (more = better but slower) ybot --apply --generations 500 my_league.cfg # Reset cache before running (required after changing stat sources) ybot --apply --resetcache my_league.cfg # Include day-to-day (DTD) players in lineup considerations ybot --apply --ignorestatus my_league.cfg # Example output: # Evaluating trades # Adjusting lineup for player status # Optimizing open lineup spots using available free agents # 100%|################################################| # Optimizing lineup using players available from bench # 100%|################################################| # Optimized lineup # B : WK_G G/A/PPP/SOG/PIM # C : Aleksander Barkov 3 38.0/63.0/32.0/241.0/10.0 # C : Brayden Point 3 38.0/55.0/38.0/223.0/26.0 # ... # Computing roster moves to apply # Move Sidney Crosby to IR # Add Brayden Point and drop Anthony Mantha ``` -------------------------------- ### Optimize Lineups with ManagerBot Source: https://context7.com/spilchen/yahoo_fantasy_bot/llms.txt Automate lineup adjustments, including injury management and free agent optimization, using the ManagerBot class. ```python from yahoo_fantasy_bot.bot import ManagerBot import configparser cfg = configparser.RawConfigParser( converters={'list': lambda x: [i.strip() for i in x.split(',')]} ) cfg.read('my_league.cfg') bot = ManagerBot(cfg, reset_cache=False, ignore_status=False) # Move injured players to IR slots bot.pick_injury_reserve() # Remove players with status issues (DTD, SUSP, etc.) from starting lineup bot.move_non_available_players() # Move players recovered from IL back to bench bot.move_recovered_il_to_bench() # Remove any manually excluded players bot.remove_excluded_players() # Option 1: Optimize using free agents (may add/drop players) lineup_improved = bot.optimize_lineup_from_free_agents() print(f"Lineup improved from free agents: {lineup_improved}") # Option 2: Fill empty spots from bench first, then free agents bot.fill_empty_spots_from_bench() bot.fill_empty_spots() # Option 3: Optimize using only current roster (bench swaps only) bot.optimize_lineup_from_bench() # Pick bench players after optimization bot.pick_bench() # Display the optimized roster bot.print_roster() ``` -------------------------------- ### Manage Rosters with Container and Builder Source: https://context7.com/spilchen/yahoo_fantasy_bot/llms.txt Handle roster constraints and player selection using the roster module's Container and Builder classes. ```python from yahoo_fantasy_bot.roster import Container, Builder, PlayerSelector import pandas as pd # Builder handles position constraints from league settings positions = ['C', 'C', 'LW', 'LW', 'RW', 'RW', 'D', 'D', 'D', 'D', 'G', 'G'] roster_bldr = Builder(positions) # Get maximum players allowed max_players = roster_bldr.max_players() print(f"Roster size: {max_players}") # Container holds the actual roster with stat tracking roster = Container(cfg) # Add a player (must have 'eligible_positions' and 'selected_position') player = { 'name': 'Connor McDavid', 'player_id': 12345, 'eligible_positions': ['C', 'LW'], 'selected_position': 'C', 'percent_owned': 100 } roster.add_player(player) # Fit a player to available position slot new_player = pd.Series({ 'name': 'Auston Matthews', 'player_id': 12346, 'eligible_positions': ['C'], 'selected_position': None, 'percent_owned': 99 }) try: roster = roster_bldr.fit_if_space(roster, new_player) print("Player added successfully") except LookupError: print("No space for player on roster") # PlayerSelector for ranking and selecting from player pool player_pool_df = pd.DataFrame([...]) # DataFrame of available players selector = PlayerSelector(player_pool_df) selector.rank(['G', 'A', 'PPP']) # Rank by goals, assists, power play points # Iterate through ranked players for player in selector.select(): print(f"{player['name']}: {player['rank']}") # Or shuffle for random selection selector.shuffle() ``` -------------------------------- ### Orchestrate Workflow with Automation Driver Source: https://context7.com/spilchen/yahoo_fantasy_bot/llms.txt Use the Driver class to execute the full automation workflow including trade evaluation and roster optimization. ```python from yahoo_fantasy_bot.automation import Driver import configparser cfg = configparser.RawConfigParser( converters={'list': lambda x: [i.strip() for i in x.split(',')]} ) cfg.read('my_league.cfg') # Initialize the automation driver # dry_run: If True, preview changes without applying # full: If True, optimize entire lineup (more churn) # prompt: If True, confirm each roster move # reset_cache: If True, clear all cache files # ignore_status: If True, include DTD players in lineup driver = Driver( cfg, dry_run=True, full=False, prompt=False, reset_cache=False, ignore_status=False ) # Run the complete automation workflow driver.run() ``` -------------------------------- ### Apply Roster Changes Source: https://context7.com/spilchen/yahoo_fantasy_bot/llms.txt Commit optimized lineup changes to Yahoo! with options for dry runs and confirmation prompts. ```python from yahoo_fantasy_bot.bot import ManagerBot import configparser cfg = configparser.RawConfigParser( converters={'list': lambda x: [i.strip() for i in x.split(',')]} ) cfg.read('my_league.cfg') bot = ManagerBot(cfg, reset_cache=False, ignore_status=False) # Run optimization steps bot.pick_injury_reserve() bot.move_non_available_players() bot.fill_empty_spots() bot.pick_bench() bot.optimize_lineup_from_bench() # Preview roster moves (dry run) bot.apply_roster_moves(dry_run=True, prompt=False) # Apply roster moves to Yahoo! with confirmation prompts bot.apply_roster_moves(dry_run=False, prompt=True) # Apply roster moves automatically (no prompts) bot.apply_roster_moves(dry_run=False, prompt=False) ``` -------------------------------- ### Yahoo Fantasy Bot Caching System Source: https://context7.com/spilchen/yahoo_fantasy_bot/llms.txt Python code demonstrating the use of TeamCache and LeagueCache utilities to reduce Yahoo! API calls. Configure expiry times for prediction builders and free agents, and load or rebuild cached data as needed. Caches can be cleared using the .remove() method. ```python from yahoo_fantasy_bot.utils import TeamCache, LeagueCache import configparser cfg = configparser.RawConfigParser() cfg.read('my_league.cfg') # Team-specific cache (predictions, free agents, lineups) team_cache = TeamCache(cfg, 'team_key_here') # Load or rebuild prediction builder with expiry import datetime expiry = datetime.timedelta(minutes=1440) # 24 hours def build_predictions(): # Expensive operation to build predictions return prediction_builder_object pred_bldr = team_cache.load_prediction_builder(expiry, build_predictions) # Load cached free agents def fetch_free_agents(): return league.free_agents(None) free_agents = team_cache.load_free_agents( datetime.timedelta(minutes=60), fetch_free_agents ) # Clear team cache when needed team_cache.remove() # League-level cache (static settings) league_cache = LeagueCache(cfg) def load_league_settings(): return league.settings() settings = league_cache.load_statics(load_league_settings) # Clear league cache league_cache.remove() ``` -------------------------------- ### Yahoo Fantasy Bot Configuration File Source: https://context7.com/spilchen/yahoo_fantasy_bot/llms.txt This INI file structure controls all aspects of bot behavior, including OAuth credentials, caching parameters, prediction sources, and optimization settings. Configure parameters like league ID, stat categories, and prediction source options. ```ini [Logger] file = .log/ybot.nhl.log level = INFO [Connection] # OAuth credentials file (generated by ybot_setup) oauthFile = oauth2.json [Cache] dir = .cache/ freeAgentExpiry = 60 predictionBuilderExpiry = 1440 [League] id = 403.l.12345 # Stat categories to optimize for predictedStatCategories = G,A,PPP,SOG,PIM,W,SV% [Prediction] builderPackage=yahoo_fantasy_bot builderModule=.nhl builderClassLoader=init_prediction_builder # Options: yahoo, yahoo_lastseason, yahoo_lastmonth, csv source=yahoo player_id_column_name=player_id # For CSV source, specify file paths: #skaters_csv_file=/path/to/skaters.csv #goalies_csv_file=/path/to/goalies.csv [LineupOptimizer] package=yahoo_fantasy_bot module=.lineup_optimizer function=optimize_with_genetic_algorithm generations=250 initialPopulationSize=24 tournamentParticipants=4 numOffspring=6 mutationPct=10 minPctOwned=10 lockPlayersAbovePctOwn=80 lockPlayerFile= excludePlayerFile= benchSelection=avoidChurn [Display] package=yahoo_fantasy_bot module=.nhl class=PlayerPrinter [Scorer] package=yahoo_fantasy_bot module=.nhl class=Scorer useWeeklySchedule=false stdevCap=3 [ScoreAccumulator] package=yahoo_fantasy_bot module=.nhl class=StatAccumulator [Trade] autoReject=true ``` -------------------------------- ### Evaluate Trades Source: https://context7.com/spilchen/yahoo_fantasy_bot/llms.txt Evaluate pending trades and optionally auto-reject them via configuration. ```python # Apply trade decisions to Yahoo! (accepts or rejects) bot.evaluate_trades(dry_run=False, verbose=True, prompt=True) ``` -------------------------------- ### Generate MLB Stat Predictions Source: https://context7.com/spilchen/yahoo_fantasy_bot/llms.txt Generate and summarize player stat projections for MLB rosters. ```python from yahoo_fantasy_bot.mlb import Builder, init_prediction_builder, Scorer from yahoo_oauth import OAuth2 import yahoo_fantasy_api as yfa import configparser cfg = configparser.RawConfigParser( converters={'list': lambda x: [i.strip() for i in x.split(',')]} ) cfg.read('mlb_league.cfg') # Connect to Yahoo! sc = OAuth2(None, None, from_file=cfg['Connection']['oauthFile']) lg = yfa.League(sc, cfg['League']['id']) # Initialize MLB prediction builder pred_bldr = init_prediction_builder(lg, cfg) # Get roster roster = lg.to_team(lg.team_key()).roster() # Generate predictions (handles hitters and pitchers separately) predictions_df = pred_bldr.predict(roster, fail_on_missing=False) # Score the predictions scorer = Scorer(cfg) stat_summary = scorer.summarize(predictions_df) print(stat_summary) ``` -------------------------------- ### Generate NHL Stat Predictions Source: https://context7.com/spilchen/yahoo_fantasy_bot/llms.txt Generate and summarize player stat projections for NHL rosters. ```python from yahoo_fantasy_bot.nhl import Builder, init_prediction_builder, Scorer from yahoo_oauth import OAuth2 import yahoo_fantasy_api as yfa import configparser cfg = configparser.RawConfigParser( converters={'list': lambda x: [i.strip() for i in x.split(',')]} ) cfg.read('nhl_league.cfg') # Connect to Yahoo! sc = OAuth2(None, None, from_file=cfg['Connection']['oauthFile']) lg = yfa.League(sc, cfg['League']['id']) # Initialize prediction builder (handles caching automatically) pred_bldr = init_prediction_builder(lg, cfg) # Get roster from Yahoo! roster = lg.to_team(lg.team_key()).roster() # Generate predictions for roster predictions_df = pred_bldr.predict(roster, fail_on_missing=False) # Score the predictions scorer = Scorer(cfg) stat_summary = scorer.summarize(predictions_df) print(stat_summary) ``` -------------------------------- ### Evaluate Trade Proposals Source: https://context7.com/spilchen/yahoo_fantasy_bot/llms.txt Automatically evaluate incoming trade proposals using the ManagerBot trade evaluation functionality. ```python from yahoo_fantasy_bot.bot import ManagerBot import configparser cfg = configparser.RawConfigParser( converters={'list': lambda x: [i.strip() for i in x.split(',')]} ) cfg.read('my_league.cfg') bot = ManagerBot(cfg, reset_cache=False, ignore_status=False) # Evaluate all pending trades against your team # dry_run=True previews decisions without sending to Yahoo! # verbose=True prints trade details num_trades = bot.evaluate_trades(dry_run=True, verbose=True, prompt=False) print(f"Evaluated {num_trades} trade(s)") # Example output when verbose=True: # Sending # Player A ``` -------------------------------- ### Interact with ManagerBot Class Source: https://context7.com/spilchen/yahoo_fantasy_bot/llms.txt Programmatic access to the ManagerBot class for custom integration or direct API interaction. ```python from yahoo_fantasy_bot.bot import ManagerBot import configparser # Load configuration cfg = configparser.RawConfigParser( converters={'list': lambda x: [i.strip() for i in x.split(',')]} ) cfg.read('my_league.cfg') # Initialize the bot (connects to Yahoo!, loads predictions, syncs lineup) bot = ManagerBot(cfg, reset_cache=False, ignore_status=False) # Current lineup is automatically loaded and accessible print(f"Lineup has {len(bot.lineup)} players") print(f"Bench has {len(bot.bench)} players") print(f"IR has {len(bot.injury_reserve)} players") # Access team and league objects for direct Yahoo! API calls team = bot.tm # yahoo_fantasy_api.Team object league = bot.lg # yahoo_fantasy_api.League object # Get opponent information for the current matchup print(f"Playing against: {bot.opp_team_name}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.