-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamlit_app.py
More file actions
2976 lines (2835 loc) · 116 KB
/
Copy pathstreamlit_app.py
File metadata and controls
2976 lines (2835 loc) · 116 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Streamlit dashboard: HDB resale EDA (maps, clusters, forecast, graph, yields)."""
from __future__ import annotations
import json
import os
import sys
from pathlib import Path
from typing import Any
from urllib.parse import quote_plus
import networkx as nx
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import requests
import streamlit as st
from streamlit_folium import st_folium
if Path(__file__).resolve().parent.joinpath("src").exists():
_src = Path(__file__).resolve().parent / "src"
if str(_src) not in sys.path:
sys.path.insert(0, str(_src))
from singapore_eda.clustering import cluster_interpretation, cluster_kmeans
from singapore_eda.constants import (
DEFAULT_RAW_CSV,
DEFAULT_RENT_CSV,
HDB_CITATION_URL,
HDB_DATASTORE_SEARCH,
HDB_MEDIAN_RENT_CITATION_URL,
HDB_MEDIAN_RENT_RESOURCE_ID,
PLANNING_AREA_GEOJSON_POLL_URL,
)
from singapore_eda.display_table import (
block_table_for_display,
cluster_medians_for_display,
correlation_edges_for_display,
forecast_rmse_for_display,
gross_yield_table_for_display,
storey_table_for_display,
)
from singapore_eda.eip import eip_match_stats
from singapore_eda.features import add_bto_reference_features, model_design_subset
from singapore_eda.feedback import append_feedback
from singapore_eda.forecaster_config import load_forecaster_config
from singapore_eda.forecaster_v1 import predict_with_explain
from singapore_eda.forecasting import backtest_rmse, monthly_median_price
from singapore_eda.gov_http import get_gov_client
from singapore_eda.graph_analytics import (
correlation_community_table,
correlation_edges_dataframe,
correlation_graph,
graph_summary,
spatial_adjacency_graph,
town_price_pivot,
unweighted_spatial_edge_table,
)
from singapore_eda.housing_finance import (
GrantSelection,
HouseholdProfile,
HousingFinanceScenario,
HousingType,
LoanType,
RateSegment,
load_policy_defaults,
run_housing_finance,
)
from singapore_eda.housing_finance.calculators import make_fixed_then_sora_segments
from singapore_eda.housing_finance.formatters import (
cashflow_table,
government_return_table,
itemized_cost_table,
profit_breakdown_table,
)
from singapore_eda.insights import build_insights
from singapore_eda.mapviz import (
block_street_table,
folium_choropleth_by_name,
geo_median_value_dict,
)
from singapore_eda.pipeline import load_enriched
from singapore_eda.rent_cache import age_hours, rent_csv_is_fresh
from singapore_eda.rent_ingest import download_median_rent
from singapore_eda.rental_yields import gross_yield_table
from singapore_eda.stats import (
numeric_correlation,
ols_log_price,
ols_log_price_with_storey,
ttest_resale_by_group,
)
from singapore_eda.storey import median_price_by_storey_stratum
from singapore_eda.viz import (
fig_correlation_heatmap,
fig_flat_type_box,
fig_median_price_by_town,
fig_price_over_time,
fig_town_median_lines_with_forecast,
)
_ROOT = Path(__file__).resolve().parent
_DEFAULT_FIXTURE = _ROOT / "tests" / "fixtures" / "hdb_sample.csv"
_ALT_BIG_CSV = _ROOT / "data" / "data" / "sales_data.csv"
_RENT_CAND = _ROOT / str(DEFAULT_RENT_CSV)
_FIX_RENT = _ROOT / "tests" / "fixtures" / "median_rent_sample.csv"
_DEFAULT_RENT = str(_RENT_CAND) if _RENT_CAND.is_file() else str(_FIX_RENT)
_PLANNING_GEO = _ROOT / "data" / "reference" / "planning_areas.geojson"
_TINY_GEO = _ROOT / "tests" / "fixtures" / "planning_areas_tiny.geojson"
_REQUIRED_RESALE_COLS = {"month", "resale_price"}
_FORECASTER_MODEL_PATH = _ROOT / "models" / "forecaster_v1" / "model.joblib"
_FORECASTER_META_PATH = _ROOT / "models" / "forecaster_v1" / "metadata.json"
_FORECASTER_CFG_PATH = _ROOT / "configs" / "forecaster_v1.yaml"
_HOUSING_FINANCE_CFG_PATH = _ROOT / "configs" / "housing_finance_v1.yaml"
_BTO_REFERENCE_PATH = _ROOT / "data" / "reference" / "hdb_bto_reference.csv"
def _is_truthy(v: str | None) -> bool:
if v is None:
return False
return str(v).strip().lower() in {"1", "true", "yes", "on"}
def _setting(name: str) -> str | None:
# Prefer real environment variables, then Streamlit secrets for Cloud deploys.
raw = os.environ.get(name)
if raw is not None:
return raw
try:
sec = st.secrets.get(name)
except (AttributeError, FileNotFoundError, OSError, RuntimeError):
sec = None
if sec is None:
return None
return str(sec)
def _on_streamlit_cloud() -> bool:
# Streamlit Cloud exposes this in hosted apps.
return _is_truthy(os.environ.get("STREAMLIT_SHARING_MODE"))
def _default_bool_env(name: str, cloud_default: bool, local_default: bool) -> bool:
raw = _setting(name)
if raw is not None:
return _is_truthy(raw)
return cloud_default if _on_streamlit_cloud() else local_default
def _default_geo() -> str:
if _PLANNING_GEO.exists():
return str(_PLANNING_GEO)
if _TINY_GEO.exists():
return str(_TINY_GEO)
return ""
def _bootstrap_resale_if_missing(default_path: str) -> str:
def _has_required_cols(p: Path) -> bool:
try:
cols = pd.read_csv(p, nrows=0).columns
except (OSError, ValueError, pd.errors.ParserError):
return False
norm = {str(c).strip().lower().replace(" ", "_") for c in cols}
return _REQUIRED_RESALE_COLS.issubset(norm)
p = Path(default_path)
if p.exists() and _has_required_cols(p):
return default_path
if p.exists() and not _has_required_cols(p):
st.sidebar.warning(
f"CSV at `{p}` does not look like HDB resale data "
f"(needs columns: {sorted(_REQUIRED_RESALE_COLS)})."
)
if _ALT_BIG_CSV.exists():
if _has_required_cols(_ALT_BIG_CSV):
st.sidebar.info(f"Using bundled resale CSV: `{_ALT_BIG_CSV}`")
return str(_ALT_BIG_CSV)
st.sidebar.warning(
f"Bundled CSV `{_ALT_BIG_CSV}` is not HDB-format; skipping."
)
auto_fetch = _default_bool_env(
"SINGAPORE_EDA_AUTO_DOWNLOAD_ON_MISSING",
cloud_default=True,
local_default=False,
)
if auto_fetch:
max_rows_raw = _setting("SINGAPORE_EDA_BOOTSTRAP_MAX_ROWS") or "20000"
try:
max_rows = max(1000, int(str(max_rows_raw).strip()))
except ValueError:
max_rows = 20000
try:
from singapore_eda.download_data import download_hdb_resale
p.parent.mkdir(parents=True, exist_ok=True)
n = download_hdb_resale(
p,
max_rows=max_rows,
latest_first=True,
skip_if_fresh_hours=24.0,
)
st.sidebar.success(f"Fetched {n:,} resale rows from data.gov.sg.")
if p.exists() and _has_required_cols(p):
return str(p)
if p.exists():
st.sidebar.warning(
f"Downloaded file `{p}` is missing required HDB columns; falling back."
)
except (OSError, ValueError, RuntimeError) as ex:
st.sidebar.warning(f"Auto-download failed; using fixture fallback. ({ex})")
if _DEFAULT_FIXTURE.exists():
st.sidebar.info(
"Using fallback fixture (small sample). "
"Set `SINGAPORE_EDA_AUTO_DOWNLOAD_ON_MISSING=1` to auto-fetch data."
)
return str(_DEFAULT_FIXTURE)
return default_path
def _bootstrap_rent_if_missing(default_path: str) -> str:
p = Path(default_path)
if p.exists():
return default_path
auto_fetch = _default_bool_env(
"SINGAPORE_EDA_AUTO_DOWNLOAD_RENT_ON_MISSING",
cloud_default=True,
local_default=False,
)
if auto_fetch:
rid = (_setting("HDB_MEDIAN_RENT_RESOURCE_ID") or HDB_MEDIAN_RENT_RESOURCE_ID).strip()
max_rows_raw = _setting("SINGAPORE_EDA_RENT_BOOTSTRAP_MAX_ROWS") or "200000"
try:
max_rows = max(1000, int(str(max_rows_raw).strip()))
except ValueError:
max_rows = 200000
try:
p.parent.mkdir(parents=True, exist_ok=True)
n = download_median_rent(
p,
rid,
max_rows=max_rows,
skip_if_fresh_hours=24.0,
)
st.sidebar.success(f"Fetched {n:,} rent rows from data.gov.sg.")
if p.exists():
return str(p)
except (OSError, ValueError, RuntimeError) as ex:
st.sidebar.warning(f"Rent auto-download failed; using fixture fallback. ({ex})")
if _FIX_RENT.exists():
return str(_FIX_RENT)
return default_path
def _bootstrap_geo_if_tiny_or_missing(default_path: str) -> str:
p = Path(default_path) if default_path else Path("")
is_tiny = p.exists() and p.name == _TINY_GEO.name
if p.exists() and not is_tiny:
return str(p)
auto_fetch = _default_bool_env(
"SINGAPORE_EDA_AUTO_FETCH_GEO_ON_TINY",
cloud_default=True,
local_default=False,
)
if auto_fetch:
try:
body = get_gov_client().get_json(
PLANNING_AREA_GEOJSON_POLL_URL,
timeout=90,
use_cache=False,
use_file_pace=True,
)
if body.get("code") != 0:
raise RuntimeError(str(body.get("errMsg") or body.get("errorMsg") or "poll failed"))
blob_url = (body.get("data") or {}).get("url")
if not blob_url:
raise RuntimeError("poll-download response missing URL")
r = requests.get(str(blob_url), timeout=180)
r.raise_for_status()
_PLANNING_GEO.parent.mkdir(parents=True, exist_ok=True)
_PLANNING_GEO.write_bytes(r.content)
st.sidebar.success("Fetched full planning-area GeoJSON.")
return str(_PLANNING_GEO)
except (OSError, ValueError, RuntimeError, requests.RequestException) as ex:
st.sidebar.warning(f"Geo auto-fetch failed; keeping current GeoJSON. ({ex})")
return default_path
def _ols_coef_table(model: Any, top_n: int = 12) -> pd.DataFrame:
ci = model.conf_int()
rows: list[dict[str, object]] = []
for term, beta in model.params.items():
if term == "Intercept":
continue
lo = float(ci.loc[term, 0]) if term in ci.index else float("nan")
hi = float(ci.loc[term, 1]) if term in ci.index else float("nan")
pct = (pow(2.718281828459045, float(beta)) - 1.0) * 100.0
rows.append(
{
"term": str(term),
"coef_log": float(beta),
"approx_price_change_pct": pct,
"p_value": float(model.pvalues.get(term, float("nan"))),
"ci95_log_low": lo,
"ci95_log_high": hi,
}
)
if not rows:
return pd.DataFrame()
out = pd.DataFrame(rows)
# Keep continuous drivers first, then strongest remaining terms by magnitude.
priority = ["floor_area_sqm", "remaining_lease_years", "C(storey_band)"]
pri_mask = out["term"].map(lambda t: any(k in str(t) for k in priority))
pri = out[pri_mask].copy()
rest = out[~out.index.isin(pri.index)].copy()
rest = rest.sort_values(by="approx_price_change_pct", key=lambda s: s.abs(), ascending=False)
out2 = pd.concat([pri, rest.head(max(0, top_n - len(pri)))], ignore_index=True)
out2 = out2.sort_values(by="p_value", na_position="last")
return out2
def _render_ols_readable(model: Any, title: str, add_storey_note: bool = False) -> None:
st.subheader(title)
c0, c1, c2, c3 = st.columns(4)
c0.metric("Rows used", f"{int(model.nobs):,}")
c1.metric("R-squared", f"{float(model.rsquared):.3f}")
c2.metric("Adj. R-squared", f"{float(model.rsquared_adj):.3f}")
c3.metric("F-test p-value", f"{float(model.f_pvalue):.2e}")
st.markdown(
"""
**What this means to you**
- **What OLS solves here:** it estimates each factor's relationship with resale price while
**holding the other included factors fixed** (e.g. area, lease, town group, and optionally
storey band).
- **Higher is better?** not universally. A **higher predicted price** can be good for
sellers/owners, but usually worse for buyers seeking affordability.
- **How to read signs:** a **positive** coefficient means higher expected price; **negative**
means lower expected price (within this dataset and controls).
- **Decision use:** use this as a **structured explanation tool**, not a valuation engine or
investment signal.
"""
)
if add_storey_note:
st.caption(
"Storey coefficients are relative to a hidden reference band. They are descriptive, "
"not proof of causal floor premiums."
)
coef_tbl = _ols_coef_table(model)
if not coef_tbl.empty:
st.markdown("**Most relevant coefficients (human-readable)**")
st.dataframe(coef_tbl, width="stretch", height=340)
with st.expander("Raw statistical output (advanced)", expanded=False):
st.text(model.summary().as_text()[:4000])
PROJECT_AND_METHOD = """
### What problem does this app address?
Exploratory analysis of **HDB resale transactions**: how median prices differ by **town / planning
area**, **block**, **storey band**, and **time**; a simple view of **gross rental yield** when
median rent is joined; **k-means segments** to group similar homes; a **trend + short forecast** per
town; and a **co-movement** graph between town price series. It does **not** provide valuation or
investment advice.
### What data do you use?
- **Resale (required):** HDB *Resale flat prices* open data (CSV) — at least `month`, `town`,
`resale_price`, and ideally `flat_type`, `block`, `street_name`, `storey_range`, `floor_area_sqm`.
- **Optional rent (for yields):** HDB
[Median rent by town and flat type (quarterly)](https://data.gov.sg/datasets/d_23000a00c52996c55106084ed0339566/view)
via `hdb-rent-download` (see `HDB_MEDIAN_RENT_RESOURCE_ID`). CSV fields: `quarter`, `town`,
`flat_type`, `median_rent` (whole‑flat medians; flat-type codes are normalised to match resale
e.g. `3-RM` → `3 ROOM`).
- **Optional map:** planning-area **GeoJSON** (e.g. from `python scripts/fetch_reference_geo.py`).
HDB’s published **median rent is for the whole unit** for that `flat_type` in that place/period, not
a bedroom. Very old resales matched to a recent rent file will look “wrong” in yield — you must
align **period and cohort**; the app joins on **quarter + town + flat_type**.
### How is data stored in this project?
- **In this repo / your machine:** raw CSVs under `data/raw/`, small reference tables under
`data/reference/`, optional downloaded GeoJSON there.
- **In the app:** the selected resale CSV and rent CSV are **read in memory** (Pandas) — there is
no separate database unless you add one. For automation, a pipeline can write **Parquet**
(see `scripts/run_analysis.py`).
### What models or methods are used?
- **Descriptive & plots:** medians, groupby, time aggregation.
- **Regression (OLS, Overview tab):** *Ordinary Least Squares* on **log(resale price)**. We model
**log** price (not levels) so a common multiplicative story applies: the same *percentage* change
in e.g. area is easier to compare across towns. Fixed effects are *dummy variables for* **town
group** (see “town coverage” below) plus **floor area (m²)** and **remaining lease (years, from
HDB’s text)**. **R²** is *in‑sample* explanatory power; it is **not** a forecast accuracy score
and does not validate trading decisions.
- **OLS + storey bands:** the same OLS, plus **categorical storey bands** (low / mid / high) from
HDB’s *storey range* (a band, not the exact floor). Coefficients are **relative to a reference
category**; use them as stylised *within file* structure, not as causal “floor premia” without
controls for block and time.
- **Two-sample t-test (Overview):** *Welch’s t-test* (unequal variances) on **raw** resale prices
for two *town* groups. It asks whether the two town samples have **different mean** prices, under
normal-ish data; it does **not** control for size, age, or lease, so a difference can reflect
*composition* of flats, not a “town effect” in the causal sense.
- **Clustering:** k-means (standardized features) for **segmentation labels**; labels are
interpreted against sample medians in the Clusters tab.
- **Time series:** Holt–Winters **ETS** on **monthly median** by town; history must be long enough
(~24+ months) for a meaningful seasonal fit.
- **Graphs — correlation network:** edges where Pearson **|ρ|** between **monthly median**
**price series** (by town) exceeds your sidebar threshold. **Not geography** (layout is a force
algorithm).
- **Graphs — planning-area touch (neighbour) graph:** **polygons that share a boundary** in your
GeoJSON. Install optional **`pip install -e ".[geo]"` (geopandas)**; we build edges with a spatial
join (`touches`) and fall back to a slower geometry loop if needed.
### Towns in the sample (“~80% rule”)
For regression, rare towns are collapsed into a single **OTHER** category so the model is stable.
We keep the **smallest** set of towns that together make up a target share of *rows* (default
**80%** of transactions). The rest are **OTHER**; they are still in charts and the raw data.
Override with env **`SINGAPORE_EDA_TOWN_COVERAGE`** (e.g. `1.0` to keep every town as its own
group — many dummy levels) or in code `top_towns=…` with `town_coverage=None`.
### Remaining lease
The CSV gives **lease text** and we compute `remaining_lease_years` as a *decimal* (e.g. 92.4167 ≈
92 years and 5 months in our parser). The app also shows **`remaining_lease_label`**: the **HDB
string** when present, else a compact **Y/M/D** style so “92.4167” is not the only readout.
### Caching and refreshing downloads
- **Resale:** after each `hdb-download` run, a **sidecar** `*.meta.json` (next to the CSV) records
CKAN **`api_total`**. If you set **`SINGAPORE_EDA_SKIP_DOWNLOAD_IF_FRESH_HOURS=…`** and
**`SINGAPORE_EDA_CHECK_NEW_DATA=1`**, a **fresh** local file is still re-fetched when the
*live* API **total** exceeds the **stored** total (indicating new records on the portal).
- **Comprehensive data:** the default Jan‑2017+ tranche is one resource; *older* tranches and merges
are available via `hdb-download --list-tranches` and `hdb-resale-merge` (see help when schemas
align).
- **geo:** for planning-area map and neighbour graph, `python scripts/fetch_reference_geo.py` and
`pip install -e ".[geo]"`.
### How would you deploy, and how do users interact?
- **This Streamlit app:** `streamlit run streamlit_app.py` — users explore in the **browser**;
no model is “served” as an API; it’s an interactive dashboard.
- **Static report:** `quarto render` under `quarto/` and host on **GitHub Pages** (read-only, no
Python in-browser).
- **A production option** (not in this bundle): precompute features and predictions to a
**database or API** (e.g. FastAPI + Postgres) and build a read-only or authenticated UI — only if
you need scale, access control, or scheduled scoring.
---
**Limits:** the open HDB file has **no building coordinates**; we cannot draw true “pins per block”
on a basemap. The **Map** uses planning-area outlines; **Block** is a table (town / street / block
medians) from the same rows.
"""
def _town_coverage_env() -> float | None:
raw = str(os.environ.get("SINGAPORE_EDA_TOWN_COVERAGE", "")).strip()
if not raw:
return 0.8
if raw.lower() in ("all", "1", "full", "1.0"):
return 1.0
try:
return max(0.0, min(1.0, float(raw)))
except ValueError:
return 0.8
@st.cache_data(show_spinner=True)
def _load(path: str) -> pd.DataFrame:
return load_enriched(
path,
top_towns=15,
town_coverage=_town_coverage_env(),
)
def _fig_network(g: nx.Graph) -> go.Figure:
if g.number_of_nodes() == 0:
return go.Figure()
pos = nx.spring_layout(g, seed=42)
edge_x: list[float] = []
edge_y: list[float] = []
for u, v in g.edges():
edge_x.extend([pos[u][0], pos[v][0], None])
edge_y.extend([pos[u][1], pos[v][1], None])
fig = go.Figure()
line_kw = dict(width=1, color="#888")
fig.add_trace(
go.Scatter(
x=edge_x, y=edge_y, mode="lines", line=line_kw, hoverinfo="none"
)
)
nx_ = [pos[n][0] for n in g.nodes()]
ny = [pos[n][1] for n in g.nodes()]
fig.add_trace(
go.Scatter(
x=nx_,
y=ny,
mode="markers+text",
text=list(g.nodes()),
textposition="top center",
marker=dict(size=12, color="#1f77b4"),
)
)
t = "Network layout (for shape only — not a geographic map)"
fig.update_layout(title=t, showlegend=False)
return fig
def _fig_housing_cost_mix(cost_df: pd.DataFrame) -> go.Figure:
if cost_df.empty:
return go.Figure()
top = cost_df[cost_df["item"] != "Total cost of ownership"].copy()
fig = go.Figure(
data=[
go.Pie(
labels=top["item"],
values=top["amount_sgd"],
hole=0.45,
)
]
)
fig.update_layout(title="Cost mix (excluding grand total)")
return fig
def _fig_cashflow_trend(cft: pd.DataFrame) -> go.Figure:
if cft.empty:
return go.Figure()
view = cft.head(240).copy()
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=view["month"],
y=view["instalment"],
mode="lines",
name="Instalment",
)
)
fig.add_trace(
go.Scatter(
x=view["month"],
y=view["cash_used"],
mode="lines",
name="Cash used",
)
)
fig.add_trace(
go.Scatter(
x=view["month"],
y=view["cpf_used"],
mode="lines",
name="CPF used",
)
)
fig.update_layout(
title="Monthly loan cashflow trend",
xaxis_title="Month",
yaxis_title="SGD",
)
return fig
def _fig_profit_waterfall(pf: pd.DataFrame) -> go.Figure:
if pf.empty:
return go.Figure()
vals = {
str(r["item"]): float(r["amount_sgd"])
for _, r in pf.iterrows()
}
gross = vals.get("Gross sale proceeds", 0.0)
fee = vals.get("Sale agent fee", 0.0)
loan = vals.get("Loan redemption", 0.0)
user_contrib = vals.get("User contributions", 0.0)
net = vals.get("Net proceeds after obligations", 0.0)
profit = vals.get("Estimated profit", 0.0)
fig = go.Figure(
go.Waterfall(
orientation="v",
measure=["absolute", "relative", "relative", "total", "relative", "total"],
x=[
"Gross sale",
"Agent fee",
"Loan redemption",
"Net proceeds",
"User contributions",
"Estimated profit",
],
y=[gross, -fee, -loan, net, -user_contrib, profit],
)
)
fig.update_layout(title="Profit waterfall")
return fig
def _fig_repricing_savings(rs: Any) -> go.Figure:
fig = go.Figure()
fig.add_trace(
go.Bar(
x=["Gross interest savings", "Switch costs", "Net savings"],
y=[rs.gross_interest_savings, -rs.total_switch_cost, rs.net_savings],
)
)
fig.update_layout(title="Repricing/refinancing savings bridge", yaxis_title="SGD")
return fig
def _fig_compare_cashflow(cft_a: pd.DataFrame, cft_b: pd.DataFrame) -> go.Figure:
fig = go.Figure()
if not cft_a.empty:
a = cft_a.head(240)
fig.add_trace(
go.Scatter(
x=a["month"],
y=a["net_cash_outflow"],
mode="lines",
name="Scenario A net outflow",
)
)
if not cft_b.empty:
b = cft_b.head(240)
fig.add_trace(
go.Scatter(
x=b["month"],
y=b["net_cash_outflow"],
mode="lines",
name="Scenario B net outflow",
)
)
fig.update_layout(
title="Scenario comparison: monthly net cash outflow",
xaxis_title="Month",
yaxis_title="SGD",
)
return fig
def _fig_compare_summary(result_a: Any, result_b: Any) -> go.Figure:
fig = go.Figure()
categories = ["Estimated profit", "Net proceeds", "Total ownership cost"]
vals_a = [
float(result_a.profit.estimated_profit),
float(result_a.profit.net_proceeds_after_obligations),
float(result_a.costs.total_cost_of_ownership),
]
vals_b = [
float(result_b.profit.estimated_profit),
float(result_b.profit.net_proceeds_after_obligations),
float(result_b.costs.total_cost_of_ownership),
]
fig.add_trace(go.Bar(name="Scenario A", x=categories, y=vals_a))
fig.add_trace(go.Bar(name="Scenario B", x=categories, y=vals_b))
fig.update_layout(barmode="group", title="Scenario A vs B: key outcome comparison")
return fig
def _residential_bsd(amount: float) -> float:
tiers = (
(180_000.0, 0.01),
(180_000.0, 0.02),
(640_000.0, 0.03),
(500_000.0, 0.04),
(1_500_000.0, 0.05),
(float("inf"), 0.06),
)
remaining = max(0.0, amount)
duty = 0.0
for cap, rate in tiers:
taxable = min(remaining, cap)
if taxable <= 0:
break
duty += taxable * rate
remaining -= taxable
return float(np.floor(max(1.0, duty))) if amount > 0 else 0.0
def _absd_rate_pct(profile: HouseholdProfile, property_count_after_buy: int) -> float:
pcount = max(1, int(property_count_after_buy))
if profile == HouseholdProfile.SG_SG or profile == HouseholdProfile.SINGLE_CITIZEN:
return 0.0 if pcount <= 1 else (20.0 if pcount == 2 else 30.0)
if profile == HouseholdProfile.SG_PR:
return 5.0 if pcount <= 1 else (30.0 if pcount == 2 else 35.0)
if profile == HouseholdProfile.PR_PR:
return 5.0 if pcount <= 1 else (30.0 if pcount == 2 else 35.0)
return 60.0
def _ehg_amount(average_income: float, household: HouseholdProfile) -> float:
income = max(0.0, average_income)
if household == HouseholdProfile.SINGLE_CITIZEN:
if income > 4500:
return 0.0
steps = int(income // 250.0)
return max(0.0, 60_000.0 - (steps * 2_500.0))
if household in (HouseholdProfile.SG_SG, HouseholdProfile.SG_PR, HouseholdProfile.PR_PR):
if income > 9000:
return 0.0
steps = int(income // 500.0)
return max(0.0, 120_000.0 - (steps * 5_000.0))
return 0.0
def _fig_debt_vs_rental_subsidy(
cft: pd.DataFrame,
*,
initial_loan: float,
rental_tax_rate_pct: float,
) -> go.Figure:
df = cft.copy()
tax_mult = max(0.0, min(1.0, 1.0 - (rental_tax_rate_pct / 100.0)))
df["rental_net"] = df["rental_inflow"] * tax_mult
df["cum_rental_net"] = df["rental_net"].cumsum()
df["cum_cash_outflow"] = df["net_cash_outflow"].clip(lower=0.0).cumsum()
df["cum_principal"] = df["principal"].cumsum()
df["remaining_balance"] = (
initial_loan - df["cum_principal"]
).clip(lower=0.0)
df["debt_free_progress_pct"] = (
(df["cum_principal"] / max(1.0, initial_loan)) * 100.0
).clip(lower=0.0, upper=100.0)
df["rental_subsidy_pct"] = (
df["cum_rental_net"] / df["cum_cash_outflow"].replace(0.0, np.nan) * 100.0
).fillna(0.0).clip(lower=0.0, upper=300.0)
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=df["month"],
y=df["remaining_balance"],
mode="lines",
name="Remaining debt (SGD)",
line=dict(width=2),
)
)
fig.add_trace(
go.Scatter(
x=df["month"],
y=df["cum_rental_net"],
mode="lines",
name="Cumulative net rental (SGD)",
line=dict(width=2),
)
)
fig.add_trace(
go.Scatter(
x=df["month"],
y=df["debt_free_progress_pct"],
mode="lines",
name="Debt-free progress (%)",
yaxis="y2",
line=dict(width=2, dash="dot"),
)
)
fig.add_trace(
go.Scatter(
x=df["month"],
y=df["rental_subsidy_pct"],
mode="lines",
name="Rental subsidy of cash outflow (%)",
yaxis="y2",
line=dict(width=2, dash="dash"),
)
)
fig.update_layout(
title="Debt-free journey vs rental subsidy (after rental tax)",
xaxis_title="Month",
yaxis_title="SGD",
yaxis2=dict(title="Progress %", overlaying="y", side="right"),
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="left", x=0.0),
)
return fig
def _inject_minimal_ui() -> None:
st.markdown(
"""
<style>
.block-container {padding-top: 1.0rem; padding-bottom: 1.5rem; max-width: 1240px;}
h1, h2, h3 {letter-spacing: -0.02em;}
.ux-h2 {font-size: 1.25rem; font-weight: 650; margin: 0.2rem 0 0.35rem 0; color: var(--text-color);}
.ux-divider {
display: flex;
align-items: center;
gap: 0.55rem;
margin: 1.0rem 0 0.65rem 0;
color: var(--text-color);
}
.ux-divider .icon {
width: 1.7rem;
height: 1.7rem;
border-radius: 999px;
background: rgba(59, 130, 246, 0.18);
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 0.95rem;
}
.ux-divider .title {
font-size: 1.02rem;
font-weight: 680;
}
.ux-divider-line {
flex: 1;
min-width: 40px;
border-top: 1px solid rgba(148, 163, 184, 0.45);
}
.ux-note {
color: var(--text-color);
border-left: 3px solid rgba(96, 165, 250, 0.6);
background: rgba(30, 58, 138, 0.18);
border-radius: 8px;
padding: 0.55rem 0.75rem;
margin: 0.3rem 0 0.75rem 0;
}
[data-testid="stMetricValue"] {font-size: 1.1rem;}
[data-testid="stDataFrame"] {border-radius: 8px;}
.ux-metric {
border-radius: 12px;
border: 1px solid rgba(148, 163, 184, 0.35);
background: linear-gradient(165deg, rgba(30, 41, 59, 0.18), rgba(71, 85, 105, 0.10));
padding: 0.75rem 0.85rem;
min-height: 96px;
}
.ux-metric .top {
display: flex;
align-items: center;
gap: 0.4rem;
color: var(--text-color);
font-size: 0.85rem;
font-weight: 620;
margin-bottom: 0.35rem;
}
.ux-metric .val {
color: var(--text-color);
font-size: 1.28rem;
font-weight: 760;
line-height: 1.25;
}
.ux-banner {
border-radius: 14px;
border: 1px solid rgba(96, 165, 250, 0.45);
background: linear-gradient(90deg, rgba(30, 64, 175, 0.25), rgba(2, 132, 199, 0.12));
padding: 0.9rem 1rem;
margin-bottom: 0.7rem;
}
.ux-hero {
border-radius: 16px;
border: 1px solid rgba(96, 165, 250, 0.45);
background: radial-gradient(
circle at 12% 18%, rgba(59, 130, 246, 0.24), rgba(15, 23, 42, 0.18) 45%
),
linear-gradient(120deg, rgba(30, 64, 175, 0.20), rgba(15, 23, 42, 0.08));
padding: 1.05rem 1.15rem;
margin: 0.2rem 0 0.9rem 0;
}
.ux-hero .eyebrow {
font-size: 0.74rem;
text-transform: uppercase;
letter-spacing: 0.08em;
font-weight: 700;
color: rgba(147, 197, 253, 0.96);
margin-bottom: 0.32rem;
}
.ux-hero h3 {
margin: 0 0 0.3rem 0;
color: var(--text-color);
font-size: 1.18rem;
}
.ux-hero p {
margin: 0;
color: var(--text-color);
line-height: 1.35rem;
}
.ux-banner h3 {
margin: 0 0 0.25rem 0;
font-size: 1.1rem;
}
.ux-banner p {
margin: 0;
color: var(--text-color);
}
</style>
""",
unsafe_allow_html=True,
)
def _h2(text: str) -> None:
st.markdown(f"<div class='ux-h2'>{text}</div>", unsafe_allow_html=True)
def _section_divider(title: str, icon: str = "◉") -> None:
st.markdown(
(
"<div class='ux-divider'>"
f"<span class='icon'>{icon}</span>"
f"<span class='title'>{title}</span>"
"<span class='ux-divider-line'></span>"
"</div>"
),
unsafe_allow_html=True,
)
def _hero_card(title: str, subtitle: str, eyebrow: str = "Dashboard") -> None:
st.markdown(
(
"<div class='ux-hero'>"
f"<div class='eyebrow'>{eyebrow}</div>"
f"<h3>{title}</h3>"
f"<p>{subtitle}</p>"
"</div>"
),
unsafe_allow_html=True,
)
def _metric_card(label: str, value: str, icon: str) -> None:
st.markdown(
(
"<div class='ux-metric'>"
f"<div class='top'><span>{icon}</span><span>{label}</span></div>"
f"<div class='val'>{value}</div>"
"</div>"
),
unsafe_allow_html=True,
)
def _why(shows: str, solves: str) -> None:
st.markdown(
f"<div class='ux-note'><b>What this shows:</b> {shows}<br>"
f"<b>Why this helps users:</b> {solves}</div>",
unsafe_allow_html=True,
)
@st.cache_data(show_spinner=False, ttl=60 * 60 * 6)
def _load_bto_reference() -> pd.DataFrame:
cols = ["project_name", "town", "flat_type", "flat_model", "lease_commence_date"]
if _BTO_REFERENCE_PATH.exists():
ref = pd.read_csv(_BTO_REFERENCE_PATH)
missing = [c for c in cols if c not in ref.columns]
if missing:
raise ValueError(f"BTO reference missing columns: {missing}")
return ref[cols].dropna(subset=["town", "flat_type"]).copy()
query = quote_plus("hdb bto launch project lease commence")
search_url = f"https://data.gov.sg/api/action/package_search?q={query}&rows=5"
try:
body = get_gov_client().get_json(search_url, timeout=60, use_cache=True)
except (RuntimeError, ValueError, requests.RequestException):
return pd.DataFrame(columns=cols)
results = ((body or {}).get("result") or {}).get("results") or []
for item in results:
resources = item.get("resources") or []
for r in resources:
rid = str(r.get("id") or "").strip()
if not rid:
continue
try:
raw = get_gov_client().get_json(
HDB_DATASTORE_SEARCH,
params={"resource_id": rid, "limit": 10000},
timeout=120,
use_cache=True,
)
except (RuntimeError, ValueError, requests.RequestException):
continue
records = ((raw or {}).get("result") or {}).get("records") or []
if not records:
continue
candidate = pd.DataFrame(records)
alias_map = {
"project_name": ["project_name", "project", "projecttitle", "name"],
"town": ["town", "estate"],
"flat_type": ["flat_type", "flat", "room_type"],
"flat_model": ["flat_model", "model"],
"lease_commence_date": ["lease_commence_date", "lease_commence_year", "lease_year"],
}
out = pd.DataFrame()
for target, aliases in alias_map.items():
hit = next((a for a in aliases if a in candidate.columns), None)
if hit:
out[target] = candidate[hit]
elif target == "flat_model":
out[target] = "MODEL A"
else:
out[target] = np.nan
out["lease_commence_date"] = pd.to_numeric(out["lease_commence_date"], errors="coerce")
out = out.dropna(subset=["town", "flat_type", "lease_commence_date"])
if len(out) >= 20:
out = out[cols].copy()
out["project_name"] = out["project_name"].fillna("BTO Project")
return out
return pd.DataFrame(columns=cols)
def _valid_storey_ranges(
frame: pd.DataFrame,