"""
Visualization module for Dubai HomeIQ Dashboard
Contains Plotly chart components
"""
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
import numpy as np
from typing import Optional, List, Dict
from config import COLORS
def plot_price_trend(df: pd.DataFrame, area_name: str = None,
price_column: str = 'MEDIAN_RATE_PER_SQFT') -> go.Figure:
"""
Plot price trend over time
Args:
df: DataFrame with YEAR and price data
area_name: Optional area name for title
price_column: Column name for price data
Returns:
Plotly figure
"""
if df.empty or 'YEAR' not in df.columns or price_column not in df.columns:
return go.Figure()
df = df.sort_values('YEAR')
fig = go.Figure()
if area_name:
title = f"Price Trend: {area_name.title()}"
# Single area line
fig.add_trace(go.Scatter(
x=df['YEAR'],
y=df[price_column],
mode='lines+markers',
name=area_name.title(),
line=dict(color=COLORS['primary'], width=3),
marker=dict(size=8, color=COLORS['primary'])
))
else:
title = "Price Trends by Area"
# Multiple areas
areas = df['AREA_EN'].unique()[:10] # Limit to 10 areas
colors = px.colors.qualitative.Set3
for i, area in enumerate(areas):
area_data = df[df['AREA_EN'] == area].sort_values('YEAR')
fig.add_trace(go.Scatter(
x=area_data['YEAR'],
y=area_data[price_column],
mode='lines+markers',
name=area.title(),
line=dict(color=colors[i % len(colors)], width=2),
marker=dict(size=6)
))
fig.update_layout(
title=title,
xaxis_title="Year",
yaxis_title="Price per sqft (AED)",
hovermode='closest',
template='plotly_white',
height=500,
showlegend=True if not area_name else False
)
return fig
def plot_rental_yield_distribution(df: pd.DataFrame) -> go.Figure:
"""
Plot rental yield distribution histogram
Args:
df: DataFrame with yield data
Returns:
Plotly figure
"""
if df.empty or 'yield' not in df.columns:
return go.Figure()
fig = go.Figure()
fig.add_trace(go.Histogram(
x=df['yield'],
nbinsx=30,
marker_color=COLORS['info'],
opacity=0.7,
name='Rental Yield Distribution'
))
fig.update_layout(
title="Rental Yield Distribution",
xaxis_title="Yield (%)",
yaxis_title="Frequency",
template='plotly_white',
height=400
)
return fig
def plot_buyer_score_ranking(df: pd.DataFrame, top_n: int = 10) -> go.Figure:
"""
Plot top areas by buyer score (horizontal bar chart)
Args:
df: DataFrame with area and buyer_score columns
top_n: Number of top areas to show
Returns:
Plotly figure
"""
if df.empty or 'buyer_score' not in df.columns:
return go.Figure()
top_areas = df.nlargest(top_n, 'buyer_score')
fig = go.Figure()
# Color bars based on score
colors = [COLORS['success'] if score >= 70 else
COLORS['warning'] if score >= 50 else
COLORS['danger']
for score in top_areas['buyer_score']]
fig.add_trace(go.Bar(
y=top_areas['area'].str.title(),
x=top_areas['buyer_score'],
orientation='h',
marker=dict(color=colors),
text=[f"{score:.1f}" for score in top_areas['buyer_score']],
textposition='auto',
name='Buyer Score'
))
fig.update_layout(
title=f"Top {top_n} Areas by Buyer Score",
xaxis_title="Buyer Score",
yaxis_title="Area",
template='plotly_white',
height=400,
yaxis={'categoryorder': 'total ascending'}
)
return fig
def plot_supply_vs_demand(supply_df: pd.DataFrame, sales_df: pd.DataFrame) -> go.Figure:
"""
Plot supply vs demand bubble chart
Args:
supply_df: Supply data with units
sales_df: Sales data with transactions
Returns:
Plotly figure
"""
if supply_df.empty or sales_df.empty:
return go.Figure()
# Aggregate by area
supply_agg = supply_df.groupby('area_name_en')['no_of_units'].sum().reset_index()
sales_agg = sales_df.groupby('AREA_EN')['SALE_TRANSACTIONS'].sum().reset_index()
# Merge
merged = supply_agg.merge(
sales_agg,
left_on='area_name_en',
right_on='AREA_EN',
how='inner'
)
if merged.empty:
return go.Figure()
fig = go.Figure()
fig.add_trace(go.Scatter(
x=merged['SALE_TRANSACTIONS'],
y=merged['no_of_units'],
mode='markers',
marker=dict(
size=merged['no_of_units'] / 100,
color=merged['no_of_units'],
colorscale='Viridis',
showscale=True,
sizemode='diameter',
sizeref=merged['no_of_units'].max() / 100
),
text=merged['area_name_en'].str.title(),
hovertemplate='%{text}
Transactions: %{x}
Units: %{y}',
name='Supply vs Demand'
))
fig.update_layout(
title="Supply vs Demand Analysis",
xaxis_title="Sales Transactions",
yaxis_title="Supply Units",
template='plotly_white',
height=500
)
return fig
def plot_market_health_heatmap(df: pd.DataFrame) -> go.Figure:
"""
Plot market health heatmap by area and year
Args:
df: DataFrame with area, year, and health_index columns
Returns:
Plotly figure
"""
if df.empty or 'health_index' not in df.columns:
return go.Figure()
# Pivot for heatmap
pivot_df = df.pivot_table(
values='health_index',
index='AREA_EN',
columns='YEAR',
aggfunc='mean'
)
fig = go.Figure(data=go.Heatmap(
z=pivot_df.values,
x=pivot_df.columns,
y=[area.title() for area in pivot_df.index],
colorscale='RdYlGn',
text=pivot_df.values,
texttemplate='%{text:.1f}',
textfont={"size": 10},
colorbar=dict(title="Health Index")
))
fig.update_layout(
title="Market Health Index Heatmap",
xaxis_title="Year",
yaxis_title="Area",
template='plotly_white',
height=600
)
return fig
def plot_roi_comparison(df: pd.DataFrame, areas: List[str] = None) -> go.Figure:
"""
Plot ROI comparison chart
Args:
df: DataFrame with ROI data
areas: List of areas to compare
Returns:
Plotly figure
"""
if df.empty:
return go.Figure()
if areas:
df = df[df['area'].isin(areas)]
fig = go.Figure()
fig.add_trace(go.Bar(
x=df['area'].str.title(),
y=df.get('capital_appreciation', df.get('roi', 0)),
name='Capital Appreciation',
marker_color=COLORS['primary']
))
if 'rental_yield' in df.columns:
fig.add_trace(go.Bar(
x=df['area'].str.title(),
y=df['rental_yield'],
name='Rental Yield',
marker_color=COLORS['success']
))
fig.update_layout(
title="ROI Comparison",
xaxis_title="Area",
yaxis_title="Return (%)",
barmode='group',
template='plotly_white',
height=400
)
return fig
def plot_forecast_with_confidence(historical: pd.DataFrame,
forecast: pd.DataFrame,
area_name: str) -> go.Figure:
"""
Plot forecast with confidence intervals
Args:
historical: Historical data
forecast: Forecast data with confidence intervals
area_name: Area name for title
Returns:
Plotly figure
"""
fig = go.Figure()
# Historical data
fig.add_trace(go.Scatter(
x=historical['YEAR'],
y=historical['MEDIAN_RATE_PER_SQFT'],
mode='lines+markers',
name='Historical',
line=dict(color=COLORS['primary'], width=2)
))
# Forecast
if not forecast.empty and 'ds' in forecast.columns:
fig.add_trace(go.Scatter(
x=forecast['ds'],
y=forecast['yhat'],
mode='lines',
name='Forecast',
line=dict(color=COLORS['success'], width=2, dash='dash')
))
# Confidence intervals
if 'yhat_lower' in forecast.columns and 'yhat_upper' in forecast.columns:
fig.add_trace(go.Scatter(
x=forecast['ds'],
y=forecast['yhat_upper'],
mode='lines',
name='Upper Bound',
line=dict(width=0),
showlegend=False
))
fig.add_trace(go.Scatter(
x=forecast['ds'],
y=forecast['yhat_lower'],
mode='lines',
name='Confidence Interval',
fill='tonexty',
fillcolor='rgba(33, 150, 243, 0.2)',
line=dict(width=0)
))
fig.update_layout(
title=f"Price Forecast: {area_name.title()}",
xaxis_title="Year",
yaxis_title="Price per sqft (AED)",
template='plotly_white',
height=500,
hovermode='x unified'
)
return fig
def create_kpi_cards(metrics: Dict[str, float]) -> List[go.Figure]:
"""
Create KPI card visualizations
Args:
metrics: Dictionary of metric names and values
Returns:
List of Plotly figures (one per metric)
"""
cards = []
for metric_name, value in metrics.items():
fig = go.Figure()
# Determine color based on value
if 'score' in metric_name.lower() or 'health' in metric_name.lower():
color = COLORS['success'] if value >= 70 else \
COLORS['warning'] if value >= 50 else \
COLORS['danger']
else:
color = COLORS['primary']
fig.add_trace(go.Indicator(
mode="number+delta",
value=value,
title={"text": metric_name},
delta={'reference': 50},
number={'font': {'size': 40}, 'valueformat': '.1f'},
domain={'x': [0, 1], 'y': [0, 1]}
))
fig.update_layout(
height=200,
paper_bgcolor='white',
font={'color': color}
)
cards.append(fig)
return cards