Spaces:
Running
Running
| import requests | |
| BASE_URL = "https://fantasy.premierleague.com/api" | |
| AFCON_GW = 16 | |
| def calculate_fts(transfers, first_gw, next_gw, fh_gws, wc_gws): | |
| """Exact logic ported from open-fpl-solver dev/solver.py""" | |
| n_transfers = {gw: 0 for gw in range(2, next_gw + 2)} | |
| for t in transfers: | |
| if t["event"] in n_transfers: | |
| n_transfers[t["event"]] += 1 | |
| fts = {gw: 0 for gw in range(first_gw + 1, next_gw + 2)} | |
| fts[first_gw + 1] = 1 | |
| for i in range(first_gw + 2, next_gw + 1): | |
| if i == AFCON_GW: | |
| fts[i] = 5 | |
| continue | |
| if (i - 1) in fh_gws or (i - 1) in wc_gws: | |
| fts[i] = fts[i - 1] | |
| continue | |
| fts[i] = fts[i - 1] - n_transfers[i - 1] | |
| fts[i] = max(fts[i], 0) | |
| fts[i] += 1 | |
| fts[i] = min(fts[i], 5) | |
| return fts.get(next_gw, 1) | |
| def get_fpl_team_data(team_id: int): | |
| print(f"Executing strict open-fpl-solver logic for Team ID: {team_id}...") | |
| static = requests.get(f"{BASE_URL}/bootstrap-static/").json() | |
| element_to_type = {x["id"]: x["element_type"] for x in static["elements"]} | |
| next_gw = next(x["id"] for x in static["events"] if x["is_next"]) | |
| start_prices = { | |
| x["id"]: x["now_cost"] - x["cost_change_start"] for x in static["elements"] | |
| } | |
| transfers = requests.get(f"{BASE_URL}/entry/{team_id}/transfers/").json()[::-1] | |
| history = requests.get(f"{BASE_URL}/entry/{team_id}/history/").json() | |
| chips = history["chips"] | |
| fh_gws = [x["event"] for x in chips if x["name"] == "freehit"] | |
| wc_gws = [x["event"] for x in chips if x["name"] == "wildcard"] | |
| first_gw = history["current"][0]["event"] | |
| first_gw_data = requests.get( | |
| f"{BASE_URL}/entry/{team_id}/event/{first_gw}/picks/" | |
| ).json() | |
| # Calculate exact purchase prices and ITB | |
| squad = {x["element"]: start_prices[x["element"]] for x in first_gw_data["picks"]} | |
| itb = 1000 - sum(squad.values()) | |
| for t in transfers: | |
| if t["event"] in fh_gws: | |
| continue | |
| itb += t["element_out_cost"] | |
| itb -= t["element_in_cost"] | |
| if t["element_in"]: | |
| squad[t["element_in"]] = t["element_in_cost"] | |
| if t["element_out"] and t["element_out"] in squad: | |
| del squad[t["element_out"]] | |
| fts = calculate_fts(transfers, first_gw, next_gw, fh_gws, wc_gws) | |
| picks = [] | |
| for player_id, purchase_price in squad.items(): | |
| now_cost = next( | |
| x["now_cost"] for x in static["elements"] if x["id"] == player_id | |
| ) | |
| diff = now_cost - purchase_price | |
| selling_price = purchase_price + (diff // 2) if diff > 0 else now_cost | |
| picks.append( | |
| { | |
| "id": player_id, | |
| "purchase_price": purchase_price / 10.0, | |
| "selling_price": selling_price / 10.0, | |
| "now_cost": now_cost / 10.0, | |
| } | |
| ) | |
| return {"in_the_bank": itb / 10.0, "free_transfers": fts, "squad": picks} | |