コード例 #1
0
def buy_shares(usr, abr, num_shares, db):
    team = Team.query.filter(Team.abr == abr).first()
    price = num_shares * team.price * 1.005
    if usr.available_funds < price:
        raise ValueError('not enough funds')
    now = datetime.now(EST)
    purchase = Purchase(team_id=team.id,
                        user_id=usr.id,
                        purchased_at=now,
                        purchased_for=team.price * 1.005,
                        amt_shares=num_shares)
    db.session.add(purchase)
    db.session.commit()
    ptransac = PurchaseTransaction(team_id=team.id,
                                   user_id=usr.id,
                                   date=now,
                                   purchased_for=team.price * 1.005,
                                   amt_purchased=num_shares)
    db.session.add(ptransac)
    db.session.commit()
    res = [{team.abr: {'date': str(now), 'price': team.price * 1.005}}]
    emit('prices', res, broadcast=True, namespace='/')
    update_teamPrice(team, (team.price * .005), now, db)
    usr.available_funds -= price
    loc = db.session.merge(usr)
    db.session.add(loc)
    db.session.commit()
コード例 #2
0
def short_team(usr, abr, num_shares, db):
    now = datetime.now(EST)
    tm = db.session.query(Team).\
        filter(Team.abr == abr).first()
    price = num_shares * tm.price * .9975
    usr.available_funds += price
    short = Short(team_id=tm.id,
                  user_id=usr.id,
                  shorted_for=tm.price * .9975,
                  shorted_at=now,
                  amt_shorted=num_shares)
    db.session.add(short)
    db.session.commit()
    transac = ShortTransaction(team_id=tm.id,
                               user_id=usr.id,
                               shorted_for=tm.price * .9975,
                               shorted_at=now,
                               amt_shorted=num_shares)
    db.session.add(transac)
    db.session.commit()
    loc_usr = db.session.merge(usr)
    db.session.add(loc_usr)
    db.session.commit()
    res = [{tm.abr: {'date': str(now), 'price': tm.price * .9975}}]
    emit('prices', res, broadcast=True, namespace='/')
    update_teamPrice(tm, -(tm.price * .0025), now, db)
    return res
コード例 #3
0
def simulate(start_yr, end_yr, k, h, use_mov, injuries, db):
    active_injuries = []
    for season in get_schedule_range(start_yr, end_yr):
        teams = Team.query.all()
        season_start = season[0]['start_time']
        season_end = season[-1]['start_time'].replace(tzinfo=None)
        for team in teams:
            season_elo_reset(team, season_start, db)
        prev_date = season_start - timedelta(days=1)
        for game in season:
            if game['home_team_score'] is None:
                continue
            date_obj = game['start_time'].replace(tzinfo=None)
            date = date_obj.strftime('%Y-%m-%d')
            if date != prev_date:
                new = []
                for d, active_inj in active_injuries:
                    if date_obj < d:
                        new.append((d, active_inj))
                    else:
                        inj_team = Team.query.filter(
                            Team.name.contains(injury[1])).first()
                        recover_from_injury(inj_team, injury[0], db)
                active_injuries = new
                if date in injuries.keys():
                    for injury in injuries[date]:
                        inj_team = Team.query.filter(
                            Team.name.contains(injury[1])).first()
                        apply_injury(inj_team, injury[0], injury[2], date_obj,
                                     db)
                        if injury[2] == 'Day':
                            ret_d = date_obj + timedelta(days=1)
                        elif injury[2] == 'Week':
                            ret_d = date_obj + timedelta(weeks=1)
                        elif injury[2] == 'Month':
                            ret_d = date_obj + timedelta(weeks=4)
                        else:
                            ret_d = season_end
                        active_injuries.append((ret_d, injury))
            home_tname = capwords(game['home_team'].name.replace('_', ' '))
            away_tname = capwords(game['away_team'].name.replace('_', ' '))
            home_team = Team.query.filter(Team.name == home_tname).first()
            away_team = Team.query.filter(Team.name == away_tname).first()
            score_diff = int(game['home_team_score']) - int(
                game['away_team_score'])
            elo_diff = home_team.price - away_team.price
            elo_change = home_rating_change(k, h, score_diff, elo_diff,
                                            use_mov)
            update_teamPrice(home_team, elo_change, date_obj, db)
            update_teamPrice(away_team, -elo_change, date_obj, db)
            prev_date = date
コード例 #4
0
def unshort_team(usr, abr, num_shares, db):
    team = db.session.query(Team).\
        filter(Team.abr == abr).\
        first()
    price = num_shares * team.price * 1.0025
    if price > usr.available_funds:
        raise ValueError('insufficient funds')
    all_shorts = db.session.query(Short).\
        filter(Short.user_id == usr.id).\
        filter(Short.team_id == team.id).\
        filter(Short.exists == True).\
        all()
    total_shares = reduce(lambda x, p: x + p.amt_shorted, all_shorts, 0)
    if num_shares > total_shares:
        raise ValueError('not enough shares owned')
    now = datetime.now(EST)
    all_holdings.sort(key=lambda p: p.amt_shares, reverse=True)
    left_to_delete = num_shares
    ix = 0
    while left_to_delete > 0:
        p = all_shorts[ix]
        to_del = min(p.amt_shorted, left_to_delete)
        if to_del == p.amt_shorted:
            p.exists = False
            p.unshorted_at = now
            p.unshorted_for = team.price * 1.0025
        else:
            p.amt_shorted -= to_del
        loc = db.session.merge(p)
        db.session.add(loc)
        db.session.commit()
        left_to_delete -= to_del
        ix += 1
    usr.available_funds -= price
    loc_u = db.session.merge(usr)
    db.session.add(loc_u)
    db.session.commit()
    new_unshort = Unshort(team_id=team.id,
                          unshorted_at=now,
                          amt_unshorted=num_shares,
                          user_id=usr.id,
                          unshorted_for=team.price * 1.0025)
    db.session.add(new_unshort)
    db.session.commit()
    res = [{team.abr: {'date': str(now), 'price': team.price * 1.0025}}]
    emit('prices', res, broadcast=True, namespace='/')
    update_teamPrice(team, team.price * .0025, now, db)
    return res
