| import gradio as gr |
| import yfinance as yf |
| import plotly.graph_objects as go |
| import pandas as pd |
| import numpy as np |
| from sklearn.linear_model import LinearRegression |
|
|
| def forecast_crypto(coin, currency, window_days): |
| |
| base_ticker = f"{coin}-USD" |
| data = yf.download(base_ticker, period="1y", interval="1d") |
| |
| if data.empty: |
| return None, f"β οΈ Gagal mengambil data untuk {base_ticker}." |
| |
| if isinstance(data.columns, pd.MultiIndex): |
| data.columns = data.columns.get_level_values(0) |
| |
| |
| if currency != "USD": |
| fx_ticker = f"USD{currency}=X" |
| fx_data = yf.download(fx_ticker, period="1y", interval="1d") |
| |
| if fx_data.empty: |
| return None, f"β οΈ Gagal mengambil data kurs {fx_ticker}." |
| |
| if isinstance(fx_data.columns, pd.MultiIndex): |
| fx_data.columns = fx_data.columns.get_level_values(0) |
| |
| |
| |
| fx_close = fx_data['Close'].reindex(data.index).ffill().bfill() |
| |
| |
| for col in ['Open', 'High', 'Low', 'Close']: |
| if col in data.columns: |
| data[col] = data[col] * fx_close |
|
|
| |
| data['Trend (SMA)'] = data['Close'].rolling(window=int(window_days)).mean() |
| |
| |
| |
| df_pred = data[['Close']].dropna().tail(int(window_days)) |
| |
| if len(df_pred) < 3: |
| return None, "β οΈ Data tidak cukup untuk melakukan prediksi." |
|
|
| |
| X = np.arange(len(df_pred)).reshape(-1, 1) |
| y = df_pred['Close'].values |
| |
| model = LinearRegression() |
| model.fit(X, y) |
| |
| |
| next_day_X = np.array([[len(df_pred)]]) |
| predicted_price = model.predict(next_day_X)[0] |
| |
| |
| fig = go.Figure() |
| |
| |
| fig.add_trace(go.Scatter(x=data.index, y=data['Close'], |
| mode='lines', name='Harga Aktual', |
| line=dict(color='#2980b9', width=2))) |
| |
| |
| fig.add_trace(go.Scatter(x=data.index, y=data['Trend (SMA)'], |
| mode='lines', name=f'Garis Tren ({window_days} Hari)', |
| line=dict(color='#e74c3c', width=2, dash='dash'))) |
| |
| fig.update_layout( |
| title=f"π AI Market Forecasting: {coin} to {currency}", |
| xaxis_title="Tanggal", |
| yaxis_title=f"Harga ({currency})", |
| template="plotly_white", |
| hovermode="x unified", |
| legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1) |
| ) |
| |
| |
| last_price = float(data['Close'].iloc[-1]) |
| current_trend = float(data['Trend (SMA)'].iloc[-1]) |
| |
| status = "π’ Naik (Bullish)" if last_price > current_trend else "π΄ Turun (Bearish)" |
| |
| |
| simbol = "Rp" if currency == "IDR" else ("$" if currency == "USD" else ("β¬" if currency == "EUR" else "Β£")) |
| |
| summary = f""" |
| ### π Market & Prediction Summary ({coin}/{currency}) |
| * **Harga Penutupan Terakhir:** **{simbol} {last_price:,.2f}** |
| * **Status Tren Pasar:** **{status}** |
| * π€ **AI Prediksi Harga Besok:** **{simbol} {predicted_price:,.2f}** |
| |
| *(Catatan: Konversi mata uang dilakukan secara real-time menggunakan data pasar valuta asing. Prediksi dihitung menggunakan Machine Learning berdasarkan momentum {window_days} hari terakhir).* |
| """ |
| |
| return fig, summary |
|
|
| |
| with gr.Blocks(theme=gr.themes.Soft(), title="CryptoProphet AI") as app: |
| gr.Markdown("# π€ CryptoProphet: AI Market Forecasting") |
| gr.Markdown("Sistem analitik prediktif yang menarik data *real-time* via API, melakukan konversi kurs otomatis, dan menggunakan **Machine Learning** untuk meramalkan harga kripto di hari berikutnya.") |
| |
| with gr.Row(): |
| with gr.Column(scale=1): |
| in_coin = gr.Dropdown(choices=["BTC", "ETH", "SOL", "BNB", "DOGE", "XRP", "ADA"], |
| value="BTC", label="Pilih Koin Kripto") |
| in_currency = gr.Dropdown(choices=["USD", "IDR", "EUR", "GBP"], |
| value="IDR", label="Pilih Mata Uang (Fiat)") |
| in_days = gr.Slider(minimum=7, maximum=90, value=30, step=1, label="Jendela Prediksi ML (Hari)") |
| btn = gr.Button("π Jalankan Prediksi AI", variant="primary") |
| |
| with gr.Column(scale=2): |
| out_summary = gr.Markdown("### π Memuat data prediksi AI...") |
| |
| with gr.Row(): |
| out_plot = gr.Plot() |
| |
| btn.click(forecast_crypto, inputs=[in_coin, in_currency, in_days], outputs=[out_plot, out_summary]) |
| app.load(forecast_crypto, inputs=[in_coin, in_currency, in_days], outputs=[out_plot, out_summary]) |
|
|
| app.launch() |