codelion commited on
Commit
c54e392
·
verified ·
1 Parent(s): 0bebf0b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -165
app.py CHANGED
@@ -1,176 +1,89 @@
1
  import gradio as gr
2
  import yfinance as yf
3
- import requests
4
  import numpy as np
5
  import pandas as pd
6
- import matplotlib.pyplot as plt
7
- from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
8
- import time
9
 
10
- # Polymarket GraphQL API endpoint
11
- POLYMARKET_API = "https://api.polymarket.com/graphql"
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- # Function to fetch Polymarket data
14
- def fetch_polymarket_data(search_term="S&P"):
15
  try:
16
- query = """
17
- query {
18
- markets(first: 5, searchTerm: "%s") {
19
- edges {
20
- node {
21
- id
22
- question
23
- outcomes {
24
- name
25
- price
26
- }
27
- }
28
- }
29
- }
30
- }
31
- """ % search_term
32
- response = requests.post(POLYMARKET_API, json={"query": query}, timeout=10)
33
- if response.status_code != 200:
34
- return None
35
- data = response.json()
36
- markets = data["data"]["markets"]["edges"]
37
- if not markets:
38
- return None
39
-
40
- # Parse the first relevant market
41
- for market in markets:
42
- node = market["node"]
43
- outcomes = node["outcomes"]
44
- if len(outcomes) >= 2:
45
- return {
46
- "question": node["question"],
47
- "outcomes": {outcome["name"]: float(outcome["price"]) for outcome in outcomes}
48
- }
49
- return None
50
- except Exception as e:
51
- return None
52
-
53
- # Function to fetch Yahoo Finance data with retry
54
- def fetch_yahoo_data(ticker, retries=3, delay=2):
55
- for attempt in range(retries):
56
- try:
57
- stock = yf.download(ticker, period="1y", auto_adjust=False, progress=False)
58
- if stock.empty or len(stock) < 2:
59
- return None, None, None, f"No data returned for ticker '{ticker}'. It may be invalid or lack sufficient history."
60
- daily_returns = stock["Close"].pct_change().dropna()
61
- if daily_returns.empty:
62
- return None, None, None, f"No valid returns calculated for ticker '{ticker}'. Insufficient price data."
63
- mu = daily_returns.mean() * 252 # Annualized drift
64
- sigma = daily_returns.std() * np.sqrt(252) # Annualized volatility
65
- last_price = stock["Close"][-1] # Use most recent unadjusted Close
66
- return mu, sigma, last_price, None
67
- except Exception as e:
68
- error_msg = f"Attempt {attempt + 1}/{retries} failed for ticker '{ticker}': {str(e)}"
69
- if attempt < retries - 1:
70
- time.sleep(delay) # Wait before retrying
71
- else:
72
- return None, None, None, error_msg
73
- return None, None, None, f"Failed to fetch data for '{ticker}' after {retries} attempts."
74
-
75
- # Monte Carlo Simulation with GBM
76
- def monte_carlo_simulation(S0, mu, sigma, T, N, sims, risk_factor, pm_data):
77
- dt = 1 / 252 # Daily time step
78
- steps = int(T * 252)
79
- sim_paths = np.zeros((sims, steps + 1))
80
- sim_paths[:, 0] = S0
81
-
82
- # Adjust drift based on Polymarket probabilities
83
- if pm_data and "outcomes" in pm_data:
84
- outcomes = pm_data["outcomes"]
85
- bullish_prob = outcomes.get("Yes", 0.5) if "Yes" in outcomes else 0.5
86
- bearish_prob = 1 - bullish_prob
87
- mu_bull = mu * 1.2 * risk_factor
88
- mu_bear = mu * -0.5 * risk_factor
89
- mu_adjusted = bullish_prob * mu_bull + bearish_prob * mu_bear
90
- else:
91
- mu_adjusted = mu * risk_factor
92
-
93
- for t in range(1, steps + 1):
94
- Z = np.random.standard_normal(sims)
95
- sim_paths[:, t] = sim_paths[:, t-1] * np.exp(
96
- (mu_adjusted - 0.5 * sigma**2) * dt + sigma * np.sqrt(dt) * Z
97
  )
