File size: 24,754 Bytes
1acd6e1
 
 
 
 
277a313
1acd6e1
 
dc2be38
0f95c64
 
1acd6e1
dc2be38
 
 
277a313
4fb476c
277a313
4fb476c
0f95c64
 
 
 
 
 
 
 
 
 
 
 
4fb476c
 
dc2be38
 
 
828f0f0
 
 
3268778
4a31bd8
3268778
4a31bd8
3268778
 
 
828f0f0
3268778
 
 
828f0f0
4a31bd8
828f0f0
 
 
 
 
 
4a31bd8
 
 
 
 
828f0f0
 
 
 
4a31bd8
0f95c64
0b12519
0f95c64
277a313
 
 
 
 
 
828f0f0
4a31bd8
828f0f0
 
 
4a31bd8
828f0f0
 
 
3268778
 
 
4a31bd8
1acd6e1
dc2be38
0b12519
0f95c64
0b12519
 
0f95c64
0b12519
 
 
 
 
 
 
0f95c64
 
 
 
 
 
 
 
 
 
 
0b12519
0f95c64
 
 
 
 
 
277a313
 
 
0f95c64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b12519
 
 
dc2be38
3268778
4a31bd8
1acd6e1
 
 
 
4a31bd8
0f95c64
277a313
 
 
 
 
 
 
 
 
 
dd6e62d
 
 
 
277a313
 
 
 
 
 
 
 
 
 
 
 
0f95c64
dd6e62d
0f95c64
dd6e62d
 
 
 
 
0f95c64
277a313
 
 
 
 
 
 
 
 
 
 
 
 
0f95c64
 
 
277a313
 
 
 
 
 
 
 
 
 
0f95c64
 
 
277a313
 
 
 
 
 
0f95c64
 
 
 
1acd6e1
277a313
 
 
 
 
 
dc2be38
 
 
 
 
0f95c64
 
 
 
dc2be38
 
1acd6e1
dc2be38
1acd6e1
dc2be38
1acd6e1
dc2be38
1acd6e1
 
dc2be38
4a31bd8
dc2be38
 
0f95c64
277a313
0f95c64
277a313
 
 
0f95c64
 
 
 
 
 
dd6e62d
 
 
 
0f95c64
 
 
 
 
 
dd6e62d
 
0f95c64
dd6e62d
 
 
 
0f95c64
277a313
 
0f95c64
dd6e62d
277a313
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd6e62d
277a313
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd6e62d
 
 
 
 
0f95c64
dd6e62d
 
1acd6e1
3268778
4a31bd8
3268778
277a313
3268778
277a313
0f95c64
277a313
 
 
 
 
0f95c64
 
277a313
 
0f95c64
dd6e62d
277a313
dd6e62d
 
 
 
0f95c64
277a313
 
0f95c64
dd6e62d
277a313
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd6e62d
277a313
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd6e62d
 
 
 
1acd6e1
3268778
 
 
dc2be38
dd6e62d
0f95c64
 
 
 
 
 
 
 
 
 
 
277a313
 
 
 
 
 
 
 
 
 
 
 
 
0f95c64
 
dd6e62d
 
dc2be38
762f595
 
 
 
0f95c64
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
import streamlit as st
import pandas as pd
import numpy as np
from prophet import Prophet
import plotly.express as px
import plotly.graph_objects as go
import matplotlib.pyplot as plt
from datetime import date
from pathlib import Path
import matplotlib.font_manager as fm
import matplotlib as mpl

# -------------------------------------------------
# CONFIG ------------------------------------------
# -------------------------------------------------
CSV_PATH = Path("2025-domae.csv")
MACRO_START, MACRO_END = "1996-01-01", "2030-12-31"
MICRO_START, MICRO_END = "2024-01-01", "2026-12-31"

# ํ•œ๊ธ€ ํฐํŠธ ์„ค์ •
font_list = [f.name for f in fm.fontManager.ttflist if 'gothic' in f.name.lower() or 
             'gulim' in f.name.lower() or 'malgun' in f.name.lower() or 
             'nanum' in f.name.lower() or 'batang' in f.name.lower()]

if font_list:
    font_name = font_list[0]
    plt.rcParams['font.family'] = font_name
    mpl.rcParams['axes.unicode_minus'] = False
else:
    plt.rcParams['font.family'] = 'DejaVu Sans'

st.set_page_config(page_title="ํ’ˆ๋ชฉ๋ณ„ ๊ฐ€๊ฒฉ ์˜ˆ์ธก", page_icon="๐Ÿ“ˆ", layout="wide")

