import requests\012from collections import defaultdict\012from datetime import datetime\012import matplotlib.pyplot as plt\012import numpy as np\012\012print("WARNING: Parlays are high-risk, high-variance bets. All legs must win for payout. This is for backtesting only - bet responsibly.")\012\012def backtest_3leg_nba_parlay_favorites(season="2024"):\012    # Fetch teams\012    teams_url = "https://www.balldontlie.io/api/v1/teams"\012    teams = requests.get(teams_url).json()['data']\012    team_map = {t['id']: t['full_name'] for t in teams}\012\012    # Fetch regular season games\012    games = []\012    start_date = f"{season}-10-01"\012    end_date = f"{season+1}-06-30"\012    page = 0\012    per_page = 100\012    while True:\012        url = f"https://www.balldontlie.io/api/v1/games?seasons[]={season}&postseason=false&start_date={start_date}&end_date={end_date}&per_page={per_page}&page={page}"\012        resp = requests.get(url).json()\012        games.extend(resp['data'])\012        if len(resp['data']) < per_page:\012            break\012        page += 1\012\012    # Process completed games\012    game_list = []\012    for g in games:\012        if g.get('status_abbreviation') == 'Final' and g.get('home_score') is not None and g.get('visitor_score') is not None:\012            home_win = g['home_score'] > g['visitor_score']\012            game_list.append({\012                'id': g['id'],\012                'date': g['date'][:10],\012                'game_date': datetime.fromisoformat(g['date'][:19]),\012                'home_id': g['home_team']['id'],\012                'visitor_id': g['visitor_team']['id'],\012                'home_score': g['home_score'],\012                'visitor_score': g['visitor_score'],\012                'home_win': home_win\012            })\012\012    game_list.sort(key=lambda x: x['game_date'])\012\012    # Backtest\012    team_wins = defaultdict(int)\012    team_losses = defaultdict(int)\012    bankroll = 1000.0\012    stake = 10.0\012    fav_decimal_odds = 1.67  # -150\012    bets = []\012    bankroll_history = [bankroll]\012\012    i = 0\012    while i < len(game_list):\012        curr_date = game_list[i]['date']\012        day_games = []\012        while i < len(game_list) and game_list[i]['date'] == curr_date:\012            day_games.append(game_list[i])\012            i += 1\012\012        # Potential legs pre-day games\012        legs = []\012        for game in day_games:\012            h_id = game['home_id']\012            v_id = game['visitor_id']\012            h_games = team_wins[h_id] + team_losses[h_id]\012            v_games = team_wins[v_id] + team_losses[v_id]\012            h_pct = team_wins[h_id] / h_games if h_games > 0 else 0.5\012            v_pct = team_wins[v_id] / v_games if v_games > 0 else 0.5\012            h_adj_pct = h_pct + 0.03  # home advantage\012\012            if h_adj_pct > v_pct + 0.05:\012                legs.append({\012                    'game_id': game['id'],\012                    'fav_side': 'home',\012                    'win_pct_diff': h_adj_pct - v_pct,\012                    'game': game,\012                    'fav_team_name': team_map[h_id]\012                })\012            elif v_pct > h_adj_pct + 0.05:\012                legs.append({\012                    'game_id': game['id'],\012                    'fav_side': 'visitor',\012                    'win_pct_diff': v_pct - h_adj_pct,\012                    'game': game,\012                    'fav_team_name': team_map[v_id]\012                })\012\012        # 3-leg parlay if possible\012        if len(legs) >= 3:\012            legs.sort(key=lambda x: x['win_pct_diff'], reverse=True)\012            top_legs = legs[:3]\012\012            combined_odds = fav_decimal_odds ** 3\012            american_odds = round((combined_odds - 1) * 100)\012\012            # Simulate outcome\012            all_won = all(\012                top_legs[j]['game']['home_win'] if top_legs[j]['fav_side'] == 'home'\012                else not top_legs[j]['game']['home_win']\012                for j in range(3)\012            )\012\012            payout = stake * combined_odds if all_won else 0\012            profit = payout - stake\012            bankroll += profit\012\012            bet = {\012                'date': curr_date,\012                'legs': [leg['fav_team_name'] for leg in top_legs],\012                'stake': stake,\012                'payout': payout,\012                'profit': profit,\012                'won': all_won,\012                'combined_odds': f"+{american_odds}"\012            }\012            bets.append(bet)\012\012        bankroll_history.append(bankroll)\012\012        # Update records post-day\012        for game in day_games:\012            h_id = game['home_id']\012            v_id = game['visitor_id']\012            if game['home_win']:\012                team_wins[h_id] += 1\012                team_losses[v_id] += 1\012            else:\012                team_wins[v_id] += 1\012                team_losses[h_id] += 1\012\012    # Metrics\012    num_bets = len(bets)\012    num_wins = sum(b['won'] for b in bets)\012    win_rate = (num_wins / num_bets * 100) if num_bets else 0\012    total_profit = bankroll - 1000\012    total_staked = num_bets * stake\012    roi = (total_profit / total_staked * 100) if total_staked else 0\012\012    print(f"\n=== 3-Leg NBA Moneyline Favorites Parlay Backtest - {season}-{int(season)+1} Season ===")\012    print(f"Initial Bankroll: $1000.00")\012    print(f"Final Bankroll: ${bankroll:.2f}")\012    print(f"Total Profit/Loss: ${total_profit:.2f}")\012    print(f"Total Parlays Placed: {num_bets}")\012    print(f"Parlay Wins: {num_wins} ({win_rate:.1f}%)")\012    print(f"Total Staked: ${total_staked:.2f}")\012    print(f"ROI: {roi:.1f}%")\012    print(f"Assumed Leg Odds: -150 (1.67 decimal) | 3-Leg Parlay: ~+{int((fav_decimal_odds**3-1)*100)}")\012\012    # Profit curve chart\012    plt.figure(figsize=(12, 6))\012    plt.plot(bankroll_history, linewidth=2, color='green')\012    plt.title('Bankroll Progression - 3-Leg NBA Favorites Parlay Backtest')\012    plt.xlabel('Trading Days')\012    plt.ylabel('Bankroll ($)')\012    plt.grid(True, alpha=0.3)\012    plt.axhline(y=1000, color='red', linestyle='--', alpha=0.7, label='Initial Bankroll')\012    plt.legend()\012    plt.tight_layout()\012    plt.show()\012\012    return bets\012\012# Run backtest\012backtest_3leg_nba_parlay_favorites("2024")