98
-
99
- return sim_paths
100
-
101
- # Main simulation function
102
- def run_simulation(investment, ticker, horizon, num_sims, risk_factor):
103
- # Validate inputs
104
- if not ticker or investment <= 0 or horizon <= 0 or num_sims <= 0:
105
- return None, "Please provide valid inputs: positive investment, horizon, and simulations, and a ticker."
106
-
107
- # Fetch data
108
- mu, sigma, S0, error_msg = fetch_yahoo_data(ticker)
109
- if mu is None:
110
- return None, error_msg
111
-
112
- pm_data = fetch_polymarket_data("S&P")
113
-
114
- # Run Monte Carlo simulation
115
- sim_paths = monte_carlo_simulation(S0, mu, sigma, horizon, num_sims, num_sims, risk_factor, pm_data)
116
- final_values = sim_paths[:, -1] * (investment / S0) # Scale to investment amount
117
-
118
- # Create histogram
119
- fig, ax = plt.subplots(figsize=(8, 6))
120
- ax.hist(final_values, bins=50, color="skyblue", edgecolor="black")
121
- ax.set_title(f"Distribution of Final Investment Value ({ticker})")
122
- ax.set_xlabel("Final Value ($)")
123
- ax.set_ylabel("Frequency")
124
- plt.tight_layout()
125
-
126
- # Calculate stats
127
- mean_val = np.mean(final_values)
128
- min_val = np.min(final_values)
129
- max_val = np.max(final_values)
130
- std_val = np.std(final_values)
131
-
132
- # Prepare summary text
133
- summary = f"Market Data (Yahoo Finance):\n"
134
- summary += f"- Drift (μ): {mu:.4f} (based on unadjusted Close)\n"
135
- summary += f"- Volatility (σ): {sigma:.4f}\n"
136
- summary += f"- Last Close Price: ${S0:.2f}\n\n"
137
- if pm_data:
138
- summary += f"Polymarket Data:\n- Question: {pm_data['question']}\n"
139
- for outcome, prob in pm_data["outcomes"].items():
140
- summary += f"- {outcome}: {prob*100:.1f}%\n"
141
- else:
142
- summary += "Polymarket Data: No relevant market found or API unavailable.\n"
143
- summary += f"\nSimulation Results ({num_sims} runs):\n"
144
- summary += f"- Mean Final Value: ${mean_val:.2f}\n"
145
- summary += f"- Min Final Value: ${min_val:.2f}\n"
146
- summary += f"- Max Final Value: ${max_val:.2f}\n"
147
- summary += f"- Std Dev: ${std_val:.2f}"
148
-
149
- return fig, summary
150
-
151
- # Gradio UI
152
- with gr.Blocks(title="Investment Simulation Platform") as demo:
153
- gr.Markdown("# Investment Decision Simulation Platform")
154
- gr.Markdown("Simulate investment outcomes using Yahoo Finance data (unadjusted) and Polymarket probabilities.")
155
-
156
  with gr.Row():
157
- with gr.Column():
158
- investment = gr.Number(label="Investment Amount ($)", value=10000)
159
- ticker = gr.Textbox(label="Ticker Symbol (e.g., AAPL, ^GSPC)", value="AAPL")
160
- horizon = gr.Number(label="Investment Horizon (Years)", value=1)
161
- num_sims = gr.Number(label="Number of Simulations", value=1000)
162
- risk_factor = gr.Slider(0.5, 2.0, value=1.0, label="Risk Factor")
163
- submit_btn = gr.Button("Run Simulation")
164
-
165
- with gr.Column():
166
- plot_output = gr.Plot(label="Final Value Distribution")
167
- text_output = gr.Textbox(label="Simulation Summary", lines=12)
168
-
169
- submit_btn.click(
170
- fn=run_simulation,
171
- inputs=[investment, ticker, horizon, num_sims, risk_factor],
172
- outputs=[plot_output, text_output]
173
  )
174
 
175
- if __name__ == "__main__":
176
- demo.launch()
 