# -------------------------------------------------
# UTILITIES ---------------------------------------
# -------------------------------------------------
DATE_CANDIDATES = {"date", "ds", "ymd", "๋‚ ์งœ", "prce_reg_mm", "etl_ldg_dt"}
ITEM_CANDIDATES = {"item", "ํ’ˆ๋ชฉ", "code", "category", "pdlt_nm", "spcs_nm"}
PRICE_CANDIDATES = {"price", "y", "value", "๊ฐ€๊ฒฉ", "avrg_prce"}


def _standardize_columns(df: pd.DataFrame) -> pd.DataFrame:
    """Standardize column names to date/item/price and deduplicate."""
    col_map = {}
    for c in df.columns:
        lc = c.lower()
        if lc in DATE_CANDIDATES:
            col_map[c] = "date"
        elif lc in PRICE_CANDIDATES:
            col_map[c] = "price"
        elif lc in ITEM_CANDIDATES:
            # first hit as item, second as species
            if "item" not in col_map.values():
                col_map[c] = "item"
            else:
                col_map[c] = "species"
    df = df.rename(columns=col_map)

    # โ”€โ”€ handle duplicated columns after rename โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    if df.columns.duplicated().any():
        df = df.loc[:, ~df.columns.duplicated()]

    # โ”€โ”€ index datetime to column โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    if "date" not in df.columns and df.index.dtype.kind == "M":
        df.reset_index(inplace=True)
        df.rename(columns={df.columns[0]: "date"}, inplace=True)

    # โ”€โ”€ convert YYYYMM string to datetime โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    if "date" in df.columns and pd.api.types.is_object_dtype(df["date"]):
        if len(df) > 0:
            sample = str(df["date"].iloc[0])
            if sample.isdigit() and len(sample) == 6:  # YYYYMM ํ˜•์‹ ํ™•์ธ
                # ์›” ๋ง์ผ๋กœ ๋ณ€ํ™˜ (YYYYMM -> YYYY-MM-DD)
                df["date"] = pd.to_datetime(df["date"].astype(str), format="%Y%m", errors="coerce")
                df["date"] = df["date"] + pd.offsets.MonthEnd(0)  # ํ•ด๋‹น ์›”์˜ ๋งˆ์ง€๋ง‰ ๋‚ ๋กœ ์„ค์ •
            elif sample.isdigit() and len(sample) == 8:  # YYYYMMDD ํ˜•์‹
                df["date"] = pd.to_datetime(df["date"].astype(str), format="%Y%m%d", errors="coerce")

    # โ”€โ”€ build item from pdlt_nm + spcs_nm if needed โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    if "item" not in df.columns and {"pdlt_nm", "spcs_nm"}.issubset(df.columns):
        df["item"] = df["pdlt_nm"].str.strip() + "-" + df["spcs_nm"].str.strip()

    # โ”€โ”€ merge item + species โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    if {"item", "species"}.issubset(df.columns):
        df["item"] = df["item"].astype(str).str.strip() + "-" + df["species"].astype(str).str.strip()
        df.drop(columns=["species"], inplace=True)

    return df


