Untitled
unknown
plain_text
a year ago
7.1 kB
15
Indexable
import ccxt
import numpy as np
import pandas as pd
import pandas_ta as ta
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import f1_score
import joblib
import os
from datetime import datetime, timedelta
import time
# Binance borsasına bağlanın
exchange = ccxt.binanceusdm()
# İşlem yapacağınız sembolleri liste olarak tanımlayın
symbols = ['BNB/USDT']
timeframe = '15m' # Zaman dilimi
limit = 500 # Kaç veri noktası almak istediğinizi belirleyin
ma_period = 10 # Hareketli ortalama süresi
# Zaman dilimlerini milisaniye cinsine çeviren bir fonksiyon
timeframe_to_minutes = {
'1m': 1,
'3m': 3,
'5m': 5,
'15m': 15,
'30m': 30,
'1h': 60,
'2h': 120,
'4h': 240,
'6h': 360,
'12h': 720,
'1d': 1440,
}
# Timeframe'in dakika cinsinden değeri
timeframe_minutes = timeframe_to_minutes[timeframe]
# Oyun teorisi tabanlı özellikleri hesaplama fonksiyonu
def calculate_game_theory_features(df):
df['price_change'] = df['close'].diff()
df['up_moves'] = np.where(df['price_change'] > 0, 1, 0)
df['down_moves'] = np.where(df['price_change'] < 0, 1, 0)
df['total_up_moves'] = df['up_moves'].cumsum()
df['total_down_moves'] = df['down_moves'].cumsum()
df['volume_change'] = df['volume'].diff().fillna(0)
df['volume_up'] = np.where(df['volume_change'] > 0, 1, 0)
df['volume_down'] = np.where(df['volume_change'] < 0, 1, 0)
df['total_volume_up'] = df['volume_up'].cumsum()
df['total_volume_down'] = df['volume_down'].cumsum()
return df
def fetch_and_update_data(symbol, timeframe, limit):
# Veri dosyası adı
filename = f'{symbol.replace("/", "_")}_veri.csv'
if os.path.exists(filename):
df = pd.read_csv(filename)
last_timestamp = pd.to_datetime(df['timestamp']).max()
start_time = last_timestamp + timedelta(minutes=timeframe_minutes)
start_time = int(start_time.timestamp() * 1000) # Milisaniyeye çevir
else:
start_time = None
ohlcv = exchange.fetch_ohlcv(symbol, timeframe, since=start_time, limit=limit)
if len(ohlcv) == 0:
print(f'{symbol} için yeni veri bulunamadı.')
return pd.DataFrame() # Boş DataFrame döndür
new_df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
new_df['symbol'] = symbol
new_df['timestamp'] = pd.to_datetime(new_df['timestamp'], unit='ms')
if os.path.exists(filename):
df = pd.concat([df, new_df], ignore_index=True).drop_duplicates(subset=['timestamp']).reset_index(drop=True)
else:
df = new_df
# Teknik analiz verilerini hesaplayın
df['rsi'] = ta.rsi(df['close'], length=14)
bbands = ta.bbands(df['close'], length=20, std=2)
df['bb_upper'] = bbands['BBU_20_2.0']
df['bb_middle'] = bbands['BBM_20_2.0']
df['bb_lower'] = bbands['BBL_20_2.0']
df['bollinger_flag'] = np.where(df['close'] > df['bb_upper'], 1, np.where(df['close'] < df['bb_lower'], -1, 0))
stoch = ta.stoch(df['high'], df['low'], df['close'], k=14, d=3)
df['stoch_k'] = stoch['STOCHk_14_3_3']
df['stochastic_flag'] = np.where(df['stoch_k'] < 20, -1, np.where(df['stoch_k'] > 80, 1, 0))
macd = ta.macd(df['close'], fast=12, slow=26, signal=9)
df['macd_line'] = macd['MACD_12_26_9']
df['macd_signal_line'] = macd['MACDs_12_26_9']
df['macd_signal'] = np.where((df['macd_line'].shift(1) < df['macd_signal_line'].shift(1)) &
(df['macd_line'] > df['macd_signal_line']), 1,
np.where((df['macd_line'].shift(1) > df['macd_signal_line'].shift(1)) &
(df['macd_line'] < df['macd_signal_line']), -1, 0))
df['ma'] = ta.sma(df['close'], length=ma_period)
df['ma_flag'] = np.where(df['close'] > df['ma'], 1, 0)
df['body_size'] = np.abs(df['close'] - df['open']).round(2)
df['unit_diff'] = df['close'].diff().round(2)
df['percent_diff'] = (df['unit_diff'] / df['close'].shift(1) * 100).round(2)
df['percent_high_diff'] = ((df['high'] - df['open']) / df['open'] * 100).round(2)
df['percent_low_diff'] = ((df['low'] - df['open']) / df['open'] * 100).round(2)
df.dropna(inplace=True)
# Oyun teorisi tabanlı özellikleri hesapla
df = calculate_game_theory_features(df)
df.to_csv(filename, index=False)
print(f'{symbol} için veri başarıyla güncellendi ve kaydedildi.')
return df
def train_and_evaluate_model(df):
X = df.drop(['symbol', 'timestamp', 'percent_diff'], axis=1)
y = np.where(df['percent_diff'] > 0, 1, 0)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = GradientBoostingClassifier()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
f1 = f1_score(y_test, y_pred)
print(f'F1 Skoru: {f1}')
model_filename = 'gradient_boosting_model.pkl'
if os.path.exists(model_filename):
previous_model = joblib.load(model_filename)
y_prev_pred = previous_model.predict(X_test)
prev_f1 = f1_score(y_test, y_prev_pred)
print(f'Önceki Modelin F1 Skoru: {prev_f1}')
if f1 > prev_f1:
joblib.dump(model, model_filename)
print("Yeni model kaydedildi.")
active_model = model
else:
print("Önceki model daha iyi performans gösteriyor, yeni model kaydedilmedi.")
active_model = previous_model
else:
joblib.dump(model, model_filename)
print("Model ilk kez kaydedildi.")
active_model = model
return active_model
def predict_next_movement(active_model, df):
next_input = df.iloc[-1:].drop(['symbol', 'timestamp', 'percent_diff'], axis=1).values
next_prediction = active_model.predict(next_input)
if next_prediction[0] == 1:
print("Tahmin: Gelecek mumda fiyat yükselecek.")
else:
print("Tahmin: Gelecek mumda fiyat düşecek.")
def determine_next_run_time(timestamp_str, timeframe_minutes):
current_time = datetime.strptime(timestamp_str, '%Y-%m-%d %H:%M:%S')
next_run_time = current_time + timedelta(minutes=timeframe_minutes)
return next_run_time
# Başlangıç zamanını ayarla
initial_timestamp = '2024-09-12 19:27:00'
next_run_time = determine_next_run_time(initial_timestamp, timeframe_minutes)
while True:
now = datetime.utcnow()
if now >= next_run_time:
for symbol in symbols:
df = fetch_and_update_data(symbol, timeframe, limit)
if df is not None and not df.empty:
active_model = train_and_evaluate_model(df)
predict_next_movement(active_model, df)
next_run_time = determine_next_run_time(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S'), timeframe_minutes)
sleep_duration = (next_run_time - now).total_seconds()
print(f'{sleep_duration} saniye bekleniyor...')
time.sleep(max(sleep_duration, 0))
Editor is loading...
Leave a Comment