Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import yfinance as yf | |
| import numpy as np | |
| import pandas as pd | |
| import matplotlib.pyplot as plt | |
| from sklearn.svm import SVR | |
| from sklearn.preprocessing import StandardScaler | |
| def predict_finance(symbol): | |
| try: | |
| # 1. VERİ ÇEKME | |
| df = yf.download(symbol, period='1y', interval='1d') | |
| if df.empty: | |
| return "Veri çekilemedi, lütfen sembolü kontrol edin.", None | |
| # 2. VERİ HAZIRLIĞI | |
| prediction_days = 30 | |
| df['Prediction'] = df[['Close']].shift(-prediction_days) | |
| # X: Mevcut fiyatlar, X_forecast: Tahmin için kullanılacak son 30 gün | |
| X = np.array(df[['Close']]) | |
| X_forecast = X[-prediction_days:] | |
| X = X[:-prediction_days] | |
| # y: Hedef fiyatlar | |
| y = np.array(df['Prediction'])[:-prediction_days] | |
| # 3. ÖLÇEKLENDİRME (Scaling) - Hataları önler | |
| scaler_x = StandardScaler() | |
| scaler_y = StandardScaler() | |
| X_scaled = scaler_x.fit_transform(X) | |
| y_scaled = scaler_y.fit_transform(y.reshape(-1, 1)).ravel() | |
| X_forecast_scaled = scaler_x.transform(X_forecast) | |
| # 4. MODEL EĞİTİMİ (SVR) | |
| model = SVR(kernel='rbf', C=1e3, gamma=0.1) | |
| model.fit(X_scaled, y_scaled) | |
| # 5. TAHMİN | |
| prediction_scaled = model.predict(X_forecast_scaled) | |
| prediction = scaler_y.inverse_transform(prediction_scaled.reshape(-1, 1)) | |
| # 6. GRAFİK OLUŞTURMA | |
| plt.figure(figsize=(12, 6)) | |
| # Son 90 günü mavi çizgiyle göster | |
| plt.plot(df.index[-90:], df['Close'][-90:], label='Gerçek Fiyatlar', color='#1f77b4', linewidth=2) | |
| # Gelecek tarihlerini oluştur ve kırmızı kesikli çizgiyle göster | |
| future_dates = pd.date_range(start=df.index[-1], periods=prediction_days + 1, freq='D')[1:] | |
| plt.plot(future_dates, prediction, label='30 Günlük AI Tahmini', color='#d62728', linestyle='--', marker='o', markersize=4) | |
| plt.title(f'{symbol} Fiyat Analizi ve Gelecek Projeksiyonu', fontsize=14) | |
| plt.xlabel('Tarih') | |
| plt.ylabel('Fiyat (USD)') | |
| plt.legend() | |
| plt.grid(True, alpha=0.3) | |
| plot_path = "plot.png" | |
| plt.savefig(plot_path) | |
| plt.close('all') # Bellek temizliği | |
| # 7. ÖZET BİLGİ VE HATA FİX (Series format hatası burada çözüldü) | |
| # .item() kullanarak Pandas Series nesnesini saf sayıya çeviriyoruz | |
| current_price = float(df['Close'].iloc[-1].item()) | |
| predicted_price = float(prediction[-1][0]) | |
| change_pct = ((predicted_price - current_price) / current_price) * 100 | |
| summary = ( | |
| f"📊 {symbol} Analiz Özeti:\n" | |
| f"--------------------------\n" | |
| f"Güncel Fiyat: ${current_price:,.2f}\n" | |
| f"30 Gün Sonraki Tahmin: ${predicted_price:,.2f}\n" | |
| f"Beklenen Değişim: %{change_pct:+.2f}" | |
| ) | |
| return summary, plot_path | |
| except Exception as e: | |
| return f"Bir hata oluştu: {str(e)}", None | |
| # 8. GRADIO ARAYÜZ TASARIMI | |
| # Kullanıcı dostu isimler ve sembol karşılıkları | |
| symbol_mapping = { | |
| "Bitcoin (BTC)": "BTC-USD", | |
| "Ethereum (ETH)": "ETH-USD", | |
| "Dogecoin (DOGE)": "DOGE-USD", | |
| "Cardano (ADA)": "ADA-USD", | |
| "Nvidia (NVDA)": "NVDA", | |
| "Microsoft (MSFT)": "MSFT", | |
| "Intel (INTC)": "INTC" | |
| } | |
| with gr.Blocks(theme=gr.themes.Soft()) as demo: | |
| gr.Markdown("# 🚀 AI Finansal Tahmin Paneli") | |
| gr.Markdown("Seçtiğiniz varlık için SVR algoritması kullanarak gelecek 30 günlük fiyat projeksiyonu oluşturun.") | |
| with gr.Row(): | |
| with gr.Column(): | |
| input_dropdown = gr.Dropdown( | |
| choices=list(symbol_mapping.values()), | |
| label="Enstrüman / Sembol Seçin", | |
| value="BTC-USD" | |
| ) | |
| btn = gr.Button("Analiz Et", variant="primary") | |
| with gr.Column(): | |
| output_text = gr.Textbox(label="Tahmin Sonucu", lines=6) | |
| output_plot = gr.Image(label="Tahmin Grafiği") | |
| btn.click(fn=predict_finance, inputs=input_dropdown, outputs=[output_text, output_plot]) | |
| if __name__ == "__main__": | |
| demo.launch() |