dibend commited on
Commit
6993a9d
·
verified ·
1 Parent(s): 7c7a7e8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -44
app.py CHANGED
@@ -5,42 +5,26 @@ import plotly.graph_objects as go
5
 
6
  CSV_URL = "https://gardenstatemls.stats.showingtime.com/infoserv/s-v1/kpou-Asg"
7
 
8
- def monte_carlo_live(T=1.0, steps=12, n_paths=100):
9
  try:
10
- # Load CSV and skip metadata
11
  df = pd.read_csv(CSV_URL, skiprows=9)
12
- df = df.dropna(axis=1, how='all') # Remove empty columns
13
-
14
- # Use only first 2 columns: Date and Median Sales Price
15
  df = df.iloc[:, :2]
16
  df.columns = ['Date', 'Median Sales Price']
17
-
18
- # Convert price to numeric after removing $ and commas
19
- df['Median Sales Price'] = pd.to_numeric(
20
- df['Median Sales Price'].replace('[\$,]', '', regex=True),
21
- errors='coerce'
22
- )
23
-
24
- # Parse date with full month names like "January 2009"
25
  df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
26
-
27
- # Drop any rows with bad values
28
  df = df.dropna(subset=['Date', 'Median Sales Price'])
29
-
30
- # Sort chronologically
31
  df = df.sort_values(by='Date')
32
 
33
- # Calculate log returns
34
  prices = df['Median Sales Price'].values
35
  if len(prices) < 2:
36
  raise ValueError("Not enough valid price data after cleaning.")
37
  returns = np.diff(np.log(prices))
38
 
39
- mu = np.mean(returns) * 12 # annualized return
40
- sigma = np.std(returns) * np.sqrt(12) # annualized volatility
41
- S0 = prices[-1] # latest price
42
 
43
- # Monte Carlo simulation
44
  dt = T / steps
45
  paths = np.zeros((steps + 1, n_paths))
46
  paths[0] = S0
@@ -48,57 +32,69 @@ def monte_carlo_live(T=1.0, steps=12, n_paths=100):
48
  rand = np.random.normal(0, 1, n_paths)
49
  paths[t] = paths[t - 1] * np.exp((mu - 0.5 * sigma ** 2) * dt + sigma * np.sqrt(dt) * rand)
50
 
51
- # Create time axis
52
  time = np.linspace(0, T, steps + 1)
53
 
54
- # Plotly figure
55
- fig = go.Figure()
56
-
57
  for i in range(n_paths):
58
- fig.add_trace(go.Scatter(x=time, y=paths[:, i], mode='lines', line=dict(width=1), showlegend=False))
59
 
60
- # Mean and median paths
61
  mean_path = paths.mean(axis=1)
62
  median_path = np.median(paths, axis=1)
63
- fig.add_trace(go.Scatter(x=time, y=mean_path, name='Mean Path', line=dict(width=3, dash='dash')))
64
- fig.add_trace(go.Scatter(x=time, y=median_path, name='Median Path', line=dict(width=3, dash='dot')))
65
 
66
- fig.update_layout(
67
  title="Monte Carlo Simulation — Garden State MLS Median Sales Price Forecast",
68
  xaxis_title="Years Ahead",
69
  yaxis_title="Simulated Price ($)",
70
  height=600
71
  )
72
 
73
- summary = f"Simulated {n_paths} paths from latest price ${S0:.2f}.\n" \
74
- f"Annualized Drift (μ): {mu * 100:.2f}%, Volatility (σ): {sigma * 100:.2f}%"
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
- return fig, summary
77
 
78
  except Exception as e:
79
- fig = go.Figure()
80
- fig.update_layout(title="Error", annotations=[{
81
  "text": str(e),
82
  "xref": "paper",
83
  "yref": "paper",
84
  "showarrow": False,
85
  "font": {"size": 16}
86
  }])
87
- return fig, f"Error: {e}"
88
 
89
  # Gradio UI
90
  with gr.Blocks() as demo:
91
- gr.Markdown("## 📊 Monte Carlo Simulation: Live MLS Median Sales Price")
92
 
93
  with gr.Row():
94
- years = gr.Slider(0.1, 5.0, value=1.0, step=0.1, label="Forecast Horizon (Years)")
95
- steps = gr.Slider(12, 120, value=12, step=12, label="Time Steps")
96
- paths = gr.Slider(10, 300, value=100, step=10, label="Number of Simulated Paths")
97
 
98
  run_button = gr.Button("Run Simulation")
99
- plot = gr.Plot()
100
- summary = gr.Textbox(label="Simulation Summary")
101
 
102
- run_button.click(monte_carlo_live, inputs=[years, steps, paths], outputs=[plot, summary])
 
 
 
 
 
 
103
 
104
  demo.launch()
 
5
 
