File size: 9,220 Bytes
adbf0d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import folium
from streamlit_folium import folium_static
import streamlit as st

def create_price_distribution_chart(data, predicted_price=None):
    """
    Crée un histogramme de la distribution des prix avec la prédiction
    """
    if data is None or 'price' not in data.columns:
        return None
    
    fig = px.histogram(
        data, 
        x='price', 
        nbins=50,
        title="     Distribution des Prix Immobiliers",
        labels={'price': 'Prix ($)', 'count': 'Nombre de propriétés'},
        color_discrete_sequence=['#3498db']
    )
    
    # Ajouter une ligne verticale pour la prédiction
    if predicted_price is not None:
        fig.add_vline(
            x=predicted_price, 
            line_dash="dash", 
            line_color="red",
            annotation_text=f"Votre prédiction: ${predicted_price:,.0f}",
            annotation_position="top right"
        )
    
    fig.update_layout(
        template="plotly_dark",
        plot_bgcolor='rgba(0,0,0,0)',
        paper_bgcolor='rgba(0,0,0,0)',
        font=dict(color='#D4DCFF'),
        title_font_size=20,
        showlegend=False
    )
    
    return fig

def create_feature_impact_chart(data, feature_name, predicted_price=None):
    """
    Crée un graphique montrant l'impact d'une caractéristique sur le prix
    """
    if data is None or feature_name not in data.columns or 'price' not in data.columns:
        return None
    
    # Calculer la moyenne des prix par valeur de la caractéristique
    feature_impact = data.groupby(feature_name)['price'].mean().reset_index()
    
    fig = px.line(
        feature_impact,
        x=feature_name,
        y='price',
        title=f"     Impact de {feature_name} sur le Prix",
        labels={'price': 'Prix Moyen ($)', feature_name: feature_name.title()},
        markers=True
    )
    
    # Ajouter une ligne horizontale pour la prédiction
    if predicted_price is not None:
        fig.add_hline(
            y=predicted_price,
            line_dash="dash",
            line_color="red",
            annotation_text=f"Votre prédiction: ${predicted_price:,.0f}",
            annotation_position="top right"
        )
    
    fig.update_layout(
        template="plotly_dark",
        plot_bgcolor='rgba(0,0,0,0)',
        paper_bgcolor='rgba(0,0,0,0)',
        font=dict(color='#D4DCFF'),
        title_font_size=16,
        title=dict(
            x=0.5,
            xanchor='center',
            y=0.95,
            yanchor='top',
            pad=dict(t=20, b=30, l=20, r=20)
        )
    )
    
    return fig

def create_price_vs_area_chart(data, predicted_price=None, predicted_area=None):
    """
    Crée un graphique de dispersion prix vs surface
    """
    if data is None or 'sqft_living' not in data.columns or 'price' not in data.columns:
        return None
    
    fig = px.scatter(
        data,
        x='sqft_living',
        y='price',
        title="     Prix vs Surface Habitable",
        labels={'sqft_living': 'Surface Habitable (pieds²)', 'price': 'Prix ($)'},
        opacity=0.6,
        color_discrete_sequence=['#3498db']
    )
    
    # Ajouter le point de prédiction
    if predicted_price is not None and predicted_area is not None:
        fig.add_scatter(
            x=[predicted_area],
            y=[predicted_price],
            mode='markers',
            marker=dict(size=15, color='red', symbol='star'),
            name='Votre prédiction',
            showlegend=True
        )
    
    fig.update_layout(
        template="plotly_dark",
        plot_bgcolor='rgba(0,0,0,0)',
        paper_bgcolor='rgba(0,0,0,0)',
        font=dict(color='#D4DCFF'),
        title_font_size=16
    )
    
    return fig

def create_correlation_heatmap(data):
    """
    Crée une heatmap de corrélation entre les caractéristiques
    """
    if data is None:
        return None
    
    # Sélectionner les colonnes numériques
    numeric_cols = data.select_dtypes(include=[np.number]).columns
    if len(numeric_cols) < 2:
        return None
    
    correlation_matrix = data[numeric_cols].corr()
    
    fig = px.imshow(
        correlation_matrix,
        title="     Matrice de Corrélation des Caractéristiques",
        color_continuous_scale='RdBu',
        aspect="auto"
    )
    
    fig.update_layout(
        template="plotly_dark",
        plot_bgcolor='rgba(0,0,0,0)',
        paper_bgcolor='rgba(0,0,0,0)',
        font=dict(color='#D4DCFF'),
        title_font_size=16
    )
    
    return fig

