File size: 9,166 Bytes
1acd6e1
 
 
 
 
 
 
 
dc2be38
1acd6e1
dc2be38
 
 
 
4a31bd8
4fb476c
 
 
 
 
dc2be38
 
 
828f0f0
 
 
3268778
4a31bd8
3268778
4a31bd8
3268778
 
 
828f0f0
3268778
 
 
828f0f0
4a31bd8
828f0f0
 
 
 
 
 
4a31bd8
 
 
 
 
828f0f0
 
 
 
4a31bd8
 
828f0f0
 
 
 
4a31bd8
828f0f0
 
 
4a31bd8
828f0f0
 
 
3268778
 
 
4a31bd8
1acd6e1
dc2be38
4a31bd8
dc2be38
 
 
 
 
3268778
 
 
 
4a31bd8
3268778
 
 
dc2be38
3268778
 
828f0f0
1acd6e1
 
 
4a31bd8
1acd6e1
 
 
 
4a31bd8
4fb476c
1acd6e1
 
 
3268778
 
1acd6e1
 
 
dc2be38
 
 
 
 
 
 
1acd6e1
dc2be38
1acd6e1
dc2be38
1acd6e1
dc2be38
1acd6e1
 
dc2be38
4a31bd8
dc2be38
 
 
3268778
4fb476c
 
1acd6e1
 
 
4fb476c
dc2be38
 
 
1acd6e1
3268778
4a31bd8
3268778
dc2be38
3268778
4fb476c
 
 
1acd6e1
 
 
dc2be38
 
 
1acd6e1
3268778
 
 
dc2be38
1acd6e1
 
3268778
4a31bd8
 
 
dc2be38
3268778
 
4a31bd8
dc2be38
762f595
 
 
3268778
 
 
dc2be38
4a31bd8
 
 
dc2be38
 
 
3268778
762f595
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import pandas as pd
import numpy as np
from prophet import Prophet
import plotly.express as px
import seaborn as sns
import matplotlib.pyplot as plt
from datetime import date
from pathlib import Path

# -------------------------------------------------
# CONFIG ------------------------------------------
# -------------------------------------------------
CSV_PATH = Path("price_data.csv")
PARQUET_PATH = Path("domae-202503.parquet")  # 1996โ€‘2025โ€‘03 ์ผ๊ฐ„/์›”๊ฐ„ ๊ฐ€๊ฒฉ
MACRO_START, MACRO_END = "1996-01-01", "2030-12-31"
MICRO_START, MICRO_END = "2020-01-01", "2026-12-31"

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" ]):
        sample = str(df["date"].iloc[0])
        if sample.isdigit() and len(sample) in (6, 8):
            df["date"] = pd.to_datetime(df["date"].astype(str).str[:6], format="%Y%m", 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 Parquet if available, else CSV. Handle flexible schema."""
    if PARQUET_PATH.exists():
        df = pd.read_parquet(PARQUET_PATH)
    elif CSV_PATH.exists():
        df = pd.read_csv(CSV_PATH)
    else:
        st.error("๐Ÿ’พ price_data.csv ๋˜๋Š” domae-202503.parquet ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")
        st.stop()

    df = _standardize_columns(df)

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

    df["date"] = pd.to_datetime(df["date"], errors="coerce")
    df = df.dropna(subset=["date", "item", "price"])
    df.sort_values("date", inplace=True)
    return df


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


@st.cache_data(show_spinner=False)
def fit_prophet(df: pd.DataFrame, horizon_end: str):
    m = Prophet(yearly_seasonality=True, weekly_seasonality=False, daily_seasonality=False)
    m.fit(df.rename(columns={"date": "ds", "price": "y"}))
    periods = (pd.Timestamp(horizon_end) - df["date"].max()).days
    future = m.make_future_dataframe(periods=periods, freq="D")
    forecast = m.predict(future)
    return m, forecast

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

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} ๊ฐ€๊ฒฉ ์˜ˆ์ธก ๋Œ€์‹œ๋ณด๋“œ")
macro_df = item_df[item_df["date"] >= MACRO_START]

m_macro, fc_macro = fit_prophet(macro_df, MACRO_END)
fig_macro = px.line(fc_macro, x="ds", y="yhat", title="Macro Forecast 1996โ€“2030")
fig_macro.add_scatter(x=macro_df["date"], y=macro_df["price"], mode="lines", name="Actual")
st.plotly_chart(fig_macro, use_container_width=True)

latest_price = macro_df.iloc[-1]["price"]
macro_pred = fc_macro.loc[fc_macro["ds"] == MACRO_END, "yhat"].iloc[0]
macro_pct = (macro_pred - latest_price) / latest_price * 100
st.metric("2030 ์˜ˆ์ธก๊ฐ€", f"{macro_pred:,.0f}", f"{macro_pct:+.1f}%")

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

micro_df = item_df[item_df["date"] >= MICRO_START]
m_micro, fc_micro = fit_prophet(micro_df, MICRO_END)
fig_micro = px.line(fc_micro, x="ds", y="yhat", title="Micro Forecast 2024โ€“2026")
fig_micro.add_scatter(x=micro_df["date"], y=micro_df["price"], mode="lines", name="Actual")
st.plotly_chart(fig_micro, use_container_width=True)

micro_pred = fc_micro.loc[fc_micro["ds"] == MICRO_END, "yhat"].iloc[0]
micro_pct = (micro_pred - latest_price) / latest_price * 100
st.metric("2026 ์˜ˆ์ธก๊ฐ€", f"{micro_pred:,.0f}", f"{micro_pct:+.1f}%")

# -------------------------------------------------
# SEASONALITY & PATTERN ---------------------------
# -------------------------------------------------
with st.expander("๐Ÿ“† ์‹œ์ฆˆ๋„๋ฆฌํ‹ฐ & ํŒจํ„ด ์„ค๋ช…"):
    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}")

# -------------------------------------------------
# CORRELATION HEATMAP -----------------------------
# -------------------------------------------------
# -------------------------------------------------
# CORRELATION HEATMAP -----------------------------
# -------------------------------------------------
st.subheader("๐Ÿงฎ ํ’ˆ๋ชฉ ๊ฐ„ ์ƒ๊ด€๊ด€๊ณ„")
monthly_pivot = (raw_df.assign(month=lambda d: d.date.dt.to_period("M"))
                        .groupby(["month", "item"], as_index=False)["price"].mean()
                        .pivot(index="month", columns="item", values="price"))

corr = monthly_pivot.corr()
fig, ax = plt.subplots(figsize=(12, 10))
mask = np.triu(np.ones_like(corr, dtype=bool))
sns.heatmap(corr, mask=mask, annot=False, cmap="coolwarm", center=0, 
            square=True, linewidths=.5, cbar_kws={"shrink": .5})

# Highlight correlations with selected item
if selected_item in corr.columns:
    item_corr = corr[selected_item].sort_values(ascending=False)
    top_corr = item_corr.drop(selected_item).head(5)
    bottom_corr = item_corr.drop(selected_item).tail(5)
    
    col1, col2 = st.columns(2)
    with col1:
        st.markdown(f"**{selected_item}์™€ ์ƒ๊ด€๊ด€๊ณ„ ๋†’์€ ํ’ˆ๋ชฉ**")
        for item, val in top_corr.items():
            st.write(f"{item}: {val:.2f}")
    with col2:
        st.markdown(f"**{selected_item}์™€ ์ƒ๊ด€๊ด€๊ณ„ ๋‚ฎ์€ ํ’ˆ๋ชฉ**")
        for item, val in bottom_corr.items():
            st.write(f"{item}: {val:.2f}")

st.pyplot(fig)

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