コード例 #5
0
def sell_shares(usr, abr, num_shares, db):
    team = db.session.query(Team).filter(Team.abr == abr).first()
    price = num_shares * team.price * .9975
    all_holdings = db.session.query(Purchase).filter(
        Purchase.user_id == usr.id).filter(Purchase.team_id == team.id).filter(
            Purchase.exists == True).all()
    total_shares = reduce(lambda x, p: x + p.amt_shares, all_holdings, 0)
    if num_shares > total_shares:
        raise ValueError('not enough shares owned')
    now = datetime.now(EST)
    all_holdings.sort(key=lambda p: p.amt_shares, reverse=True)
    left_to_delete = num_shares
    ix = 0
    while left_to_delete > 0:
        p = all_holdings[ix]
        to_del = min(p.amt_shares, left_to_delete)
        if to_del == p.amt_shares:
            p.exists = False
            p.sold_at = now
            p.sold_for = team.price * .9975
        else:
            p.amt_shares -= to_del
        loc = db.session.merge(p)
        db.session.add(loc)
        db.session.commit()
        left_to_delete -= to_del
        ix += 1
    usr.available_funds += price
    loc_u = db.session.merge(usr)
    db.session.add(loc_u)
    db.session.commit()
    new_sale = Sale(team_id=team.id,
                    date=now,
                    amt_sold=num_shares,
                    user_id=usr.id,
                    sold_for=team.price * .9975)
    db.session.add(new_sale)
    db.session.commit()
    res = [{team.abr: {'date': str(now), 'price': team.price * .9975}}]
    emit('prices', res, broadcast=True, namespace='/')
    update_teamPrice(team, -(team.price * .0025), now, db)
    return res
コード例 #6
0
def apply_injury(team, player_name, duration, date, db):
    end_of_season = datetime.strptime('2020-03-08', '%Y-%m-%d')
    days_left = (end_of_season - date).days
    # injure player
    inj_player = Player.query.filter(Player.name == player_name).first()
    inj_player.is_injured = True
    inj_mpg = inj_player.mpg
    inj_player.mpg = 0
    db.session.add(inj_player)
    db.session.commit()
    # rebalance minutes
    players = Player.query.filter(Player.team_id == team.id).all()
    total_rating = sum([player.rating for player in players])
    for player in players:
        if not player.is_injured:
            if inj_player.pos2 != '':
                if player.pos1 == inj_player.pos1:
                    player.mpg += (player.rating / total_rating) * (inj_mpg *
                                                                    .4225)
                if player.pos2 == inj_player.pos1:
                    player.mpg += (player.rating / total_rating) * (inj_mpg *
                                                                    .2275)
                if player.pos1 == inj_player.pos2:
                    player.mpg += (player.rating / total_rating) * (inj_mpg *
                                                                    .2275)
                if player.pos2 == inj_player.pos2:
                    player.mpg += (player.rating / total_rating) * (inj_mpg *
                                                                    .1225)
            else:
                if player.pos1 == inj_player.pos1:
                    player.mpg = inj_mpg * .65
                if player.pos2 == inj_player.pos1:
                    player.mpg = inj_mpg * .35
            if player.mpg > 35.5:
                player.mpg = 35.5
            db.session.add(player)
            db.session.commit()
    team.rating = active_player_rating(team, db)
    db.session.add(team)
    db.session.commit()
    ps = Player.query.filter(Player.team_id == team.id).filter(
        Player.is_injured == False).all()
    print(f'WHEN {player_name} GOT INJURED for a {duration}:')
    for p in ps:
        print(f'{p.name}: {p.mpg}')
    print('')
    print(f'Full Strength Rating: {team.fs_rating}')
    print(f'Rating: {team.rating}')
    sev = 100 * (team.fs_rating - team.rating) / team.fs_rating
    if duration == 'Day':
        sev = sev * .1
    elif duration == 'Week':
        sev = sev * .225
    elif duration == 'Month':
        sev = sev * .5
    else:
        sev = sev * .69
    if days_left < 100 and duration == 'Month':
        sev = sev + ((100 - days_left) * .1)

    if days_left < 70 and duration == 'Week':
        print("Initial Sev: " + str(sev))
        sev = sev + ((70 - days_left) * .2)

    if days_left < 63 and duration == 'Day':
        print("Initial Sev: " + str(sev))
        sev = sev + ((63 - days_left) * .2)
    print(f'severity: {sev}')
    print('======================')
    update_teamPrice(team, (-sev / 100) * team.price, date, db)
コード例 #7
0
def season_elo_reset(team, date, db):
    newprice = (.75 * team.price) + 375
    update_teamPrice(team, newprice - team.price, date, db)