Пример #1
0
    def handle(self, *args, **options):
        # purge all records

        print "flushing player database"
        Player.objects.all().delete()

        ### Scrape spotrac for cap hits

        teams = ["atlanta-hawks","boston-celtics","brooklyn-nets",
        "charlotte-hornets","chicago-bulls","cleveland-cavaliers",
        "dallas-mavericks","denver-nuggets","detroit-pistons",
        "golden-state-warriors","houston-rockets","indiana-pacers",
        "los-angeles-clippers","los-angeles-lakers","memphis-grizzlies",
        "miami-heat","milwaukee-bucks","minnesota-timberwolves",
        "new-orleans-pelicans","new-york-knicks","oklahoma-city-thunder",
        "orlando-magic","philadelphia-76ers","phoenix-suns",
        "portland-trail-blazers","sacramento-kings","san-antonio-spurs",
        "toronto-raptors","utah-jazz","washington-wizards"]

        URL = 'http://www.spotrac.com/nba/{}/cap/'

        for t in teams:
            r = requests.get(URL.format(t))
            soup = BeautifulSoup(r.text)
            table = soup.find("table")
            rows = table.findAll('tr')
            for r in rows[1:]:
                full_name = r.find(attrs={'class':'player'}).a.string
                cap_hit = r.find(title=re.compile('Cap Figure')).string.replace('$','').replace(',','').replace(' ','')
                nba_team = t.replace('-',' ')
                while True:
                    try:
                        print "adding {} from {} with salary {}".format(full_name, nba_team, cap_hit)
                    except (UnicodeEncodeError, UnicodeDecodeError) as e:
                        full_name = "Dennis Schroder"
                        continue
                    break
                player_obj = Player(
                    full_name=full_name,
                    salary=cap_hit,
                    nba_team=nba_team,
                )
                player_obj.save()
            time.sleep(2)

        # mark last update
        LastUpdated.objects.all().delete()
        last_update_obj = LastUpdated(
          last_update=timezone.now()
        )
        last_update_obj.save()
    def handle(self, *args, **options):
        for s in Squad.objects.all():
            print s

            players = Player.objects.filter(manager__manager=s.manager)

            if len(players) != 0:
                total = 0
                total += players.aggregate(Sum('salary'))['salary__sum']
                s.total_cap_hit = total
                s.save()

        # mark last update
        LastUpdated.objects.all().delete()
        last_update_obj = LastUpdated(
          last_update=timezone.now()
        )
        last_update_obj.save()
Пример #3
0
    def handle(self, *args, **options):

        with open("rosters/management/commands/league_draft.csv", "r") as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                print "Saving {} to {}".format(row["player"], row["manager"])
                squad_obj = Squad.objects.get(manager=row["manager"])
                player_obj = Player.objects.get(full_name=row["player"])
                player_obj.manager = squad_obj
                player_obj.draft_round = row["draft_round"]
                player_obj.draft_pick = row["draft_pick"]
                player_obj.save()
                squad_obj.save()

        LastUpdated.objects.all().delete()

        # mark last update
        last_update_obj = LastUpdated(last_update=timezone.now())
        last_update_obj.save()