@st.cache_data(show_spinner=False)
def load_data() -> pd.DataFrame:
    """Load price data from CSV file."""
    try:
        if not CSV_PATH.exists():
            st.error(f"๐Ÿ’พ {CSV_PATH} ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")
            st.stop()
            
        st.sidebar.info(f"{CSV_PATH} ํŒŒ์ผ์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ต๋‹ˆ๋‹ค.")
        
        # CSV ํŒŒ์ผ ์ง์ ‘ ๋กœ๋“œ
        df = pd.read_csv(CSV_PATH)
        st.sidebar.success(f"CSV ๋ฐ์ดํ„ฐ ๋กœ๋“œ ์™„๋ฃŒ: {len(df)}๊ฐœ ํ–‰")
        
        # ์›๋ณธ ๋ฐ์ดํ„ฐ ํ˜•ํƒœ ํ™•์ธ
        st.sidebar.write("์›๋ณธ ๋ฐ์ดํ„ฐ ์ปฌ๋Ÿผ:", list(df.columns))
        
        df = _standardize_columns(df)
        st.sidebar.write("ํ‘œ์ค€ํ™” ํ›„ ์ปฌ๋Ÿผ:", list(df.columns))

        missing = {c for c in ["date", "item", "price"] if c not in df.columns}
        if missing:
            st.error(f"ํ•„์ˆ˜ ์ปฌ๋Ÿผ ๋ˆ„๋ฝ: {', '.join(missing)} โ€” ํŒŒ์ผ ์ปฌ๋Ÿผ๋ช…์„ ํ™•์ธํ•˜์„ธ์š”.")
            st.stop()

        # ๋‚ ์งœ ๋ณ€ํ™˜
        before_date_convert = len(df)
        df["date"] = pd.to_datetime(df["date"], errors="coerce")
        after_date_convert = df.dropna(subset=["date"]).shape[0]
        if before_date_convert != after_date_convert:
            st.warning(f"๋‚ ์งœ ๋ณ€ํ™˜ ์ค‘ {before_date_convert - after_date_convert}๊ฐœ ํ–‰์ด ์ œ์™ธ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.")

        # ๊ฐ€๊ฒฉ ๋ฐ์ดํ„ฐ ์ •์ˆ˜ํ˜•์œผ๋กœ ๋ณ€ํ™˜ (์ˆซ์ž๊ฐ€ ์•„๋‹Œ ๊ฐ’ ์ œ๊ฑฐ)
        df["price"] = pd.to_numeric(df["price"], errors="coerce")
        
        # NA ๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ
        before_na_drop = len(df)
        df = df.dropna(subset=["date", "item", "price"])
        after_na_drop = len(df)
        if before_na_drop != after_na_drop:
            st.warning(f"NA ์ œ๊ฑฐ ์ค‘ {before_na_drop - after_na_drop}๊ฐœ ํ–‰์ด ์ œ์™ธ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.")
        
        df.sort_values("date", inplace=True)
        
        # ๋ฐ์ดํ„ฐ ๋‚ ์งœ ๋ฒ”์œ„ ํ™•์ธ
        if len(df) > 0:
            st.sidebar.write(f"๋ฐ์ดํ„ฐ ๋‚ ์งœ ๋ฒ”์œ„: {df['date'].min().strftime('%Y-%m-%d')} ~ {df['date'].max().strftime('%Y-%m-%d')}")
            st.sidebar.write(f"์ด ํ’ˆ๋ชฉ ์ˆ˜: {df['item'].nunique()}")
        else:
            st.error("์œ ํšจํ•œ ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค!")
            
        return df
    except Exception as e:
        st.error(f"๋ฐ์ดํ„ฐ ๋กœ๋“œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}")
        # ์˜ค๋ฅ˜ ์ƒ์„ธ ์ •๋ณด ํ‘œ์‹œ
        import traceback
        st.code(traceback.format_exc())
        st.stop()


@st.cache_data(show_spinner=False)
def get_items(df: pd.DataFrame):
    return sorted(df["item"].unique())


