У меня есть код Python, который предназначен для построения нескольких сценариев ставок.
Мой код ниже возвращает этот график.
import pandas as pd
import matplotlib.pyplot as plt
import itertools
bet_details = {
"Team 1": {"bet_amount": 1000, "price_per_share": 0.37, "bet_position": "L"},
"Team 2": {"bet_amount": 1000, "price_per_share": 0.59, "bet_position": "W"}} # "L" for Lose, "W" for Win
# Calculate P/L based on prediction market share model
def calculate_profit(bet_amount, odds, position, outcome):
# Calculate the number of shares based on price per share
shares = bet_amount / odds
if position == outcome:
return shares # If bet is correct, return $1 per share
else:
return -bet_amount # If bet is incorrect, lose the bet amount
# Function to simulate all scenarios and calculate P/L for each one
def simulate_bets(bet_details):
# Generate all possible win/loss combinations for the given states
scenarios = list(itertools.product(["W", "L"], repeat=len(bet_details)))
# Initialize lists to store results
scenario_results = []
breakdown = []
# Calculate P/L for each scenario
for scenario in scenarios:
scenario_name = " & ".join([f"{state}: {'Win' if outcome == 'W' else 'Lose'}" for state, outcome in zip(bet_details.keys(), scenario)])
total_profit_loss = 0
# Breakdown details for each state in this scenario
state_breakdown = []
# Calculate P/L for each state in the scenario
for state, outcome in zip(bet_details.keys(), scenario):
details = bet_details[state]
bet_amount = details["bet_amount"]
odds = details["odds"]
position = details["bet_position"]
# Calculate the profit/loss for this state in the current scenario
profit_loss = calculate_profit(bet_amount, odds, position, outcome)
total_profit_loss += profit_loss
# Append breakdown information
state_breakdown.append({
"State": state,
"Bet Amount": bet_amount,
"Bet Position": position,
"Bet Outcome": outcome,
"P/L": profit_loss
})
# Add scenario results to main results
scenario_results.append({"Scenario": scenario_name, "Total Profit/Loss": total_profit_loss})
breakdown.extend(state_breakdown)
# Create DataFrames for scenario overview and detailed breakdown
df_scenarios = pd.DataFrame(scenario_results).sort_values(by="Total Profit/Loss", ascending=False)
df_breakdown = pd.DataFrame(breakdown)
# Plotting the scenario results
plot_scenarios(df_scenarios)
return df_scenarios, df_breakdown
def plot_scenarios(df_scenarios):
fig, ax = plt.subplots(figsize=(10, 8))
bars = ax.barh(df_scenarios['Scenario'], df_scenarios['Total Profit/Loss'], color=["green" if x > 0 else "red" for x in df_scenarios['Total Profit/Loss']])
# Add labels
ax.set_xlabel("Total Profit/Loss ($)")
ax.set_title("Profit/Loss by Scenario")
# Adding text labels for P/L values with alignment adjustment
for bar in bars:
width = bar.get_width()
ax.text(width + (10 if width < 0 else -40), bar.get_y() + bar.get_height() / 2, f"{width:.2f}",
va="center", ha="left" if width < 0 else "right", color="black", fontweight="bold")
plt.show()
Есть ли способ создать график, который показывает разбивку P/L каждой ставки на полосе напротив друг друга и показывает название ставки и P/L. Когда я пытался, лучшее, чего мне удалось добиться, это вот такой неприятный результат (график).
import pandas as pd
import matplotlib.pyplot as plt
import itertools
# Define the bet details for each team in a dictionary
bet_details = {
"Team 1": {"bet_amount": 100, "odds": 0.37, "bet_position": "L"}, # "L" for Lose, "W" for Win
"Team 2": {"bet_amount": 100, "odds": 0.59, "bet_position": "W"},
}
# Calculate P/L based on prediction market share model
def calculate_profit(bet_amount, odds, position, outcome):
# Calculate the number of shares based on price per share
shares = bet_amount / odds
if position == outcome:
return shares # If bet is correct, return $1 per share
else:
return -bet_amount # If bet is incorrect, lose the bet amount
# Function to simulate all scenarios and calculate P/L for each one
def simulate_bets(bet_details):
# Generate all possible win/loss combinations for the given teams
scenarios = list(itertools.product(["W", "L"], repeat=len(bet_details)))
# Initialize lists to store results
scenario_results = []
breakdown = []
# Calculate P/L for each scenario
for scenario in scenarios:
scenario_name = " & ".join([f"{team}: {'Win' if outcome == 'W' else 'Lose'}" for team, outcome in zip(bet_details.keys(), scenario)])
total_profit_loss = 0
# Breakdown details for each team in this scenario
team_breakdown = []
# Calculate P/L for each team in the scenario
for team, outcome in zip(bet_details.keys(), scenario):
details = bet_details[team]
bet_amount = details["bet_amount"]
odds = details["odds"]
position = details["bet_position"]
# Calculate the profit/loss for this team in the current scenario
profit_loss = calculate_profit(bet_amount, odds, position, outcome)
total_profit_loss += profit_loss
# Append breakdown information
team_breakdown.append({
"Team": team,
"Bet Amount": bet_amount,
"Bet Position": position,
"Bet Outcome": outcome,
"P/L": profit_loss
})
# Add scenario results to main results
scenario_results.append({"Scenario": scenario_name, "Total Profit/Loss": total_profit_loss})
breakdown.extend(team_breakdown)
# Create DataFrames for scenario overview and detailed breakdown
df_scenarios = pd.DataFrame(scenario_results).sort_values(by="Total Profit/Loss", ascending=False)
df_breakdown = pd.DataFrame(breakdown)
# Plotting the scenario results
plot_scenarios(df_scenarios, df_breakdown)
return df_scenarios, df_breakdown
def plot_scenarios(df_scenarios, df_breakdown):
fig, ax = plt.subplots(figsize=(12, 8))
# Main scenario profit/loss bars
bars = ax.barh(df_scenarios['Scenario'], df_scenarios['Total Profit/Loss'],
color=["green" if x > 0 else "red" for x in df_scenarios['Total Profit/Loss']],
edgecolor='black')
# Adding text labels for scenario P/L values
for bar in bars:
width = bar.get_width()
ax.text(width + (10 if width < 0 else -40), bar.get_y() + bar.get_height() / 2, f"{width:.2f}",
va="center", ha="left" if width < 0 else "right", color="black", fontweight="bold")
# Create a mirrored bar for team-level P/L breakdown
for index, scenario in enumerate(df_scenarios['Scenario']):
# Get team breakdown for this scenario
team_data = df_breakdown[df_breakdown['Team'].isin(bet_details.keys())]
# Calculate the profit/loss for each team in this scenario
for team in bet_details.keys():
details = bet_details[team]
profit_loss = calculate_profit(details['bet_amount'], details['odds'], details['bet_position'],
"W" if df_scenarios.iloc[index]['Total Profit/Loss'] > 0 else "L")
# Create a bar for the team's P/L on the opposite side
ax.barh(scenario, profit_loss, left=-profit_loss, color='lightblue', edgecolor='black', height=0.4)
# Add team P/L labels on the opposite side
ax.text(-profit_loss - 5, index, f"{team}: {profit_loss:.2f}", va='center', color='black', fontweight='bold')
# Set labels and title
ax.set_xlabel("Total Profit/Loss ($)")
ax.set_title("Profit/Loss by Scenario with Team Breakdown")
plt.show()
# Example usage:
df_results, df_breakdown = simulate_bets(bet_details)
print(df_results) # Scenario summary with total P/L
print(df_breakdown) # Detailed P/L breakdown by team
Подробнее здесь: https://stackoverflow.com/questions/791 ... -bar-chart
Как создать двунаправленную гистограмму? ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Как сохранить двунаправленную ассоциацию без каскады с помощью Spring Data JPA?
Anonymous » » в форуме JAVA - 0 Ответы
- 3 Просмотры
-
Последнее сообщение Anonymous
-