1
  import gradio as gr
2
  import yfinance as yf
 
3
  import numpy as np
4
  import pandas as pd
5
+ from scipy.optimize import minimize
 
 
6
 
7
+ # Define stock tickers (25 from S&P 500)
8
+ TICKERS = [
9
+ 'AAPL', 'MSFT', 'NVDA', 'AVGO', 'ADBE',
10
+ 'AMZN', 'TSLA', 'HD',
11
+ 'PG', 'COST',
12
+ 'UNH', 'JNJ', 'LLY',
13
+ 'JPM', 'GS', 'V',
14
+ 'CAT', 'UNP', 'GE',
15
+ 'XOM', 'NEE',
16
+ 'D',
17
+ 'GOOGL', 'META', 'CMCSA',
18
+ 'PLD'
19
+ ]
20
 
21
+ def optimize_portfolio(years, target_return):
 
22
  try:
23
+ data = yf.download(TICKERS, period=f"{years}y", interval="1mo")['Adj Close']
24
+ returns = data.pct_change().dropna()
25
+ mean_returns = returns.mean() * 12
26
+ cov_matrix = returns.cov() * 12
27
+
28
+ num_assets = len(TICKERS)
29
+ init_weights = np.ones(num_assets) / num_assets
30
+
31
+ def portfolio_volatility(weights):
32
+ return np.sqrt(weights @ cov_matrix @ weights)
33
+
34
+ constraints = [
35
+ {"type": "eq", "fun": lambda w: np.sum(w) - 1},
36
+ {"type": "eq", "fun": lambda w: w @ mean_returns - target_return}
37
+ ]
38
+
39
+ bounds = tuple((0, 1) for _ in range(num_assets))
40
+
41
+ result = minimize(
42
+ portfolio_volatility,
43
+ init_weights,
44
+ method="SLSQP",
45
+ bounds=bounds,
46
+ constraints=constraints
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  )
48
+
49
+ if not result.success:
50
+ return "Optimization failed. Try adjusting inputs.", None, None, None
51
+
52
+ weights = result.x
53
+ port_return = weights @ mean_returns
54
+ port_vol = np.sqrt(weights @ cov_matrix @ weights)
55
+ risk_free_rate = 0.045
56
+ sharpe_ratio = (port_return - risk_free_rate) / port_vol
57
+
58
+ df = pd.DataFrame({
59
+ "Ticker": TICKERS,
60
+ "Weight (%)": np.round(weights * 100, 2)
61
+ }).sort_values("Weight (%)", ascending=False).reset_index(drop=True)
62
+
63
+ return df, f"{port_return*100:.2f}%", f"{port_vol*100:.2f}%", f"{sharpe_ratio:.2f}"
64
+
65
+ except Exception as e:
66
+ return f"Error: {str(e)}", None, None, None
67
+
68
+ with gr.Blocks() as demo:
69
+ gr.Markdown("# 📈 Modern Portfolio Optimizer (MPT)")
70
+ gr.Markdown("Select number of years of historical data and your target annual return. This app computes the **minimum risk portfolio** of 25 S&P 500 stocks.")
71
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  with gr.Row():
73
+ years_slider = gr.Slider(1, 10, value=5, step=1, label="Years of Historical Data")
74
+ return_slider = gr.Slider(1.0, 15.0, value=5.0, step=0.1, label="Target Annual Return (%)")
75
+
76
+ run_button = gr.Button("Optimize Portfolio")
77
+
78
+ output_table = gr.Dataframe(headers=["Ticker", "Weight (%)"], label="Optimal Allocation")
79
+ ret_text = gr.Text(label="Expected Return")
80
+ vol_text = gr.Text(label="Expected Volatility")
81
+ sharpe_text = gr.Text(label="Sharpe Ratio")
82
+
83
+ run_button.click(
84
+ fn=lambda years, target: optimize_portfolio(years, target / 100),
85
+ inputs=[years_slider, return_slider],
86
+ outputs=[output_table, ret_text, vol_text, sharpe_text]
 
 
87
  )
88
 
89
+ demo.launch()