@st.cache_data(show_spinner=False, ttl=3600)
def fit_prophet(df: pd.DataFrame, horizon_end: str, monthly=False, changepoint_prior_scale=0.05):
    """
    Prophet ๋ชจ๋ธ์„ ํ•™์Šต์‹œํ‚ค๊ณ  ์˜ˆ์ธกํ•ฉ๋‹ˆ๋‹ค.
    
    Args:
        df: ํ•™์Šต ๋ฐ์ดํ„ฐ (date, price ์ปฌ๋Ÿผ ํ•„์š”)
        horizon_end: ์˜ˆ์ธก ์ข…๋ฃŒ์ผ
        monthly: ์›” ๋‹จ์œ„ ์˜ˆ์ธก ์—ฌ๋ถ€
        changepoint_prior_scale: ๋ณ€ํ™”์  ๋ฏผ๊ฐ๋„ (๋‚ฎ์„์ˆ˜๋ก ๊ณผ์ ํ•ฉ ๊ฐ์†Œ)
    """
    # Make a copy and ensure we have data
    df = df.copy()
    df = df.dropna(subset=["date", "price"])
    
    # ์ด์ƒ์น˜ ์ œ๊ฑฐ (99 ํผ์„ผํƒ€์ผ ์ดˆ๊ณผ ๊ฐ€๊ฒฉ ์ œ์™ธ)
    upper_limit = df["price"].quantile(0.99)
    df = df[df["price"] <= upper_limit]
    
    # ์ค‘๋ณต ๋‚ ์งœ ์ฒ˜๋ฆฌ
    if monthly:
        # ์›” ๋‹จ์œ„๋กœ ์ง‘๊ณ„
        df["year_month"] = df["date"].dt.strftime('%Y-%m')
        df = df.groupby("year_month").agg({"date": "first", "price": "mean"}).reset_index(drop=True)
    else:
        # ์ผ ๋‹จ์œ„๋กœ ์ง‘๊ณ„
        df = df.groupby("date")["price"].mean().reset_index()
    
    if len(df) < 2:
        st.warning(f"๋ฐ์ดํ„ฐ ํฌ์ธํŠธ๊ฐ€ ๋ถ€์กฑํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ์ธก์„ ์œ„ํ•ด์„œ๋Š” ์ตœ์†Œ 2๊ฐœ ์ด์ƒ์˜ ์œ ํšจ ๋ฐ์ดํ„ฐ๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. (ํ˜„์žฌ {len(df)}๊ฐœ)")
        return None, None
    
    # Convert to Prophet format
    prophet_df = df.rename(columns={"date": "ds", "price": "y"})
    
    try:
        # Fit the model with tuned parameters
        m = Prophet(
            yearly_seasonality=True, 
            weekly_seasonality=False, 
            daily_seasonality=False,
            changepoint_prior_scale=changepoint_prior_scale,  # ๊ณผ์ ํ•ฉ ๋ฐฉ์ง€
            seasonality_prior_scale=10.0,  # ๊ณ„์ ˆ์„ฑ ์กฐ์ •
            seasonality_mode='multiplicative'  # ๊ณฑ์…ˆ ๋ชจ๋“œ (๊ฐ€๊ฒฉ ๋ฐ์ดํ„ฐ์— ์ ํ•ฉ)
        )
        
        # ํ•œ๊ตญ ๋ช…์ ˆ ํšจ๊ณผ ์ถ”๊ฐ€ (์„ค๋‚ , ์ถ”์„)
        m.add_country_holidays(country_name='South Korea')
        
        m.fit(prophet_df)
        
        # Generate future dates
        if monthly:
            # ์›” ๋‹จ์œ„ ์˜ˆ์ธก
            future_periods = (pd.Timestamp(horizon_end).year - df["date"].max().year) * 12 + \
                             (pd.Timestamp(horizon_end).month - df["date"].max().month) + 1
            future = m.make_future_dataframe(periods=future_periods, freq='MS')  # ์›” ์‹œ์ž‘์ผ
            future = future.resample('MS', on='ds').first().reset_index()  # ์ค‘๋ณต ์ œ๊ฑฐ
        else:
            # ์ผ ๋‹จ์œ„ ์˜ˆ์ธก
            periods = max((pd.Timestamp(horizon_end) - df["date"].max()).days, 1)
            future = m.make_future_dataframe(periods=periods, freq="D")
        
        # Make predictions
        forecast = m.predict(future)
        
        # ์˜ˆ์ธก๊ฐ’ ๋ฒ”์œ„ ์กฐ์ • (์Œ์ˆ˜ ์˜ˆ์ธก ๋ฐฉ์ง€ ๋ฐ ์ƒํ•œ๊ฐ’ ์„ค์ •)
        forecast['yhat'] = np.maximum(forecast['yhat'], 0)  # ์Œ์ˆ˜ ์ œ๊ฑฐ
        max_historical = prophet_df['y'].max() * 5  # ์ตœ๋Œ€ ์—ญ์‚ฌ์  ๊ฐ€๊ฒฉ์˜ 5๋ฐฐ๋กœ ์ œํ•œ
        forecast['yhat'] = np.minimum(forecast['yhat'], max_historical)  # ์ƒํ•œ๊ฐ’ ์„ค์ •
        
        return m, forecast
    except Exception as e:
        st.error(f"Prophet ๋ชจ๋ธ ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜: {str(e)}")
        return None, None


def format_currency(value):
    """์›ํ™” ํ˜•์‹์œผ๋กœ ์ˆซ์ž ํฌ๋งทํŒ…"""
    return f"{value:,.0f}์›"


# -------------------------------------------------
# LOAD DATA ---------------------------------------
# -------------------------------------------------
raw_df = load_data()

if len(raw_df) == 0:
    st.error("๋ฐ์ดํ„ฐ๊ฐ€ ๋น„์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ํŒŒ์ผ์„ ํ™•์ธํ•ด์ฃผ์„ธ์š”.")
    st.stop()

st.sidebar.header("๐Ÿ” ํ’ˆ๋ชฉ ์„ ํƒ")
selected_item = st.sidebar.selectbox("ํ’ˆ๋ชฉ", get_items(raw_df))
current_date = date.today()
st.sidebar.caption(f"์˜ค๋Š˜: {current_date}")

item_df = raw_df.query("item == @selected_item").copy()
if item_df.empty:
    st.error("์„ ํƒํ•œ ํ’ˆ๋ชฉ ๋ฐ์ดํ„ฐ ์—†์Œ")
    st.stop()

# -------------------------------------------------
# MACRO FORECAST 1996โ€‘2030 ------------------------
# -------------------------------------------------
st.header(f"๐Ÿ“ˆ {selected_item} ๊ฐ€๊ฒฉ ์˜ˆ์ธก ๋Œ€์‹œ๋ณด๋“œ")