def create_interactive_map(data, lat=None, long=None, predicted_price=None):
    """
    Crée une carte interactive avec les propriétés et la prédiction
    """
    if data is None or 'lat' not in data.columns or 'long' not in data.columns:
        return None
    
    # Calculer le centre de la carte
    center_lat = data['lat'].mean() if lat is None else lat
    center_long = data['long'].mean() if long is None else long
    
    # Créer la carte
    m = folium.Map(
        location=[center_lat, center_long],
        zoom_start=10,
        tiles='cartodbpositron'
    )
    
    # Ajouter les propriétés existantes (échantillon pour éviter la surcharge)
    sample_data = data.sample(min(100, len(data)))
    
    for idx, row in sample_data.iterrows():
        folium.CircleMarker(
            location=[row['lat'], row['long']],
            radius=3,
            popup=f"Prix: ${row['price']:,.0f}<br>Surface: {row['sqft_living']} pieds²",
            color='blue',
            fill=True,
            fillOpacity=0.7
        ).add_to(m)
    
    # Ajouter la prédiction si disponible
    if lat is not None and long is not None and predicted_price is not None:
        folium.Marker(
            location=[lat, long],
            popup=f"Votre prédiction: ${predicted_price:,.0f}",
            icon=folium.Icon(color='red', icon='star')
        ).add_to(m)
    
    return m

def create_price_by_zipcode_chart(data, predicted_price=None, predicted_zipcode=None):
    """
    Crée un graphique des prix moyens par code postal
    """
    if data is None or 'zipcode' not in data.columns or 'price' not in data.columns:
        return None
    
    # Calculer le prix moyen par code postal
    zipcode_prices = data.groupby('zipcode')['price'].mean().reset_index()
    zipcode_prices = zipcode_prices.sort_values('price', ascending=False).head(20)
    
    fig = px.bar(
        zipcode_prices,
        x='zipcode',
        y='price',
        title="     Prix Moyen par Code Postal (Top 20)",
        labels={'price': 'Prix Moyen ($)', 'zipcode': 'Code Postal'},
        color='price',
        color_continuous_scale='viridis'
    )
    
    # Ajouter une ligne horizontale pour la prédiction
    if predicted_price is not None:
        fig.add_hline(
            y=predicted_price,
            line_dash="dash",
            line_color="red",
            annotation_text=f"Votre prédiction: ${predicted_price:,.0f}",
            annotation_position="top right"
        )
    
    fig.update_layout(
        template="plotly_dark",
        plot_bgcolor='rgba(0,0,0,0)',
        paper_bgcolor='rgba(0,0,0,0)',
        font=dict(color='#D4DCFF'),
        title_font_size=16,
        xaxis_tickangle=-45,
        title=dict(
            x=0.5,
            xanchor='center',
            y=0.95,
            yanchor='top',
            pad=dict(t=20, b=30, l=20, r=20)
        )
    )
    
    return fig

def create_comparison_dashboard(data, predicted_price, input_features):
    """
    Crée un tableau de bord de comparaison
    """
    if data is None:
        return None
    
    # Calculer les statistiques de comparaison
    stats = {
        'Prix moyen du marché': f"${data['price'].mean():,.0f}",
        'Prix médian du marché': f"${data['price'].median():,.0f}",
        'Votre prédiction': f"${predicted_price:,.0f}",
        'Différence avec la moyenne': f"${predicted_price - data['price'].mean():,.0f}",
        'Pourcentage vs moyenne': f"{((predicted_price / data['price'].mean()) - 1) * 100:.1f}%"
    }
    
    # Créer un graphique de comparaison
    comparison_data = pd.DataFrame({
        'Métrique': ['Prix Moyen', 'Prix Médian', 'Votre Prédiction'],
        'Prix': [data['price'].mean(), data['price'].median(), predicted_price]
    })
    
    fig = px.bar(
        comparison_data,
        x='Métrique',
        y='Prix',
        title="     Comparaison avec le Marché",
        color='Métrique',
        color_discrete_map={
            'Prix Moyen': '#3498db',
            'Prix Médian': '#2ecc71',
            'Votre Prédiction': '#e74c3c'
        }
    )
    
    fig.update_layout(
        template="plotly_dark",
        plot_bgcolor='rgba(0,0,0,0)',
        paper_bgcolor='rgba(0,0,0,0)',
        font=dict(color='#D4DCFF'),
        title_font_size=16,
        showlegend=False,
        title=dict(
            x=0.5,
            xanchor='center',
            y=0.95,
            yanchor='top',
            pad=dict(t=20, b=30, l=20, r=20)
        )
    )
    
    return fig, stats