File size: 5,572 Bytes
dce4fa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import pandas as pd
import joblib

# --- SAYFA AYARLARI ---
st.set_page_config(page_title="Corporate Bankruptcy AI Analysis", layout="wide")

# --- MODEL YÜKLEME ---
@st.cache_resource
def load_model():
    data_yuklenen = joblib.load('bankruptcy_model.pkl')
    return data_yuklenen["model"], data_yuklenen["columns"]

model, columns = load_model()
feature_columns = [c for c in columns if c != 'Bankrupt?']

# --- TÜRKÇE KARŞILIKLAR ---
translation_map = {
    "Net Income to Stockholder's Equity": "Özsermaye Karlılığı",
    "Net Income to Total Assets": "Varlık Karlılığı",
    "Borrowing dependency": "Borç Bağımlılığı",
    "ROA(A) before interest and % after tax": "Varlık Getirisi (A) Vergi Sonrası",
    "ROA(B) before interest and depreciation after tax": "Varlık Getirisi (B) Amortisman Sonrası",
    "ROA(C) before interest and depreciation before interest": "Varlık Getirisi (C) Faiz Öncesi",
    "Liability to Equity": "Borç / Özsermaye Oranı",
    "Total debt/Total net worth": "Toplam Borç / Net Değer",
    "Persistent EPS in the Last Four Seasons": "Süreklilik Arz Eden EPS",
    "Net profit before tax/Paid-in capital": "Net Kâr / Ödenmiş Sermaye",
    "Per Share Net profit before tax (Yuan ¥)": "Hisse Başı Net Kâr",
    "Debt ratio %": "Borçlanma Oranı %",
    "Net worth/Assets": "Net Değer / Varlıklar",
    "Retained Earnings to Total Assets": "Dağıtılmamış Kârlar / Varlıklar",
    "Current Liability to Equity": "Kısa Vadeli Borç / Özsermaye",
    "Current Liabilities/Equity": "Cari Borçlar / Özsermaye",
    "Operating Profit Per Share (Yuan ¥)": "Hisse Başı Faaliyet Kârı",
    "Operating profit/Paid-in capital": "Faaliyet Kârı / Sermaye",
    "Working Capital to Total Assets": "İşletme Sermayesi / Varlıklar",
    "Working Capital/Equity": "İşletme Sermayesi / Özsermaye"
}

# --- SENARYO VERİLERİ (Dinamik Test Verileri) ---
safe_vals = [0.88, 0.85, 0.12, 0.82, 0.83, 0.84, 0.08, 0.09, 0.85, 0.82, 0.80, 0.15, 0.88, 0.87, 0.07, 0.06, 0.82, 0.81, 0.88, 0.89]
risky_vals = [0.05, 0.08, 0.92, 0.10, 0.11, 0.09, 0.95, 0.94, 0.02, 0.07, 0.08, 0.90, 0.12, 0.15, 0.96, 0.93, 0.05, 0.04, 0.09, 0.11]

# --- SIDEBAR ---
st.sidebar.title("🏨 Prediction Menu / Tahmin Menüsü")
if st.sidebar.button("✅ Load Safe Data / Güvenli Veri Yükle"):
    for i, col in enumerate(feature_columns): st.session_state[f"field_{col}"] = safe_vals[i]

if st.sidebar.button("⚠️ Load Risky Data / Riskli Veri Yükle"):
    for i, col in enumerate(feature_columns): st.session_state[f"field_{col}"] = risky_vals[i]

if st.sidebar.button("🔄 Reset / Verileri Sıfırla"):
    for col in feature_columns: st.session_state[f"field_{col}"] = 0.0

st.sidebar.divider()
with st.sidebar.expander("📚 Glossary / Oran Sözlüğü"):
    for eng, tr in translation_map.items(): st.write(f"**{eng}:** {tr}")

# --- ANA PANEL ---
st.title("Corporate Bankruptcy Prediction System / Kurumsal İflas Tahmin Sistemi")
st.write("---")

# Veri Giriş Alanı (Kapalı Başlar)
with st.expander("📊 Financial Input Fields (20 Features) / Veri Giriş Alanları", expanded=False):
    col1, col2, col3 = st.columns(3)
    inputs = {}
    for i, col_name in enumerate(feature_columns):
        if f"field_{col_name}" not in st.session_state: st.session_state[f"field_{col_name}"] = 0.0
        label = f"{col_name} ({translation_map.get(col_name, '')})"
        target_col = [col1, col2, col3][i % 3]
        with target_col:
            inputs[col_name] = st.number_input(label, format="%.4f", key=f"field_{col_name}")

# Mevcut Veri Tablosu
df_input = pd.DataFrame(inputs, index=["Value / Değer"])
st.subheader("📋 Current Data View / Mevcut Veri Tablosu")
st.dataframe(df_input, use_container_width=True)

# --- ANALİZ VE GRAFİK BÖLÜMÜ ---
if st.button("🚀 RUN STRATEGIC ANALYSIS / ANALİZİ BAŞLAT"):
    prediction = model.predict(df_input)
    prediction_proba = model.predict_proba(df_input)
    
    st.divider()
    res_col1, res_col2 = st.columns([1, 1])
    
    with res_col1:
        if prediction[0] == 1:
            st.error(f"### ⚠️ RESULT: BANKRUPTCY RISK / İFLAS RİSKİ")
            st.warning(f"Probability Score: %{prediction_proba[0][1]*100:.2f}")
        else:
            st.success(f"### ✅ RESULT: FINANCIALLY HEALTHY / SAĞLIKLI")
            st.info(f"Health Score: %{prediction_proba[0][0]*100:.2f}")
            
    with res_col2:
        # GRAFİK EKLEME: Olasılık Dağılım Grafiği
        st.subheader("📊 Probability Analysis / Olasılık Analizi")
        prob_data = pd.DataFrame({
            'Status': ['Healthy / Sağlıklı', 'Bankrupt / İflas'],
            'Percentage (%)': [prediction_proba[0][0]*100, prediction_proba[0][1]*100]
        })
        st.bar_chart(data=prob_data, x='Status', y='Percentage (%)', color="#ff4b4b" if prediction[0] == 1 else "#00cc66")

    # Alt Kısma Yönetici Özeti
    st.write("---")
    st.subheader("📝 Summary Report / Yönetici Özeti")
    if prediction[0] == 1:
        st.write("The AI model has detected a high correlation between your input variables and known historical bankruptcy patterns. Immediate review of liquidity and debt ratios is advised.")
    else:
        st.write("The company shows strong financial stability. Most ratios are within safe historical boundaries.")

st.caption("Strategic AI Model | Accuracy: %88.7 | Bilingual Support")