# ๋ฐ์ดํ„ฐ ํ•„ํ„ฐ๋ง ๋กœ์ง
try:
    macro_start_dt = pd.Timestamp("1996-01-01")
    # ๋ฐ์ดํ„ฐ์˜ ์‹œ์ž‘์ผ์ด 1996๋…„ ์ดํ›„์ธ์ง€ ํ™•์ธ
    if item_df["date"].min() > macro_start_dt:
        macro_start_dt = item_df["date"].min()
    
    macro_df = item_df[item_df["date"] >= macro_start_dt].copy()
except Exception as e:
    st.error(f"๋‚ ์งœ ํ•„ํ„ฐ๋ง ์˜ค๋ฅ˜: {str(e)}")
    macro_df = item_df.copy()  # ํ•„ํ„ฐ๋ง ์—†์ด ์ „์ฒด ๋ฐ์ดํ„ฐ ์‚ฌ์šฉ

# Add diagnostic info
with st.expander("๋ฐ์ดํ„ฐ ์ง„๋‹จ"):
    st.write(f"- ์ „์ฒด ๋ฐ์ดํ„ฐ ์ˆ˜: {len(item_df)}")
    st.write(f"- ๋ถ„์„ ๋ฐ์ดํ„ฐ ์ˆ˜: {len(macro_df)}")
    if len(macro_df) > 0:
        st.write(f"- ๊ธฐ๊ฐ„: {macro_df['date'].min().strftime('%Y-%m-%d')} ~ {macro_df['date'].max().strftime('%Y-%m-%d')}")
        st.dataframe(macro_df.head())
    else:
        st.write("๋ฐ์ดํ„ฐ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.")

if len(macro_df) < 2:
    st.warning(f"{selected_item}์— ๋Œ€ํ•œ ๋ฐ์ดํ„ฐ๊ฐ€ ์ถฉ๋ถ„ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ์ „์ฒด ๊ธฐ๊ฐ„ ๋ฐ์ดํ„ฐ๋ฅผ ํ‘œ์‹œํ•ฉ๋‹ˆ๋‹ค.")
    fig = px.line(item_df, x="date", y="price", title=f"{selected_item} ๊ณผ๊ฑฐ ๊ฐ€๊ฒฉ")
    st.plotly_chart(fig, use_container_width=True)
else:
    try:
        with st.spinner("์žฅ๊ธฐ ์˜ˆ์ธก ๋ชจ๋ธ ์ƒ์„ฑ ์ค‘..."):
            # ์›” ๋‹จ์œ„ ์˜ˆ์ธก์œผ๋กœ ๋ณ€๊ฒฝ
            m_macro, fc_macro = fit_prophet(macro_df, MACRO_END, monthly=True, changepoint_prior_scale=0.01)
        
        if m_macro is not None and fc_macro is not None:
            # ์‹ค์ œ ๋ฐ์ดํ„ฐ์™€ ์˜ˆ์ธก ๋ฐ์ดํ„ฐ ๊ตฌ๋ถ„
            cutoff_date = pd.Timestamp("2025-01-01")
            
            # ํ”Œ๋กฏ ์ƒ์„ฑ
            fig = go.Figure()
            
            # ์‹ค์ œ ๋ฐ์ดํ„ฐ ์ถ”๊ฐ€ (1996-2024)
            historical_data = macro_df[macro_df["date"] < cutoff_date].copy()
            if not historical_data.empty:
                fig.add_trace(go.Scatter(
                    x=historical_data["date"], 
                    y=historical_data["price"],
                    mode="lines",
                    name="์‹ค์ œ ๊ฐ€๊ฒฉ (1996-2024)",
                    line=dict(color="blue", width=2)
                ))
            
            # ์˜ˆ์ธก ๋ฐ์ดํ„ฐ ์ถ”๊ฐ€ (2025-2030)
            forecast_data = fc_macro[fc_macro["ds"] >= cutoff_date].copy()
            if not forecast_data.empty:
                fig.add_trace(go.Scatter(
                    x=forecast_data["ds"], 
                    y=forecast_data["yhat"],
                    mode="lines",
                    name="์˜ˆ์ธก ๊ฐ€๊ฒฉ (2025-2030)",
                    line=dict(color="red", width=2, dash="dash")
                ))
                
                # ์‹ ๋ขฐ ๊ตฌ๊ฐ„ ์ถ”๊ฐ€
                fig.add_trace(go.Scatter(
                    x=forecast_data["ds"],
                    y=forecast_data["yhat_upper"],
                    mode="lines",
                    line=dict(width=0),
                    showlegend=False
                ))
                fig.add_trace(go.Scatter(
                    x=forecast_data["ds"],
                    y=forecast_data["yhat_lower"],
                    mode="lines",
                    line=dict(width=0),
                    fill="tonexty",
                    fillcolor="rgba(255, 0, 0, 0.1)",
                    name="95% ์‹ ๋ขฐ ๊ตฌ๊ฐ„"
                ))
            
            # ๋ ˆ์ด์•„์›ƒ ์„ค์ •
            fig.update_layout(
                title=f"{selected_item} ์žฅ๊ธฐ ๊ฐ€๊ฒฉ ์˜ˆ์ธก (1996-2030)",
                xaxis_title="์—ฐ๋„",
                yaxis_title="๊ฐ€๊ฒฉ (์›)",
                legend=dict(
                    orientation="h",
                    yanchor="bottom",
                    y=1.02,
                    xanchor="right",
                    x=1
                )
            )
            
            # ์ฐจํŠธ ํ‘œ์‹œ
            st.plotly_chart(fig, use_container_width=True)
            
            # 2030๋…„ ์˜ˆ์ธก๊ฐ€ ํ‘œ์‹œ
            try:
                latest_price = macro_df.iloc[-1]["price"]
                # 2030๋…„ ๋งˆ์ง€๋ง‰ ์›” ์ฐพ๊ธฐ
                target_date = pd.Timestamp("2030-12-31")
                close_dates = fc_macro.loc[(fc_macro["ds"] - target_date).abs().argsort()[:1], "ds"].values[0]
                macro_pred = fc_macro.loc[fc_macro["ds"] == close_dates, "yhat"].iloc[0]
                macro_pct = (macro_pred - latest_price) / latest_price * 100
                
                col1, col2 = st.columns(2)
                with col1:
                    st.metric("ํ˜„์žฌ ๊ฐ€๊ฒฉ", format_currency(latest_price))
                with col2:
                    st.metric("2030๋…„ ์˜ˆ์ธก๊ฐ€", format_currency(macro_pred), f"{macro_pct:+.1f}%")
            except Exception as e:
                st.error(f"์˜ˆ์ธก๊ฐ€ ๊ณ„์‚ฐ ์˜ค๋ฅ˜: {str(e)}")
        else:
            st.warning("์˜ˆ์ธก ๋ชจ๋ธ์„ ์ƒ์„ฑํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")
            fig = px.line(item_df, x="date", y="price", title=f"{selected_item} ๊ณผ๊ฑฐ ๊ฐ€๊ฒฉ")
            st.plotly_chart(fig, use_container_width=True)
    except Exception as e:
        st.error(f"์žฅ๊ธฐ ์˜ˆ์ธก ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}")
        fig = px.line(item_df, x="date", y="price", title=f"{selected_item} ๊ณผ๊ฑฐ ๊ฐ€๊ฒฉ")
        st.plotly_chart(fig, use_container_width=True)

