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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import os
|
| 3 |
+
import glob
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import numpy as np
|
| 6 |
+
import gradio as gr
|
| 7 |
+
from ta.momentum import RSIIndicator
|
| 8 |
+
from ta.trend import MACD, SMAIndicator
|
| 9 |
+
from ta.volatility import BollingerBands
|
| 10 |
+
import lightgbm as lgb
|
| 11 |
+
|
| 12 |
+
# ==============================
|
| 13 |
+
# CONFIG
|
| 14 |
+
# ==============================
|
| 15 |
+
DATA_FOLDER = r"D:\Internship_Project\Crypto_Data_Tracker"
|
| 16 |
+
|
| 17 |
+
# ==============================
|
| 18 |
+
# LOAD & PREPARE DATA
|
| 19 |
+
# ==============================
|
| 20 |
+
def load_crypto_data():
|
| 21 |
+
csv_files = glob.glob(os.path.join(DATA_FOLDER, "*.csv"))
|
| 22 |
+
all_data = []
|
| 23 |
+
for file in csv_files:
|
| 24 |
+
coin_name = os.path.basename(file).replace('.csv', '')
|
| 25 |
+
temp_df = pd.read_csv(file)
|
| 26 |
+
temp_df['Coin'] = coin_name
|
| 27 |
+
all_data.append(temp_df)
|
| 28 |
+
|
| 29 |
+
df = pd.concat(all_data, ignore_index=True)
|
| 30 |
+
|
| 31 |
+
# Detect date and price columns
|
| 32 |
+
date_col = next((c for c in df.columns if 'date' in c.lower()), None)
|
| 33 |
+
price_col = next((c for c in df.columns if 'close' in c.lower()), None)
|
| 34 |
+
coin_col = 'Coin'
|
| 35 |
+
|
| 36 |
+
df[date_col] = pd.to_datetime(df[date_col], errors='coerce')
|
| 37 |
+
df = df.dropna(subset=[date_col])
|
| 38 |
+
|
| 39 |
+
# Add technical indicators
|
| 40 |
+
def add_indicators(g):
|
| 41 |
+
g = g.sort_values(by=date_col).copy()
|
| 42 |
+
g['Daily_Return'] = g[price_col].pct_change()
|
| 43 |
+
g['SMA_20'] = SMAIndicator(g[price_col], window=20).sma_indicator()
|
| 44 |
+
g['RSI'] = RSIIndicator(g[price_col], window=14).rsi()
|
| 45 |
+
macd = MACD(g[price_col])
|
| 46 |
+
g['MACD'] = macd.macd()
|
| 47 |
+
g['MACD_Signal'] = macd.macd_signal()
|
| 48 |
+
return g
|
| 49 |
+
|
| 50 |
+
df = df.groupby(coin_col, group_keys=False).apply(add_indicators)
|
| 51 |
+
|
| 52 |
+
return df, price_col, date_col, coin_col
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# ==============================
|
| 56 |
+
# SIMPLE CRYPTO PREDICTOR
|
| 57 |
+
# ==============================
|
| 58 |
+
class SimpleCryptoPredictor:
|
| 59 |
+
def __init__(self, df, price_col, date_col, coin_col):
|
| 60 |
+
self.df = df.copy()
|
| 61 |
+
self.price_col = price_col
|
| 62 |
+
self.date_col = date_col
|
| 63 |
+
self.coin_col = coin_col
|
| 64 |
+
self.model = None
|
| 65 |
+
self.available_coins = []
|
| 66 |
+
self.feature_columns = []
|
| 67 |
+
|
| 68 |
+
def initialize(self):
|
| 69 |
+
coin_counts = self.df[self.coin_col].value_counts()
|
| 70 |
+
self.available_coins = coin_counts[coin_counts >= 50].index.tolist()
|
| 71 |
+
self._train_model()
|
| 72 |
+
|
| 73 |
+
def _train_model(self):
|
| 74 |
+
features_list = []
|
| 75 |
+
for coin in self.available_coins[:20]:
|
| 76 |
+
coin_data = self.df[self.df[self.coin_col] == coin].copy()
|
| 77 |
+
if len(coin_data) < 100:
|
| 78 |
+
continue
|
| 79 |
+
features_df = self._create_features(coin_data, include_target=True)
|
| 80 |
+
if len(features_df) > 0:
|
| 81 |
+
features_list.append(features_df)
|
| 82 |
+
|
| 83 |
+
all_features = pd.concat(features_list, ignore_index=True)
|
| 84 |
+
feature_cols = ['return_1d', 'return_3d', 'return_7d', 'rsi_norm',
|
| 85 |
+
'vol_7d', 'sma_signal', 'return_lag1', 'vol_lag1']
|
| 86 |
+
available_cols = [c for c in feature_cols if c in all_features.columns]
|
| 87 |
+
X = all_features[available_cols].copy()
|
| 88 |
+
y = all_features['target_return'].copy()
|
| 89 |
+
mask = ~(X.isna().any(axis=1) | y.isna())
|
| 90 |
+
X = X[mask]
|
| 91 |
+
y = y[mask]
|
| 92 |
+
|
| 93 |
+
self.model = lgb.LGBMRegressor(n_estimators=100, max_depth=6, learning_rate=0.1, random_state=42)
|
| 94 |
+
self.model.fit(X, y)
|
| 95 |
+
self.feature_columns = available_cols
|
| 96 |
+
|
| 97 |
+
def _create_features(self, coin_data, include_target=False):
|
| 98 |
+
coin_data = coin_data.sort_values(self.date_col).copy()
|
| 99 |
+
if len(coin_data) < 30:
|
| 100 |
+
return pd.DataFrame()
|
| 101 |
+
coin_data['return_1d'] = coin_data[self.price_col].pct_change(1) * 100
|
| 102 |
+
coin_data['return_3d'] = coin_data[self.price_col].pct_change(3) * 100
|
| 103 |
+
coin_data['return_7d'] = coin_data[self.price_col].pct_change(7) * 100
|
| 104 |
+
coin_data['rsi_norm'] = (coin_data['RSI'] - 50) / 50
|
| 105 |
+
coin_data['vol_7d'] = coin_data['return_1d'].rolling(7).std()
|
| 106 |
+
coin_data['sma_20'] = coin_data[self.price_col].rolling(20).mean()
|
| 107 |
+
coin_data['sma_signal'] = np.where(coin_data[self.price_col] > coin_data['sma_20'], 1, -1)
|
| 108 |
+
coin_data['return_lag1'] = coin_data['return_1d'].shift(1)
|
| 109 |
+
coin_data['vol_lag1'] = coin_data['vol_7d'].shift(1)
|
| 110 |
+
if include_target:
|
| 111 |
+
coin_data['price_future'] = coin_data[self.price_col].shift(-1)
|
| 112 |
+
coin_data['target_return'] = ((coin_data['price_future'] - coin_data[self.price_col]) / coin_data[self.price_col] * 100)
|
| 113 |
+
coin_data = coin_data.replace([np.inf, -np.inf], np.nan)
|
| 114 |
+
return coin_data
|
| 115 |
+
|
| 116 |
+
def predict_coin(self, coin_name):
|
| 117 |
+
if coin_name not in self.available_coins:
|
| 118 |
+
return f"Coin '{coin_name}' not found."
|
| 119 |
+
coin_data = self.df[self.df[self.coin_col] == coin_name].copy()
|
| 120 |
+
features_df = self._create_features(coin_data)
|
| 121 |
+
latest = features_df.iloc[-1]
|
| 122 |
+
feature_values = [latest.get(c, 0) for c in self.feature_columns]
|
| 123 |
+
pred_return = self.model.predict([feature_values])[0]
|
| 124 |
+
price = latest.get(self.price_col, 0)
|
| 125 |
+
if pred_return > 3:
|
| 126 |
+
rec = "STRONG BUY π’"
|
| 127 |
+
elif pred_return > 1:
|
| 128 |
+
rec = "BUY π’"
|
| 129 |
+
elif pred_return > -1:
|
| 130 |
+
rec = "HOLD π‘"
|
| 131 |
+
elif pred_return > -3:
|
| 132 |
+
rec = "SELL π΄"
|
| 133 |
+
else:
|
| 134 |
+
rec = "STRONG SELL π΄"
|
| 135 |
+
return f"{coin_name}: Price=${price:.4f}, Predicted Return={pred_return:+.2f}%, Recommendation={rec}"
|
| 136 |
+
|
| 137 |
+
def find_opportunities(self, top_n=10):
|
| 138 |
+
predictions = []
|
| 139 |
+
for coin in self.available_coins:
|
| 140 |
+
coin_data = self.df[self.df[self.coin_col] == coin].copy()
|
| 141 |
+
features_df = self._create_features(coin_data)
|
| 142 |
+
if len(features_df) == 0:
|
| 143 |
+
continue
|
| 144 |
+
latest = features_df.iloc[-1]
|
| 145 |
+
feature_values = [latest.get(c, 0) for c in self.feature_columns]
|
| 146 |
+
pred_return = self.model.predict([feature_values])[0]
|
| 147 |
+
predictions.append((coin, latest.get(self.price_col, 0), pred_return))
|
| 148 |
+
predictions.sort(key=lambda x: x[2], reverse=True)
|
| 149 |
+
return pd.DataFrame(predictions[:top_n], columns=['Coin', 'Price', 'Predicted Return %'])
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
# ==============================
|
| 153 |
+
# INIT
|
| 154 |
+
# ==============================
|
| 155 |
+
df, price_col, date_col, coin_col = load_crypto_data()
|
| 156 |
+
predictor = SimpleCryptoPredictor(df, price_col, date_col, coin_col)
|
| 157 |
+
predictor.initialize()
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
# ==============================
|
| 161 |
+
# GRADIO APP
|
| 162 |
+
# ==============================
|
| 163 |
+
def predict_single(coin):
|
| 164 |
+
return predictor.predict_coin(coin)
|
| 165 |
+
|
| 166 |
+
def top_opportunities(n):
|
| 167 |
+
df_top = predictor.find_opportunities(int(n))
|
| 168 |
+
return df_top
|
| 169 |
+
|
| 170 |
+
coin_dropdown = gr.Dropdown(choices=predictor.available_coins, label="Select Coin")
|
| 171 |
+
top_n_slider = gr.Slider(1, 20, value=10, step=1, label="Top N Opportunities")
|
| 172 |
+
|
| 173 |
+
with gr.Blocks() as demo:
|
| 174 |
+
gr.Markdown("## π Crypto Prediction Dashboard")
|
| 175 |
+
with gr.Row():
|
| 176 |
+
with gr.Column():
|
| 177 |
+
gr.Markdown("### Single Coin Prediction")
|
| 178 |
+
coin_input = gr.Dropdown(choices=predictor.available_coins, label="Select Coin")
|
| 179 |
+
predict_btn = gr.Button("Predict")
|
| 180 |
+
prediction_output = gr.Textbox(label="Prediction Result")
|
| 181 |
+
with gr.Column():
|
| 182 |
+
gr.Markdown("### Top Opportunities")
|
| 183 |
+
top_n_input = gr.Slider(1, 20, value=10, step=1, label="Top N Opportunities")
|
| 184 |
+
top_btn = gr.Button("Find Opportunities")
|
| 185 |
+
table_output = gr.Dataframe(headers=["Coin", "Price", "Predicted Return %"])
|
| 186 |
+
|
| 187 |
+
predict_btn.click(predict_single, inputs=coin_input, outputs=prediction_output)
|
| 188 |
+
top_btn.click(top_opportunities, inputs=top_n_input, outputs=table_output)
|
| 189 |
+
|
| 190 |
+
if __name__ == "__main__":
|
| 191 |
+
demo.launch()
|