6
  CSV_URL = "https://gardenstatemls.stats.showingtime.com/infoserv/s-v1/kpou-Asg"
7
 
8
+ def monte_carlo_live(T=1.0, steps=120, n_paths=1000):
9
  try:
 
10
  df = pd.read_csv(CSV_URL, skiprows=9)
11
+ df = df.dropna(axis=1, how='all')
 
 
12
  df = df.iloc[:, :2]
13
  df.columns = ['Date', 'Median Sales Price']
14
+ df['Median Sales Price'] = pd.to_numeric(df['Median Sales Price'].replace('[\$,]', '', regex=True), errors='coerce')
 
 
 
 
 
 
 
15
  df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
 
 
16
  df = df.dropna(subset=['Date', 'Median Sales Price'])
 
 
17
  df = df.sort_values(by='Date')
18
 
 
19
  prices = df['Median Sales Price'].values
20
  if len(prices) < 2:
21
  raise ValueError("Not enough valid price data after cleaning.")
22
  returns = np.diff(np.log(prices))
23
 
24
+ mu = np.mean(returns) * 12
25
+ sigma = np.std(returns) * np.sqrt(12)
26
+ S0 = prices[-1]
27
 
 
28
  dt = T / steps
29
  paths = np.zeros((steps + 1, n_paths))
30
  paths[0] = S0
 
32
  rand = np.random.normal(0, 1, n_paths)
33
  paths[t] = paths[t - 1] * np.exp((mu - 0.5 * sigma ** 2) * dt + sigma * np.sqrt(dt) * rand)
34
 
 
35
  time = np.linspace(0, T, steps + 1)
36
 
37
+ forecast_fig = go.Figure()
 
 
38
  for i in range(n_paths):
39
+ forecast_fig.add_trace(go.Scatter(x=time, y=paths[:, i], mode='lines', line=dict(width=1), showlegend=False))
40
 
 
41
  mean_path = paths.mean(axis=1)
42
  median_path = np.median(paths, axis=1)
43
+ forecast_fig.add_trace(go.Scatter(x=time, y=mean_path, name='Mean Path', line=dict(width=3, dash='dash')))
44
+ forecast_fig.add_trace(go.Scatter(x=time, y=median_path, name='Median Path', line=dict(width=3, dash='dot')))
45
 
46
+ forecast_fig.update_layout(
47
  title="Monte Carlo Simulation — Garden State MLS Median Sales Price Forecast",
48
  xaxis_title="Years Ahead",
49
  yaxis_title="Simulated Price ($)",
50
  height=600
51
  )
52
 
53
+ historical_fig = go.Figure()
54
+ historical_fig.add_trace(go.Scatter(x=df['Date'], y=df['Median Sales Price'], mode='lines+markers', name='Median Sales Price'))
55
+ historical_fig.update_layout(
56
+ title="Historical Median Sales Prices (Garden State MLS)",
57
+ xaxis_title="Date",
58
+ yaxis_title="Median Sales Price ($)",
59
+ height=500
60
+ )
61
+
62
+ summary = f"""**Simulation Summary**
63
+ - Starting Price: ${S0:,.2f}
64
+ - Simulated {n_paths} paths for {T:.1f} years
65
+ - Annualized Drift (μ): {mu * 100:.2f}%
66
+ - Annualized Volatility (σ): {sigma * 100:.2f}%"""
67
 
68
+ return historical_fig, forecast_fig, summary
69
 
70
  except Exception as e:
71
+ err_fig = go.Figure()
72
+ err_fig.update_layout(title="Error", annotations=[{
73
  "text": str(e),
74
  "xref": "paper",
75
  "yref": "paper",
76
  "showarrow": False,
77
  "font": {"size": 16}
78
  }])
79
+ return err_fig, err_fig, f"Error: {e}"
80
 
81
  # Gradio UI
82
  with gr.Blocks() as demo:
83
+ gr.Markdown("## 🏡 Monte Carlo Simulation: Garden State MLS Median Sales Price Forecast")
84
 
85
  with gr.Row():
86
+ years = gr.Slider(0.1, 10.0, value=1.0, step=0.1, label="Forecast Horizon (Years)")
87
+ steps = gr.Slider(12, 240, value=120, step=12, label="Time Steps")
88
+ paths = gr.Slider(10, 2000, value=1000, step=10, label="Number of Simulated Paths")
89
 
90
  run_button = gr.Button("Run Simulation")
 
 
91
 
92
+ with gr.Row():
93
+ historical_plot = gr.Plot(label="📈 Historical Prices")
94
+ simulation_plot = gr.Plot(label="🔮 Forecast Simulation")
95
+
96
+ summary = gr.Markdown(label="📝 Simulation Summary")
97
+
98
+ run_button.click(fn=monte_carlo_live, inputs=[years, steps, paths], outputs=[historical_plot, simulation_plot, summary])
99
 
100
  demo.launch()