# -------------------------------------------------
# MICRO FORECAST 2024โ€‘2026 ------------------------
# -------------------------------------------------
st.subheader("๐Ÿ”Ž 2024โ€“2026 ๋‹จ๊ธฐ ์˜ˆ์ธก (์›”๋ณ„)")

# ๋ฐ์ดํ„ฐ ํ•„ํ„ฐ๋ง - ์ตœ๊ทผ 3๋…„ ๋ฐ์ดํ„ฐ ํ™œ์šฉ
try:
    three_years_ago = pd.Timestamp("2021-01-01")
    if item_df["date"].min() > three_years_ago:
        three_years_ago = item_df["date"].min()
    
    micro_df = item_df[item_df["date"] >= three_years_ago].copy()
except Exception as e:
    st.error(f"๋‹จ๊ธฐ ์˜ˆ์ธก ๋ฐ์ดํ„ฐ ํ•„ํ„ฐ๋ง ์˜ค๋ฅ˜: {str(e)}")
    # ์ตœ๊ทผ ๋ฐ์ดํ„ฐ ์‚ฌ์šฉ
    micro_df = item_df.sort_values("date").tail(24).copy()

if len(micro_df) < 2:
    st.warning(f"์ตœ๊ทผ ๋ฐ์ดํ„ฐ๊ฐ€ ์ถฉ๋ถ„ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.")
    fig = px.line(item_df, x="date", y="price", title=f"{selected_item} ์ตœ๊ทผ ๊ฐ€๊ฒฉ")
    st.plotly_chart(fig, use_container_width=True)