Пример #4
0
    def handle(self, *args, **options):
        FILE_PATH = "rosters/management/commands/draft_order.csv"

        DraftPick.objects.all().delete()
        with open(FILE_PATH, "r") as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                print "trying round {} pick {} manager {} player {}".format(
                    row["round"], row["pick"], row["manager"], row["player"]
                )

                squad_obj = Squad.objects.get(manager=row["manager"])

                if row["player"]:
                    player_obj = Player.objects.get(full_name=row["player"])
                    player_obj.manager = squad_obj

                    new_pick_obj = DraftPick(
                        draft_round=row["round"],
                        draft_pick=row["pick"],
                        note=row["note"],
                        squad=squad_obj,
                        player=player_obj,
                    )
                else:
                    new_pick_obj = DraftPick(
                        draft_round=row["round"], draft_pick=row["pick"], note=row["note"], squad=squad_obj
                    )

                squad_obj.save()
                player_obj.save()
                new_pick_obj.save()

        for s in Squad.objects.all():
            print "summing {}".format(s)

            players = Player.objects.filter(manager__manager=s.manager)

            if len(players) != 0:
                total = 0
                total += players.aggregate(Sum("salary"))["salary__sum"]
                s.total_cap_hit = total
                s.save()

        with open(FILE_PATH, "w+") as csvfile:
            csvwriter = csv.writer(csvfile)
            csvwriter.writerow(["round", "pick", "manager", "player", "salary", "team", "note"])
            for p in DraftPick.objects.order_by("draft_round", "draft_pick", "squad"):
                csvwriter.writerow(
                    [
                        p.draft_round,
                        p.draft_pick,
                        p.squad,
                        p.player if p.player else "",
                        p.player.salary if p.player else "",
                        p.player.nba_team if p.player else "",
                        p.note,
                    ]
                )

        LastUpdated.objects.all().delete()

        # mark last update
        last_update_obj = LastUpdated(last_update=timezone.now())
        last_update_obj.save()
Пример #5
0
    def handle(self, *args, **options):
        logfile = open('rosters/management/commands/errors_load_squads.txt', 'wb')

        now = datetime.datetime.today()
        logfile.write('Starting update {}\n\n'.format(now.strftime("%d %B %Y %H:%M")))

        logfile.write("flushing squad database\n\n")
        Squad.objects.all().delete()

        if options['blank']:
            for manager_nickname, manager_fullname in Squad.MANAGER_CHOICES:
                logfile.write("initalizing blank team for {}\n".format(manager_nickname))
                squad_obj = Squad(
                    manager=manager_nickname,
                )
                squad_obj.slug = slugify(squad_obj.get_manager_display())
                squad_obj.save()
        else:
            ## Get managers from Yahoo league

            # calling Yahoo API with keys and tokens
            api = YahooAPI('keyfile.txt', 'tokenfile.txt')

            # base format for any call
            BASE_API_CALL = 'http://fantasysports.yahooapis.com/fantasy/v2/{}'

            # just getting the rosters for each team
            roster_call = BASE_API_CALL.format('team/nba.l.129466.t.{}/roster/')

            for i in range(1,11):
                request = api.request(roster_call.format(i), params={'format': 'json'}).json()
                output = request['fantasy_content']['team']

                # initialize all Squads
                manager_nickname = output[0][19]['managers'][0]['manager']['nickname']

                logfile.write("initalizing team for {}\n".format(manager_nickname))
                squad_obj = Squad(
                    manager=manager_nickname,
                )
                squad_obj.slug = slugify(squad_obj.get_manager_display())
                squad_obj.save()

                # Yahoo names --> spotrac names
                translation = {
                    'Matthew Dellavedova': 'Matt Dellavedova',
                    'Otto Porter': 'Otto Porter Jr.',
                    'Ish Smith': 'Ishmael Smith',
                    'Kentavious Caldwell-Pope': 'Kentavious Caldwell-Pope ',
                    'Enes Kanter': 'Enes  Kanter',
                    'J.J. Barea': 'Jose Barea',
                    'Patty Mills': 'Patrick Mills',
                    'Lou Williams': 'Louis Williams',
                }

                # loading players to each roster
                number_players = int(output[1]['roster']['0']['players']['count'])

                total_cap_hit = 0

                for j in range(0, number_players):
                    player_name = output[1]['roster']['0']['players'][str(j)]['player'][0][2]['name']['full']
                    if player_name in translation.keys():
                        player_name = translation[player_name]
                    try:
                        new_player_obj = Player.objects.get(full_name=player_name)
                        new_player_obj.manager = squad_obj
                        squad_obj.total_cap_hit += new_player_obj.salary
                        new_player_obj.save()
                        squad_obj.save()
                    except Player.DoesNotExist:
                        logfile.write("***NO RECORD OF {}***".format(player_name))

            # mark last update
            LastUpdated.objects.all().delete()
            last_update_obj = LastUpdated(
              last_update=timezone.now()
            )
            last_update_obj.save()