GithubHelp home page GithubHelp logo

dimakudosh / pydfs-lineup-optimizer Goto Github PK

View Code? Open in Web Editor NEW
405.0 44.0 153.0 576 KB

Daily Fantasy Sports lineup optimzer for all popular daily fantasy sports sites

License: MIT License

Python 100.00%
pydfs-lineup-optimizer python sports fantasy-sports fantasy-football nba nfl nhl mlb fantasy

pydfs-lineup-optimizer's Introduction

PYDFS-LINEUP-OPTIMIZER Build StatusCoverage Status

pydfs-lineup-optimizer is a tool for creating optimal lineups for daily fantasy sport.

Installation

To install pydfs-lineup-optimizer, simply run:

$ pip install pydfs-lineup-optimizer

Support

Now it supports following dfs sites:

League DraftKings FanDuel FantasyDraft Yahoo FanBall DraftKings Captain Mode FanDuel Single Game DraftKings Tiers
NFL + + + + + + + +
NBA + + + + - + + +
NHL + + + + - + + +
MLB + + + + - + + +
WNBA + + - - - + - -
Golf + + + + - - - -
Soccer + - - + - + - -
CFL + - - - - - - -
CFB + - - - - - - -
LOL - + - - - + + -
MMA + + - - - - - -
NASCAR + + - - - - - -
Tennis + - - - - - - -
CSGO + - - - - - - -

Documentation

Documentation is available at https://pydfs-lineup-optimizer.readthedocs.io/en/latest

Example

Here is an example for evaluating optimal lineup for Yahoo fantasy NBA. It loads players list from "yahoo-NBA.csv" and select 10 best lineups.

from pydfs_lineup_optimizer import Site, Sport, get_optimizer


optimizer = get_optimizer(Site.YAHOO, Sport.BASKETBALL)
optimizer.load_players_from_csv("yahoo-NBA.csv")
for lineup in optimizer.optimize(10):
    print(lineup)

pydfs-lineup-optimizer's People

Contributors

aaronsewall avatar adanet2 avatar dheadt avatar dimakudosh avatar eciancio avatar ethanopp avatar jmelowry avatar mavieth avatar sansbacon avatar siegler avatar vladiki avatar wawegner avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pydfs-lineup-optimizer's Issues

fanduel NFL optimizer error

I keep encountering a bug in the FanDuel NFL optimizer, regardless of whether I create my own player objects or use load_players_from_CSV.

Here is an example of the output using the site CSV file:

In [4]: optimizer.load_players_from_CSV('~/fd.csv')

In [5]: lineup_generator = optimizer.optimize(10)
...: for lineup in lineup_generator:
...: print(lineup)
...:

LineupOptimizerException Traceback (most recent call last)
in ()
1 lineup_generator = optimizer.optimize(10)
----> 2 for lineup in lineup_generator:
3 print(lineup)
4