else:
    try:
        with st.spinner("๋‹จ๊ธฐ ์˜ˆ์ธก ๋ชจ๋ธ ์ƒ์„ฑ ์ค‘..."):
            # ์›” ๋‹จ์œ„ ์˜ˆ์ธก์œผ๋กœ ๋ณ€๊ฒฝ
            m_micro, fc_micro = fit_prophet(micro_df, MICRO_END, monthly=True, changepoint_prior_scale=0.05)
            
        if m_micro is not None and fc_micro is not None:
            # 2024-01-01๋ถ€ํ„ฐ 2026-12-31๊นŒ์ง€ ํ•„ํ„ฐ๋ง
            start_date = pd.Timestamp("2024-01-01")
            end_date = pd.Timestamp("2026-12-31")
            
            # ์›”๋ณ„ ๋ฐ์ดํ„ฐ ์ค€๋น„
            monthly_historical = micro_df.copy()
            monthly_historical["year_month"] = monthly_historical["date"].dt.strftime("%Y-%m")
            monthly_historical = monthly_historical.groupby("year_month").agg({
                "date": "first", 
                "price": "mean"
            }).reset_index(drop=True)
            
            monthly_historical = monthly_historical[
                (monthly_historical["date"] >= start_date) & 
                (monthly_historical["date"] <= end_date)
            ]
            
            monthly_forecast = fc_micro[
                (fc_micro["ds"] >= start_date) & 
                (fc_micro["ds"] <= end_date)
            ].copy()
            
            # ์›”๋ณ„ ์ฐจํŠธ ์ƒ์„ฑ
            fig = go.Figure()
            
            # 2024๋…„ ์‹ค์ œ ๋ฐ์ดํ„ฐ
            actual_2024 = monthly_historical[
                (monthly_historical["date"] >= pd.Timestamp("2024-01-01")) & 
                (monthly_historical["date"] <= pd.Timestamp("2024-12-31"))
            ]
            
            if not actual_2024.empty:
                fig.add_trace(go.Scatter(
                    x=actual_2024["date"],
                    y=actual_2024["price"],
                    mode="lines+markers",
                    name="2024 ์‹ค์ œ ๊ฐ€๊ฒฉ",
                    line=dict(color="blue", width=2),
                    marker=dict(size=8)
                ))
            
            # 2024๋…„ ์ดํ›„ ์˜ˆ์ธก ๋ฐ์ดํ„ฐ
            cutoff = pd.Timestamp("2024-12-31")
            future_data = monthly_forecast[monthly_forecast["ds"] > cutoff]
            
            if not future_data.empty:
                fig.add_trace(go.Scatter(
                    x=future_data["ds"],
                    y=future_data["yhat"],
                    mode="lines+markers",
                    name="2025-2026 ์˜ˆ์ธก ๊ฐ€๊ฒฉ",
                    line=dict(color="red", width=2, dash="dash"),
                    marker=dict(size=8)
                ))
                
                # ์‹ ๋ขฐ ๊ตฌ๊ฐ„ ์ถ”๊ฐ€
                fig.add_trace(go.Scatter(
                    x=future_data["ds"],
                    y=future_data["yhat_upper"],
                    mode="lines",
                    line=dict(width=0),
                    showlegend=False
                ))
                fig.add_trace(go.Scatter(
                    x=future_data["ds"],
                    y=future_data["yhat_lower"],
                    mode="lines",
                    line=dict(width=0),
                    fill="tonexty",
                    fillcolor="rgba(255, 0, 0, 0.1)",
                    name="95% ์‹ ๋ขฐ ๊ตฌ๊ฐ„"
                ))
            
            # ๋ ˆ์ด์•„์›ƒ ์„ค์ •
            fig.update_layout(
                title=f"{selected_item} ์›”๋ณ„ ๋‹จ๊ธฐ ์˜ˆ์ธก (2024-2026)",
                xaxis_title="์›”",
                yaxis_title="๊ฐ€๊ฒฉ (์›)",
                xaxis=dict(
                    tickformat="%Y-%m",
                    dtick="M3",  # 3๊ฐœ์›” ๊ฐ„๊ฒฉ
                    tickangle=45
                ),
                legend=dict(
                    orientation="h",
                    yanchor="bottom",
                    y=1.02,
                    xanchor="right",
                    x=1
                )
            )
            
            # ์ฐจํŠธ ํ‘œ์‹œ
            st.plotly_chart(fig, use_container_width=True)
            
            # ์›”๋ณ„ ์˜ˆ์ธก ๊ฐ€๊ฒฉ ํ‘œ์‹œ (2025-2026)
            with st.expander("์›”๋ณ„ ์˜ˆ์ธก ๊ฐ€๊ฒฉ ์ƒ์„ธ๋ณด๊ธฐ"):
                monthly_detail = monthly_forecast[monthly_forecast["ds"] > cutoff].copy()
                monthly_detail["๋‚ ์งœ"] = monthly_detail["ds"].dt.strftime("%Y๋…„ %m์›”")
                monthly_detail["์˜ˆ์ธก๊ฐ€๊ฒฉ"] = monthly_detail["yhat"].apply(format_currency)
                monthly_detail["ํ•˜ํ•œ๊ฐ’"] = monthly_detail["yhat_lower"].apply(format_currency)
                monthly_detail["์ƒํ•œ๊ฐ’"] = monthly_detail["yhat_upper"].apply(format_currency)
                
                st.dataframe(
                    monthly_detail[["๋‚ ์งœ", "์˜ˆ์ธก๊ฐ€๊ฒฉ", "ํ•˜ํ•œ๊ฐ’", "์ƒํ•œ๊ฐ’"]], 
                    hide_index=True
                )
            
            # 2026๋…„ ์˜ˆ์ธก๊ฐ€ ํ‘œ์‹œ
            try:
                latest_price = monthly_historical.iloc[-1]["price"] if not monthly_historical.empty else micro_df.iloc[-1]["price"]
                
                # 2026๋…„ ๋งˆ์ง€๋ง‰ ์›” ์ฐพ๊ธฐ
                target_date = pd.Timestamp("2026-12-31")
                close_dates = monthly_forecast.loc[(monthly_forecast["ds"] - target_date).abs().argsort()[:1], "ds"].values[0]
                micro_pred = monthly_forecast.loc[monthly_forecast["ds"] == close_dates, "yhat"].iloc[0]
                micro_pct = (micro_pred - latest_price) / latest_price * 100
                
                col1, col2 = st.columns(2)
                with col1:
                    st.metric("ํ˜„์žฌ ๊ฐ€๊ฒฉ", format_currency(latest_price))
                with col2:
                    st.metric("2026๋…„ 12์›” ์˜ˆ์ธก๊ฐ€", format_currency(micro_pred), f"{micro_pct:+.1f}%")
            except Exception as e:
                st.error(f"์˜ˆ์ธก๊ฐ€ ๊ณ„์‚ฐ ์˜ค๋ฅ˜: {str(e)}")
        else:
            st.warning("๋‹จ๊ธฐ ์˜ˆ์ธก ๋ชจ๋ธ์„ ์ƒ์„ฑํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")
    except Exception as e:
        st.error(f"๋‹จ๊ธฐ ์˜ˆ์ธก ์˜ค๋ฅ˜: {str(e)}")

