0% found this document useful (0 votes)
8 views3 pages

Lightbgm Train

The document outlines a Python script that fetches cryptocurrency market data using the CCXT library and trains a LightGBM model to predict price movements based on various technical indicators. It includes classes for data fetching and indicator calculations, as well as a main loop for training models on multiple symbols and timeframes. The trained models are saved to a specified directory for future use.

Uploaded by

fawadtaii1122
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views3 pages

Lightbgm Train

The document outlines a Python script that fetches cryptocurrency market data using the CCXT library and trains a LightGBM model to predict price movements based on various technical indicators. It includes classes for data fetching and indicator calculations, as well as a main loop for training models on multiple symbols and timeframes. The trained models are saved to a specified directory for future use.

Uploaded by

fawadtaii1122
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

import os

import joblib
import pandas as pd
import lightgbm as lgb
from sklearn.model_selection import train_test_split
import ccxt

# === CONFIGURATION ===


MODEL_DIR = "./models/"
os.makedirs(MODEL_DIR, exist_ok=True)

# === DATA FETCHER ===


class DataFetcher:
def __init__(self, api_key, secret):
self.exchange = ccxt.mexc({
'apiKey': api_key,
'secret': secret,
'enableRateLimit': True
})

def get_symbols(self):
info = self.exchange.fetch_markets()
return [m['symbol'] for m in info if m['quote'] == 'USDT']

def fetch_ohlcv(self, symbol, timeframe, limit=100):


data = self.exchange.fetch_ohlcv(symbol, timeframe=timeframe, limit=limit)
df = pd.DataFrame(data, columns=['timestamp', 'open', 'high', 'low',
'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
return df

# === ADDITIONAL INDICATORS ===


class IndicatorEngine:
@staticmethod
def apply_all(df):
df['rsi'] = IndicatorEngine.rsi(df)
df['macd'], df['macd_signal'], df['macd_hist'] = IndicatorEngine.macd(df)
df['ema'] = df['close'].ewm(span=20, adjust=False).mean() # Exponential
Moving Average
df['sma'] = df['close'].rolling(window=50).mean() # Simple Moving Average
df['stoch_k'], df['stoch_d'] = IndicatorEngine.stochastic_oscillator(df)
df['atr'] = IndicatorEngine.atr(df)
return df

@staticmethod
def rsi(df, period=14):
delta = df['close'].diff()
gain = delta.where(delta > 0, 0)
loss = -delta.where(delta < 0, 0)
avg_gain = gain.rolling(window=period).mean()
avg_loss = loss.rolling(window=period).mean()
rs = avg_gain / avg_loss
return 100 - (100 / (1 + rs))

@staticmethod
def macd(df, fast=12, slow=26, signal=9):
macd = df['close'].ewm(span=fast, adjust=False).mean() -
df['close'].ewm(span=slow, adjust=False).mean()
macd_signal = macd.ewm(span=signal, adjust=False).mean()
macd_hist = macd - macd_signal
return macd, macd_signal, macd_hist

@staticmethod
def stochastic_oscillator(df, k_period=14, d_period=3):
low_min = df['low'].rolling(window=k_period).min()
high_max = df['high'].rolling(window=k_period).max()
stoch_k = 100 * ((df['close'] - low_min) / (high_max - low_min))
stoch_d = stoch_k.rolling(window=d_period).mean()
return stoch_k, stoch_d

@staticmethod
def atr(df, period=14):
tr = pd.concat([df['high'] - df['low'],
(df['high'] - df['close'].shift()).abs(),
(df['low'] - df['close'].shift()).abs()], axis=1)
atr = tr.max(axis=1).rolling(window=period).mean()
return atr

# === LIGHTGBM MODEL TRAINING ===


def train_lightgbm_model(symbol, timeframe, fetcher):
df = fetcher.fetch_ohlcv(symbol, timeframe)
df = IndicatorEngine.apply_all(df)

# Defining features (including EMA, SMA)


features = ['rsi', 'macd', 'macd_signal', 'macd_hist', 'ema', 'sma', 'stoch_k',
'stoch_d', 'atr']
X = df[features]
y = (df['close'].shift(-1) > df['close']).astype(int) # Target: 1 if price
goes up, else 0

# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)

# Train LightGBM model


lgb_model = lgb.LGBMClassifier()
lgb_model.fit(X_train, y_train)

# Save the trained LightGBM model


joblib.dump(lgb_model, os.path.join(MODEL_DIR,
f'lightgbm_{symbol}_{timeframe}.pkl'))

# Evaluate the model (optional)


accuracy = lgb_model.score(X_test, y_test)
print(f"LightGBM Model Accuracy for {symbol} at {timeframe} timeframe:
{accuracy * 100:.2f}%")

# === MAIN TRAINING LOOP ===


if __name__ == '__main__':
api_key = 'mx0vglW9QUdnlBkEqr' # Your MEXC API key
secret_key = '82b4df93e0cb4b92a08f3fd443719355' # Your MEXC Secret key

# Initialize the fetcher


fetcher = DataFetcher(api_key, secret_key)

# Training for each symbol and timeframe


symbols = fetcher.get_symbols()
timeframes = ['1m', '5m', '15m', '1h', '4h', '1d'] # Timeframes you want to
train on

for symbol in symbols[:750]: # You can limit the number of symbols for testing
purposes (replace 10 with 750 if needed)
for timeframe in timeframes:
print(f"Training LightGBM model for {symbol} at {timeframe}
timeframe...")
train_lightgbm_model(symbol, timeframe, fetcher)
print(f"LightGBM model saved for {symbol} at {timeframe} timeframe.")

You might also like