~/anaconda3/lib/python3.6/site-packages/pydfs_lineup_optimizer/lineup_optimizer.py in optimize(self, n, max_exposure, randomness, with_injured)
525 yield lineup
526 else:
--> 527 raise LineupOptimizerException('Can't generate lineups')
528 self._lineup = locked_players
529 return

LineupOptimizerException: Can't generate lineups

fd.zip

DraftKings Hockey KeyError

Dima,

line 7, in
for lineup in lineup_generator:
line 478, in optimize
lineup = self._build_lineup(lineup_players)
line 312, in _build_lineup
players.sort(key=lambda p: (len(p.positions), max([single_positions[pos] for pos in p.positions])))
line 312, in
players.sort(key=lambda p: (len(p.positions), max([single_positions[pos] for pos in p.positions])))
line 312, in
players.sort(key=lambda p: (len(p.positions), max([single_positions[pos] for pos in p.positions])))
KeyError: 'RW'

This is my code:
from pydfs_lineup_optimizer import Site, Sport, get_optimizer

optimizer = get_optimizer(Site.DRAFTKINGS, Sport.HOCKEY)
optimizer.load_players_from_CSV("DKSalaries.csv")
lineup_generator = optimizer.optimize(10)
for lineup in lineup_generator:
print(lineup)

This is what's happening when trying to generate DraftKings Hockey lineups using the unmodified DKSalaries.csv sheet. Is there something I need to do differently to get this to work?

MLB 5 Hitters on FD

Dima - I keep getting 5 hitters from the same team on FD. We can have 1 pitcher and 4 hitters from the same team, but not 5 hitters on FanDuel. I've noticed this since the you added the stacking feature.

Time zone incorrect

timezone('EST')
must be replaced with
timezone('US/Eastern')
in two places

NBA Draftkings Showdown

The exposure limits for NBA Draftkings showdown (and likely other showdown types with a captain) don't work as one may think. I believe the max exposure allows for a player at each position captain and utility. Is it possible we can have a limiting factor on each?

Optimizer Not Producing Valid DK LoL Lineups

I haven't looked exhaustively but the ruleset DraftKings lays out for LoL lineups is not being honored by the optimizer. Specifically the rules say:

-Lineups will consist of 8 spots with
-A maximum of 4 players from any one LoL team in a matchup.
-Teams do not count towards the 4-player maximum.
-Additionally, Lineups must span at least 2 different LoL games.

I was able to produce a lineup that had 5 players from the same team (I can confirm the fifth position was not the TEAM).

In addition, I don't see you tracking the fixtures for each player (i.e. which LoL game they are taking part in). If you don't have this data point I'm not sure how you can fulfill the final rule about lineups spanning 2 different LoL games.

Happy to provide starting player pools and resulting lineups if that helps. I have attached one example.

playerPool.txt
resultingLinupe.txt

How to constrain which positions allowed in Flex

Hi - I'm referring to Draftkings NFL. I've loaded my metrics into the optimizer and it appears that every flex player is a TE in the output. I'm not sure how I can apply a constraint here to allow only WR, RB, in Flex, or just WR in Flex, etc. Thanks

Enhancement to generating top expected value lineup

Thanks for creating this! I wanted to share a pruning algorithm that ensures maximum expected value and may be useful for players wanting the top lineup optimized towards one category. This can be an alternative approach to what you mentioned here https://pydfs-lineup-optimizer.readthedocs.io/en/latest/performance-and-optimization.html

Prunes player pool to generate maxium expected value follows:
    if a player has a higher predicted score and lower salary, remove all players with a higher salary than the player
Additionally
    if all position spots are unused, keep up to the remaining number of slots left
    with a lower score than the player we are on but higher predicted point total than the next best option
Here's an example:
    Odell beckam  salary 8000 predicted 19
    Alshon Jeffrey salary 7900 predicted 20
    Mohammed sanu salary 5100 predicted 15

Because there are 3+1 spots for WR (including FLEX), we can't remove odell beckham because he would contribute more
to our point total than removing him. If there was only 1 WR slot we'd be safe to remove him.

I can create a PR some day if your interested. I've used this over at https://www.blog.sportsdatadirect.com/2018/08/22/draftkings-2018-millionaire-maker-recaps/ and have consistently been able to find the top lineups possible using my pruned player pool. Using your pulp solver version I've gotten matching results for 6 out of 6 weeks I tested with my pruning alg

add_player_to_lineup requires Player object rather than full_name

I think it would be helpful to have a convenience method 'get_player' or 'find_player':

from fuzzywuzzy import fuzz, process

def get_player(self, full_name):
    player = [x for x in self.players if x.full_name == full_name]
    if not player:
        fuzzy, confidence = process.extractOne(full_name, [x.full_name for x in self.players])
        if confidence >= threshold:
            player = [x for x in self.players if x.full_name == fuzzy]
    if player:
        return player[0]
    else:
        return None

Feature Request: Lineup fill method for Max_Exposure

Would it be possible to add an option to check max_exposure as each lineup is generated rather than for the full group?

Let's say there are only two players at a position that both have the same salary but different point projections, and max_exposure set to 50% for both. Currently if 10 lineups are generated the first 5 would have the higher ranked player. With this option, you'd have the higher ranked player in every other lineup, since the lower ranked player would get selected as soon as the lineup pool has >50% exposure to the first player, rather than meeting the requirement at the end of generating the lineups.

Anyway to Export?

Just a suggestion, is there a way to export the lineups created to a csv or something like th at?

Can't get players

Hi,

I can't get players with the 'optimizer.players', neither with the 'optimizer.get_player_by_name()'
What am I doing wrong?

Thanks for the help!

Multiple lineups

There should be an option to have multiple lineups.

If you have a constraint called max_points, set it to some large number initially, then in a loop where you generate lineups set max_points = solution - very small amount, say .001. You will then generate a different lineup each time through the loop. something like this . . .

def n_lineups(n):
    max_points = 1000
    for idx in range(n):
        pts_cap = constraint(0, maxpts)
        maxpts = solution_points - .001

Seems like a bug in late-swap Classic MLB

MLB roaster positions: P | P | C | 1B | 2B | 3B | SS | OF | OF | OF
NBA roaster positions: PG | SG | SF | PF | C | G | F | UTIL

NBA positions are all unique, while MLB (which is baseball) have several identical names, like two Ps and three OFs. So in this code:

1 if unswappable_players:
2 locked_positions = [player.lineup_position for player in unswappable_players]
3 players = [player for player in players if player not in unswappable_players]
4 positions = [position for position in positions if position.name not in locked_positions]
5 lineup.extend(unswappable_players)

In line 4 'positions' will be missing all three 'OF' positions even if only a single player in 'OF' position is unswappable.
Which means that late-swap optimization will not be correct.

Optimizer might choose all players from the same team in Captain mode

That makes wrong lineups.
There is a way to avoid it by using:
optimizer.set_players_from_one_team({'OKC': 5})
but this solution is not universal and requires manually finding and adding every team.
It would be good to have:
optimizer.set_players_from_one_team(5)
which will be used by any team the Optimizer currently using players from.

Cant load CSV file for FanDuel

KeyError Traceback (most recent call last)
in ()
----> 1 optimizer.load_players_from_CSV("FanDuel-MLB-2018-05-15-25805-lineup-upload-template.csv")

~\Desktop\pydfs-lineup-optimizer-master\pydfs_lineup_optimizer\lineup_optimizer.py in load_players_from_CSV(self, filename)
162 :type filename: str
163 """
--> 164 self._players = self._settings.load_players_from_CSV(filename)
165 self._set_available_teams()
166

~\Desktop\pydfs-lineup-optimizer-master\pydfs_lineup_optimizer\settings.py in load_players_from_CSV(cls, filename)
131 max_exposure = row.get('Max Exposure')
132 player = Player(
--> 133 row['Id'],
134 row['First Name'],
135 row['Last Name'],

KeyError: 'Id'

Catch LineupOptimizerException

What's the correct way to catch this exception? I can't for the life of me catch it.

Even this doesn't work.

try:
    lineup_generator = optimizer.optimize(10)
except:
    pass

I still get the Runtime Error

pydfs_lineup_optimizer.exceptions.LineupOptimizerException: Can't generate lineups

Generate multiple lineups with the same point total?

I was trying to generate the top optimal lineups for yesterday's DK PGA tournament and noticed that when I generate multiple lineups, each generated lineup has a discrete point total despite having multiple ways to arrive at that total.

Specifically, there were several combinations of players under salary cap that arrive at 586.0 points, (which was the winning GPP total) but only one lineup is generated with 586.0 points.

Is this something that is intentionally being done by the optimizer?


This is the only 586.0 point lineup that was generated by the library when I don't lock any players:
image

But if I lock the players to just the lineup that won the GPP yesterday, I get a different lineup at 586.0 points:
image

I'm guessing that it's picking the "best" lineup for each 0.5 point interval, since the one it chose had a lower salary total than the one that won the GPP.

Ideally, I'd want to see all the permutations for a point total before it goes on to the next lower one. Is there a way to control for this?

feature request: ownership constraint

It would be helpful to add "projected_ownership_min" and "projected_ownership_max" properties to the Player class and a corresponding constraint in the optimizer.

For the Player class, the values for projected_ownership_min and projected_ownership_max range from 0 to 1.

def __init__(self, player_id,  first_name, last_name, positions, team, salary, fppg, is_injured=False,
             max_exposure=None, projected_ownership_min=0, projected_ownership_max=0):
    # type: (int, str, str, List[str], str, float, float, bool, Optional[float]) -> None
    self.id = player_id
    self.first_name = first_name
    self.last_name = last_name
    self.positions = positions
    self.team = team.upper()
    self.salary = salary
    self.fppg = fppg
    self.is_injured = is_injured
    self._max_exposure = None
    self.max_exposure = max_exposure
    self.projected_ownership_min = projected_ownership_min
    self.projected_ownership_max= projected_ownership_max

For the optimizer, the default values for projected_ownership_min and projected_ownership_max could be set > N players so it would have no effect. The user then could specify lower numbers to ensure that the lineup does not include too many high-owned players. It is unclear to me how to add settings and constraints to the optimizer, but I think the rules would look like the following:

class LineupMinOwnershipRule(OptimizerRule):
def apply(self, solver, players_dict):
variables = []
coefficients = []
for player, variable in players_dict.items():
variables.append(variable)
coefficients.append(player.projected_ownership_min)
solver.add_constraint(variables, coefficients, SolverSign.LTE, self.optimizer.projected_ownership_min)

class LineupMaxOwnershipRule(OptimizerRule):
def apply(self, solver, players_dict):
variables = []
coefficients = []
for player, variable in players_dict.items():
variables.append(variable)
coefficients.append(player.projected_ownership_max)
solver.add_constraint(variables, coefficients, SolverSign.LTE, self.optimizer.projected_ownership_max)

Thanks!

League of Legends Now Uses Captain Mode

The rules for LoL lineups have completely changed from last season so unfortunately now the optimizer is not usable for LoL. They have introduced the captain concept and eliminated the FLEX position so the team is now 7 instead of 8 players. If you have the time and desire, I would be grateful if you could update the tool to reflect the new rules for LoL.

Great work, by the way, this thing is great.

Set min total salary

How can I set salary constraint on the lineup optimizer? e, g. I want to set a min total salary to be $59900 for all lineups in fanduel. Thanks for the help.

Pitcher vs Opposing Hitter

Hi Dima,

Can you make it so the optimizer doesn't select hitters from the team your pitcher is opposing?

For instance, if Boston were playing Houston and I was using Chris Sale in a Pitcher spot, I wouldn't want any batters in my lineup from Houston. Likewise, if I were using Gerrit Cole for Houston I wouldn't want any Boston hitters in my lineup.

The reason being your upside is limited if you have hitters that are facing the pitcher you roster. If Sale has a great game, then the Houston batters likely had a poor game. You wouldn't want them in the same lineup.

FanDuel Showdown MLB

Hi Dima,

Any chance you want to add FanDuel MLB showdowns to the solver package? They have an MVP (2 x score), All Star (1.5 x score), and 3 open spots. Must have at least 1 person from each team.

Draftkings Basketball Keyerror

Hi when i try to do a basketball lineup im getting this error

Traceback (most recent call last):
File "C:\Program Files (x86)\Python37-32\lib\site-packages\pydfs_lineup_optimizer\sites\draftkings\importer.py", line 20, in import_players
name = row['Name'].split()
KeyError: 'Name'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "", line 1, in
File "C:\Program Files (x86)\Python37-32\lib\site-packages\pydfs_lineup_optimizer\lineup_optimizer.py", line 174, in load_players_from_csv
self._players = csv_importer(filename).import_players()
File "C:\Program Files (x86)\Python37-32\lib\site-packages\pydfs_lineup_optimizer\sites\draftkings\importer.py", line 32, in import_players
raise LineupOptimizerIncorrectCSV
pydfs_lineup_optimizer.exceptions.LineupOptimizerIncorrectCSV: Incorrect csv format!

but i got the csv from draftkings

Unable to build lineup from optimizer result

Hello, been a long time follower of your app.

Back with the older version, I was able to create tons of lineups, well over 500 but with this newer version, depending on the player projections, once I get to about 20 lineups i get the "Unable to build lineup from optimizer result" error.

Ive tried messing with it but i couldnt get it to work, so i went back to the older version. However I love how this is newer version is organized in a way we can easily upload projections.

Unable to import players from an array

Hello,

I am trying to import players that are from a Google Sheet. I believe I have it formatted correctly. It is in an array. See below for the first two records:

['site_id', 'first_name', 'last_name', 'pos', 'team', 'salary', 'fppg', 'injury', 'max_exposure', 'min_exposure', 'ownership']
['58312', "D'Angelo", "Russell", 'SG', 'BKN', '9000', '10.39', '', '23%', '3%', '14%']

However, I get the following error when i run optimizer.load_players(player_array_final):
AttributeError: 'list' object has no attribute 'team'

List index out of range

When uploading csv from DraftKings(Football) Error message: list index out of range is presented, any work around or knowledge of this?

Initial Installation Issue - ImportError: No module named solvers

Trying to get initial installation and having a little trouble.

MacOS
pip 10.0.1
Python 2.7.15

After running: $ pip install pydfs-lineup-optimizer
Output shows:
Requirement already satisfied: pydfs-lineup-optimizer in {{PATH}} (2.0.0)
Requirement already satisfied: PuLP>=1.6.8 in {{PATH}} (from pydfs-lineup-optimizer) (1.6.8)
Requirement already satisfied: typing in {{PATH}} (from pydfs-lineup-optimizer) (3.6.4)
Requirement already satisfied: pyparsing>=2.0.1 in {{PATH}} (from PuLP>=1.6.8->pydfs-lineup-optimizer) (2.2.0)

After attempting to do initial import: from pydfs_lineup_optimizer import get_optimizer, Site, Sport

I get the following error:
Traceback (most recent call last):
File "test.py", line 1, in
from pydfs_lineup_optimizer import get_optimizer, Site, Sport
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pydfs_lineup_optimizer/init.py", line 7, in
from pydfs_lineup_optimizer.lineup_optimizer import LineupOptimizer
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pydfs_lineup_optimizer/lineup_optimizer.py", line 6, in
from pydfs_lineup_optimizer.solvers import PuLPSolver, SolverException
ImportError: No module named solvers

Please let me know if I can provide anymore information.

Hoping to get this resolved, this looks awesome!

  • Kevin

Game Stacks

Hi Dima,

This is great, I really appreciate you creating this for us.

I see you can stack one team using optimizer.set_players_from_one_team({'PHO': 3}) , is there a way to Game Stack by setting the number of players from two different teams?

For instance, tonight GS plays PHI, I'd like to know how to force the optimizer to give me several lineups containing the maximum 4 players from each team.

Thanks!

Game request: DK MMA

Hey,

Would you be able to add MMA in? Shoudn't be near as complex as say Basketball or NFL.

I'll give it a try myself but been a while since I've written any code.

Cheers

DraftKings and Hockey, Doesn't like my data.

Hello again;
and again, this issue is caused by my own stupidity.

I'm pulling my data from mySql Data Tables that I've scraped from various websites. I've gotten the FanDuel Hockey, working and it's great (Thank you so much) ,
but for some reason, I can't figure out what I'm missing on the DraftKings side. (I have a feeling that my Position(s) are wrong for DraftKings, but I don't know how to fix it.)
Can you please help me? -- Thanks.
-- ==================================================
Here's a sample of my input data: (The first two are goalies, the second two are ['C','UTIL'] and ['W', 'UTIL']...
player_info[0] :
PlayerName : Marc-Andre Fleury
Name[0] : Marc-Andre
Name[1] : Fleury
TeamShort : VGK
Position : ['G']
Salary : 8200.0
FanPoints : 10.6
player_info[1] :
PlayerName : Matt Murray
Name[0] : Matt
Name[1] : Murray
TeamShort : PIT
Position : ['G']
Salary : 8000.0
FanPoints : 2.6
PlayerName : S. Stamkos
Name[0] : S.
Name[1] : Stamkos
TeamShort : TBL
Position : ['C', 'UTIL']
Salary : 7100.0
FanPoints : 6.0
player_info[10] :
PlayerName : V. Tarasenko
Name[0] : V.
Name[1] : Tarasenko
TeamShort : STL
Position : ['W', 'UTIL']
Salary : 7000.0
FanPoints : 6.0
-- ===================================================
Here's my code:
players.append(Player(
int(i),
name[0],
name[1],
player_info[2].split('/'), # for Fanduel use '-' for Draftkings use '/'
player_info[1],
float(player_info[3]),
float(player_info[4])
))
optimizer.load_players(players)
for player in optimizer.players:
if player.efficiency == 0:
optimizer.remove_player(player)
lineup_generator = optimizer.optimize(3)

Here's the Error:
pydfs_lineup_optimizer.solvers.exceptions.SolverException: Unable to solve
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File ".\NHLDKTodaysTop3Lineups(TXT).py", line 147, in
for lineup in lineup_generator:
File "C:\Users\Larry Brown\AppData\Local\Programs\Python\Python37\lib\site-packages\pydfs_lineup_optimizer\lineup_optimizer.py", line 397, in optimize
raise LineupOptimizerException('Can't generate lineups')
pydfs_lineup_optimizer.exceptions.LineupOptimizerException: Can't generate lineups
-- ====================================================

Optimal lineup not created on Fanduel Baseball

When building baseball lineups on FanDuel we can currently only get 4 players per team. This rule has been modified for the 2018 season and your now allowed to have 4 hitters from the same team as well as a pitcher from the same team.

EX:

Current implementation:

  1. P Jon Gray COL 36.317 8600
  2. C1B Justin Bour PHI 9.11 2000
  3. 2B Javier Baez CHC 16.12 3700
  4. 3B Nolan Arenado COL 18.16 4500
  5. SS Nick Ahmed ARI 8.6 2500
  6. OF Charlie Blackmon COL 17.959 4200
  7. OF Carlos Gonzalez COL 16.646 3800
  8. OF Albert Almora CHC 10.336 2300
  9. 2B Ben Zobrist CHC 14.085 3400

Desired Implementation:

  1. P Jon Gray COL 36.317 8600
  2. C1B Justin Bour PHI 9.11 2000
  3. 2B Javier Baez CHC 16.12 3700
  4. 3B Nolan Arenado COL 18.16 4500
  5. SS Nick Ahmed ARI 8.6 2500
  6. OF Charlie Blackmon COL 17.959 4200
  7. OF Carlos Gonzalez COL 16.646 3800
  8. OF Albert Almora CHC 10.336 2300
  9. 2B DJ LeMahieu COL 14.865 3400

Notice the 9 spot will not build with DJ as the most optimal because this would violate the current 4 players per team max, when it is a 100% legal lineup.

Using SQL to populate DraftKings (Players) -- Doesn't work

Hello again, I know this is my fault and my own stupidity, but can you please help.
I got your optimizer working by populating the Players through an SQL query using site.FANDUEL (works great!). But I can't seem to get it to work with the DRAFTKINGS Optimizer.

optimizer = get_optimizer(Site.DRAFTKINGS, Sport.BASEBALL)

the DRAFTKINGS optimizer works great using the CSV file Loader.

I believe my data looks good, in my database. Do you think there might be something wrong with my data? (I'm also attaching an Export of my scraped MLB Data.

I've tried to include everything I could think of. Can you please point me in the right direction?

20190326-MLBRosterData.zip

Can you please help?
Thank you so much!,
Larry

#####################################################
Traceback (most recent call last):
File "C:\Users\Larry Brown\AppData\Local\Programs\Python\Python37\lib\site-packages\pydfs_lineup_optimizer\lineup_optimizer.py", line 385, in optimize
solved_variables = solver.solve()
File "C:\Users\Larry Brown\AppData\Local\Programs\Python\Python37\lib\site-packages\pydfs_lineup_optimizer\solvers\pulp_solver.py", line 47, in solve
raise SolverException('Unable to solve')
pydfs_lineup_optimizer.solvers.exceptions.SolverException: Unable to solve

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File ".\MLBDKTodaysTop3Lineups.py", line 143, in
for lineup in lineup_generator:
File "C:\Users\Larry Brown\AppData\Local\Programs\Python\Python37\lib\site-packages\pydfs_lineup_optimizer\lineup_optimizer.py", line 397, in optimize
raise LineupOptimizerException('Can't generate lineups')
pydfs_lineup_optimizer.exceptions.LineupOptimizerException: Can't generate lineups
########################################################
`from pydfs_lineup_optimizer import Site, Sport, get_optimizer, Player
optimizer = get_optimizer(Site.DRAFTKINGS, Sport.BASEBALL)

players = []

roster = mF.getAllMLBPlayerInfo('DK')
for i, player_info in enumerate(roster):
name = player_info[0].split(' ')

print('player_info[' + str(i) +'] : ')
print('PlayerName : ' + str(player_info[0]))
print('Name[0]    : ' + str(name[0]))
print('Name[1]    : ' + str(name[1]))
print('TeamShort  : ' + str(player_info[1]))
print('Position   : ' + str(player_info[2].split('/')))
print('Salary     : ' + str(player_info[3]))
print('FanPoints  : ' + str(player_info[4]))

players.append(Player(
    int(i),
    name[0],
    name[1],
    player_info[2].split('/'),    # for Fanduel use '-' for Draftkings use '/'
    player_info[1],
    float(player_info[3]),
    float(player_info[4])
))

optimizer.load_players(players)`
########################################################
OUTPUT from Print Statements above:
player_info[280] :
PlayerName : Eric Stamets
Name[0] : Eric
Name[1] : Stamets
TeamShort : CLE
Position : ['SS']
Salary : 2700.0
FanPoints : 5.36
player_info[281] :
PlayerName : Martin Maldonado
Name[0] : Martin
Name[1] : Maldonado
TeamShort : KCR
Position : ['C']
Salary : 2700.0
FanPoints : 5.68
player_info[282] :
PlayerName : Miguel Cabrera
Name[0] : Miguel
Name[1] : Cabrera
TeamShort : DET
Position : ['1B']
Salary : 2400.0
FanPoints : 6.92

#####################################################
def getAllMLBPlayerInfo(VENDOR='FD'):
conn = mysql.connector.connect(user='xxxx', password='xxxx', host='192.168.1.248', database='MLB_TABLE')
cur = conn.cursor()

print('Vendor Variable: ' + VENDOR)

if VENDOR=='FD':
    qPlayerInfo = \
    "Select \
        MLBStartingLineups.PlayerName, \
        MLBStartingLineups.TeamShort, \
        MLBStartingLineups.PlayerFDPosition, \
        MLBStartingLineups.FanDuelSalary, \
        MLBStartingLineups.FanDuelFPoints \
    from MLBStartingLineups \
    where (FanDuelSalary != 0) and (FanDuelFPoints != 0) \
    order by FanDuelSalary Desc;"
if VENDOR=='DK':
    qPlayerInfo = \
    "Select \
        MLBStartingLineups.PlayerName, \
        MLBStartingLineups.TeamShort, \
        MLBStartingLineups.PlayerDKPosition, \
        MLBStartingLineups.DraftKingsSalary, \
        MLBStartingLineups.DraftKingsFPoints \
    from MLBStartingLineups \
    where (DraftKingsSalary != 0) and (DraftKingsFPoints != 0) \
    order by DraftKingsSalary Desc;"

cur.execute(qPlayerInfo)
playerInfo = cur.fetchall()

cur.close()
return(playerInfo) # Return All PlayerInfo

########################################################

Is there a way to set minimum exposure?

Hello,

I have been playing around with this program for several weeks and i keep running into the problem that i cannot set minimum exposure without forcing the player/players into the top lineups the optimizer spits out. So say I want to have Duke Johnson Jr. in at least 10% of my lineups but I don't want to force him into the first few lineups (using the add player function), is there a way to do this? This mainly comes up when I have several players that i want at low ownership and they may not be optimal so they don't get spit out in any of the 40+ lineups naturally thus forcing me to make them be in the first 5-10. Any time i want multiple sub optimal players it will try to force them into the same lineup which isn't quite what im going for with the idea. Any help is appreciated and thanks for the awesome groundwork.

Team Related Constraints in FantasyDraft

I think the answer is I can't do this, but I wanted to check.

I tried to include the set_players_from_one_team option for my MLB lineups playing FantasyDraft, but kept getting an error "incorrect team name" even though I was using the only abbreviation that exists for a given team. I think the problem is that in the Fdraft csv format, the only team related info is Matchup, so like "ATL @ STL" and it doesn't look like the CSV does anything to differentiate the teams.

Is that right? If so is there anything i can do about it?

Unicode Error

I get this when I try to upload a CSV file of the players' information.

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xdf in position 1727: invalid continuation byte

Feature request: point multipliers in scoring?

FanDuel has quite a few variations of contest scoring, especially for single games, where certain lineup slots have multipliers on the scoring, like 2.0x, 1.5x, 1.2x, etc.

Is it possible to add this more dynamic lineup scoring to the optimizer to handle these situations?

Lineup diversity requirement

Is it possible to limit the number of players who appear in the same lineup?
For example, say the optimal lineup is Player A, B, C, D, E, F, G, and H
The overlap parameter is 5, meaning that no lineup should have more than 5 common players. Another lineup with A, B, C, D, E, F, X, Y would fail the constraint, whereas a lineup with A, B, C, D, E, X, Y would be OK. I'm not familiar with how to use pulp, but this is how it might be done (inefficiently) using or-tools:

# loop through optimal lineups that have already been generated
# add diversity constraint of no more than overlap in new lineup
for lineup in existing_lineups:
    diversity_cap = solver.Constraint(0, overlap)
    for player in lineup.players:
        # lookup index of player in all_players
        # then set coefficient of that index to 1
        i = [i for i, p in enumerate(all_players) if p.id == player.id][0]
        diversity_cap.SetCoefficient(variables[i], 1)

FanDuel football lineups are bad

Hey,

Nice work! Like your library a lot but I'm seeing some issues when creating FanDuel football lineups...

The lineups get generated, but are not optimal - it doesn't function as expected after observing the correct behavior when running through the test CSV file. (# Note: I am using a local copy of the source as I found that the pip install is not the latest version. The only modification I have made is round the FPPG output display for each player selected in a lineup).

For example, for one of today's FanDuel lobby games, these are the outputs I get are listed below.

Attached is the FanDuel file used.
FanDuel-NFL-2016-12-18-17288-players-list.zip

Thanks.

BW

Connected to pydev debugger (build 163.8233.8)

  1. LeSean McCoy ['RB']BUF 18.15 9000.0$
  2. Matt Barkley ['QB']CHI 11.06 6200.0$
  3. Sterling Shepard ['WR']NYG 9.02 5300.0$
  4. Jeremy Kerley ['WR']SF 7.05 4900.0$
  5. Justin Hardy ['WR']ATL 4.04 4900.0$
  6. Dorial Green-Beckham ['WR']PHI 5.85 4900.0$
  7. Matt Prater ['K']DET 10.0 4800.0$
  8. Shaun Draughn ['RB']SF 5.32 4700.0$
  9. Austin Hooper ['TE']ATL 4.72 4600.0$
    Fantasy Points 75.2119592009
    Salary 49300.0
  10. Ryan Mallett ['QB']BAL -0.01 6000.0$
  11. Taylor Heinicke ['QB']MIN 0.0 5000.0$
  12. Raheem Mostert ['RB']SF -0.25 4500.0$
  13. Jalston Fowler ['RB']TEN 0.95 4500.0$
  14. Tavarres King ['WR']NYG 0.55 4500.0$
  15. Devin Hester ['WR']BAL -0.17 4500.0$
  16. Robbie Gould ['K']NYG 3.71 4500.0$
  17. Danny Vitale ['TE']CLE 0.05 4500.0$
  18. Lucky Whitehead ['WR']DAL 0.97 4500.0$
    Fantasy Points 5.80095241378
    Salary 42500.0
  19. Ryan Mallett ['QB']BAL -0.01 6000.0$
  20. Raheem Mostert ['RB']SF -0.25 4500.0$
  21. Jalston Fowler ['RB']TEN 0.95 4500.0$
  22. Keshawn Martin ['WR']SF -2.0 4500.0$
  23. Tavarres King ['WR']NYG 0.55 4500.0$
  24. Devin Hester ['WR']BAL -0.17 4500.0$
  25. Robbie Gould ['K']NYG 3.71 4500.0$
  26. Danny Vitale ['TE']CLE 0.05 4500.0$
  27. Lucky Whitehead ['WR']DAL 0.97 4500.0$
    Fantasy Points 3.80095241378
    Salary 42000.0
  28. Ryan Mallett ['QB']BAL -0.01 6000.0$
  29. Raheem Mostert ['RB']SF -0.25 4500.0$
  30. Jalston Fowler ['RB']TEN 0.95 4500.0$
  31. Tony Washington ['WR']JAC 0.8 4500.0$
  32. Keshawn Martin ['WR']SF -2.0 4500.0$
  33. Tavarres King ['WR']NYG 0.55 4500.0$
  34. Devin Hester ['WR']BAL -0.17 4500.0$
  35. Robbie Gould ['K']NYG 3.71 4500.0$
  36. Danny Vitale ['TE']CLE 0.05 4500.0$
    Fantasy Points 3.63428572725
    Salary 42000.0
  37. Ryan Mallett ['QB']BAL -0.01 6000.0$
  38. Taylor Heinicke ['QB']MIN 0.0 5000.0$
  39. Raheem Mostert ['RB']SF -0.25 4500.0$
  40. Jalston Fowler ['RB']TEN 0.95 4500.0$
  41. Keshawn Martin ['WR']SF -2.0 4500.0$
  42. Tavarres King ['WR']NYG 0.55 4500.0$
  43. Devin Hester ['WR']BAL -0.17 4500.0$
  44. Robbie Gould ['K']NYG 3.71 4500.0$
  45. Danny Vitale ['TE']CLE 0.05 4500.0$
    Fantasy Points 2.83428571533
    Salary 42500.0

Feature Request: Question: MySQL vs. CSV

Thank you so much for writing and posting this, I love it.
I have one question. Is it possible to use my "mySQL" database instead of reading from a CSV file?

I scrape FanDuel and DraftKings Websites on a daily basis and store that data into a mySQL table, then I can work on it. I'm just wondering if there is a way to Import directly from a query into your Player List / Dictionary? instead of from a CSV File.
I know that I could write my query to output to a CSV file, then use your scripts to read in that CSV file. but, if I could read in directly from a mySQL DB, that would be great!

Is this possible now? or is this a Function Request? or something I can do on my own, with a little direction from you.

Thank you again, SO MUCH.

Small issue in __init__.py

Type in init.py:
Site.FANDUEL: {
Sport.BASKETBALL: FanDuelBasketballSettings,
Sport.FOOTBALL: FanDuelFootballSettings,
Sport.HOCKEY: FanDuelHockeySettings,
Sport.BASEBALL: FanDuelBasketballSettings,
},

It should be FanDuelBaseballSettings

Also, Sport.BASEBALL: DraftKingBaseballSettings, you are missing 's' in DraftKing(s)

FanDuel Basketball drop lowest score update?

Hello,

First, I would like to say thank you so much for creating this :)

I was wonder, will there be an update for FanDuel Basketball as they have changed their rules where the lowest score in your lineup is dropped.

Thanks.

feature request: DK showdown captain slates

DraftKings now has one-game "showdown captain mode" games that have the same salary cap but a few differences from the ordinary DraftKings game:

(1) There are only six lineup spots.

(2) There are no fixed positions (everything is FLEX) and you can play kickers as well as the ordinary positions on DraftKings.

(3) There is a captain slot in the lineup. The captain costs 1.5X the published salary and gets 1.5X the points earned.

So the settings would be:

@SitesRegistry.register_settings
class DraftKingsCaptainFootballSettings(DraftKingsSettings):
sport = Sport.FOOTBALL
positions = [
LineupPosition('CAPTAIN', ('QB','WR','RB','TE','DST','K')),
LineupPosition('FLEX1', ('QB','WR','RB','TE','DST','K')),
LineupPosition('FLEX2', ('QB','WR','RB','TE','DST','K')),
LineupPosition('FLEX3', ('QB','WR','RB','TE','DST','K')),
LineupPosition('FLEX4', ('QB','WR','RB','TE','DST','K')),
LineupPosition('FLEX5', ('QB','WR','RB','TE','DST','K'))
]

It is unclear to me how to modify the existing optimize function to account for the "captain," which increases a player's salary and fantasy points per game when used in that slot.

Thanks!
Eric

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.