# -------------------------------------------------
# SEASONALITY & PATTERN ---------------------------
# -------------------------------------------------
with st.expander("๐Ÿ“† ์‹œ์ฆˆ๋„๋ฆฌํ‹ฐ & ํŒจํ„ด ์„ค๋ช…"):
    if 'm_micro' in locals() and m_micro is not None and 'fc_micro' in locals() and fc_micro is not None:
        try:
            comp_fig = m_micro.plot_components(fc_micro)
            st.pyplot(comp_fig)

            month_season = (fc_micro[["ds", "yearly"]]
                            .assign(month=lambda d: d.ds.dt.month)
                            .groupby("month")["yearly"].mean())
            st.markdown(
                f"**์—ฐ๊ฐ„ ํ”ผํฌ ์›”:** {int(month_season.idxmax())}์›”  \n"
                f"**์—ฐ๊ฐ„ ์ €์  ์›”:** {int(month_season.idxmin())}์›”  \n"
                f"**์—ฐ๊ฐ„ ๋ณ€๋™ํญ:** {month_season.max() - month_season.min():.1f}")
            
            # ์›”๋ณ„ ๊ณ„์ ˆ์„ฑ ์ฐจํŠธ
            month_names = ["1์›”", "2์›”", "3์›”", "4์›”", "5์›”", "6์›”", "7์›”", "8์›”", "9์›”", "10์›”", "11์›”", "12์›”"]
            month_values = month_season.values
            
            fig = px.bar(
                x=month_names, 
                y=month_values,
                title=f"{selected_item} ์›”๋ณ„ ๊ฐ€๊ฒฉ ๋ณ€๋™ ํŒจํ„ด",
                labels={"x": "์›”", "y": "์ƒ๋Œ€์  ๊ฐ€๊ฒฉ ๋ณ€๋™"}
            )
            
            st.plotly_chart(fig, use_container_width=True)
        except Exception as e:
            st.error(f"์‹œ์ฆˆ๋„๋ฆฌํ‹ฐ ๋ถ„์„ ์˜ค๋ฅ˜: {str(e)}")
    else:
        st.info("ํŒจํ„ด ๋ถ„์„์„ ์œ„ํ•œ ์ถฉ๋ถ„ํ•œ ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.")

# -------------------------------------------------
# FOOTER ------------------------------------------
# -------------------------------------------------
st.markdown("---")
st.caption("ยฉ 2025 ํ’ˆ๋ชฉ๋ณ„ ๊ฐ€๊ฒฉ ์˜ˆ์ธก ์‹œ์Šคํ…œ | ๋ฐ์ดํ„ฐ ๋ถ„์„ ์ž๋™ํ™”")