Gold_Price_Analysis / src /streamlit_app.py
ESMATUGBA's picture
Update src/streamlit_app.py
360f218 verified
Raw
History Blame Contribute Delete
4.91 kB
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import os
# 1. SAYFA AYARLARI
st.set_page_config(layout="wide", page_title="Gold Price Analysis")
# CSS: Tasarım Ayarları
st.markdown("""
<style>
.stApp { background-color: #FFFFFF; }
[data-testid="stMetricValue"] { font-size: 45px !important; font-weight: bold !important; color: #B28F2D !important; }
[data-testid="stMetricLabel"] { font-size: 18px !important; font-weight: bold !important; color: #333333 !important; }
</style>
""", unsafe_allow_html=True)
# 2. VERİ YÜKLEME
def load_data():
csv_files = [f for f in os.listdir('.') if f.endswith('.csv')]
if csv_files:
df = pd.read_csv(csv_files[0])
date_col = next((col for col in df.columns if 'date' in col.lower()), df.columns[0])
df[date_col] = pd.to_datetime(df[date_col])
df['YEAR'] = df[date_col].dt.year
df = df.rename(columns={date_col: 'Date'})
return df
return None
df = load_data()
if df is None:
st.error("Veri dosyası bulunamadı!")
st.stop()
# 3. SIDEBAR (Yıl Seçimi)
st.sidebar.header("📅 Filtreler / Filters")
years_list = sorted(df['YEAR'].unique(), reverse=True)
year = st.sidebar.selectbox("Yıl Seçin / Select Year", options=years_list, key="year_selector")
# FİLTRELEME (Her yıl seçildiğinde veriyi tamamen yeniler)
filtered_df = df[df['YEAR'] == year].copy().reset_index(drop=True)
# 4. ANA BAŞLIK (İstediğin Gibi Dinamik Yıl Eklendi)
st.markdown(f"<h1 style='text-align: center; color: #333;'>Gold Price Analysis / Altın Fiyat Analizi ({year})</h1>", unsafe_allow_html=True)
st.divider()
# 5. YÖNETİCİ BİLGİ NOTU
st.markdown("### 💼 Yönetici Bilgi Notu / Executive Summary")
col_tr, col_en = st.columns(2)
with col_tr:
if year == 2008:
st.warning("### 🇹🇷 2008'de altın güvenli limandır, alım faydalıdır.")
else:
st.success(f"### 🇹🇷 {year} yılı verileri istikrarlı görünüyor, teknik seviyeler izlenmeli.")
with col_en:
if year == 2008:
st.warning("### 🇺🇸 Gold is a safe haven in 2008; buying is beneficial.")
else:
st.success(f"### 🇺🇸 Data for {year} appears stable, monitor technical levels.")
st.divider()
# 6. ÖZEL METRİKLER (Dinamik)
m1, m2, m3 = st.columns(3)
m1.metric("Son Kapanış", f"{filtered_df['GLD'].iloc[-1]:.2f}")
m2.metric(f"{year} Zirve", f"{filtered_df['GLD'].max():.2f}")
m3.metric(f"{year} Dip", f"{filtered_df['GLD'].min():.2f}")
# 7. ANA TREND GRAFİĞİ (Dinamik)
st.markdown(f"#### 📈 {year} Altın Fiyat Trendi")
fig1 = go.Figure()
fig1.add_trace(go.Scatter(x=filtered_df['Date'], y=filtered_df['GLD'],
mode='lines',
line=dict(color='gold', width=2)))
fig1.update_layout(
template="plotly_dark", paper_bgcolor='black', plot_bgcolor='black',
height=400, margin=dict(l=40, r=40, t=20, b=40),
xaxis=dict(showgrid=True, gridcolor='#222', tickfont=dict(color='white')),
yaxis=dict(showgrid=True, gridcolor='#222', tickfont=dict(color='white'))
)
st.plotly_chart(fig1, use_container_width=True, key=f"trend_graph_{year}")
# Grafik Altı Dinamik Yorum
st.info(f"💡 **Analiz Notu:** {year} yılı için en yüksek fiyat {filtered_df['GLD'].max():.2f} USD, en düşük fiyat ise {filtered_df['GLD'].min():.2f} USD olarak kaydedilmiştir.")
st.divider()
# 8. YAN YANA GRAFİKLER VE YORUMLARI
c1, c2 = st.columns(2)
with c1:
st.markdown("#### 🎯 Dağılım / Distribution")
fig2 = px.histogram(filtered_df, x="GLD", nbins=30, color_discrete_sequence=['gold'], template="plotly_dark")
fig2.update_layout(paper_bgcolor='black', plot_bgcolor='black', height=350)
st.plotly_chart(fig2, use_container_width=True, key=f"dist_graph_{year}")
st.warning(f"📊 **Yorum:** {year} yılında altın fiyatlarının en yoğun olduğu bölgeler yukarıdaki histogramda gösterilmektedir.")
with c2:
st.markdown("#### 🌡️ Korelasyon / Correlation")
numeric_df = filtered_df.select_dtypes(include=['number']).drop(columns=['YEAR'], errors='ignore')
fig3 = px.imshow(numeric_df.corr(), text_auto=".2f", color_continuous_scale='YlOrRd', template="plotly_dark")
fig3.update_layout(paper_bgcolor='black', plot_bgcolor='black', height=350)
st.plotly_chart(fig3, use_container_width=True, key=f"corr_graph_{year}")
st.warning(f"🔗 **Yorum:** {year} yılında altının petrol, gümüş ve borsa ile olan korelasyon katsayıları hesaplanmıştır.")
st.divider()
# 9. VERİ TABLOSU (Her zaman açık)
st.markdown(f"### 📋 {year} Yılı Ham Veri Seti / View Data")
st.dataframe(filtered_df, use_container_width=True)
# İndirme Butonu
csv = filtered_df.to_csv(index=False).encode('utf-8')
st.download_button(f"📥 {year} Verilerini CSV İndir", data=csv, file_name=f'gold_data_{year}.csv')