Sos / Pach.py
Pezh's picture
Create Pach.py
7a7a869 verified
raw
history blame
3.88 kB
import ccxt
import pandas as pd
import streamlit as st
import xgboost as xgb
from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split
exchange = ccxt.mexc({
'apiKey': 'mx0vglbkoCOwmqV5tn',
'secret': 'c6d8cc8953fd405787ed54e3488ae0db',
'enableRateLimit': True,
})
def fetch_ohlcv_data(symbol, timeframe, limit):
return exchange.fetch_ohlcv(symbol, timeframe, since=None, limit=limit)
def data_to_dataframe(data):
df = pd.DataFrame(data, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
df.set_index('timestamp', inplace=True)
return df
def prepare_dataset(df, lags):
X = pd.DataFrame()
y = pd.DataFrame()
for lag in range(1, lags + 1):
shifted_close = df['close'].shift(lag)
X[f'close_lag_{lag}'] = shifted_close
y = df['close'].shift(-1)
return X, y
def train_xgboost_model(X_train, y_train):
dtrain = xgb.DMatrix(X_train, label=y_train)
params = {
'objective': 'reg:squarederror',
'eval_metric': 'rmse',
}
model = xgb.train(params, dtrain)
return model
def predict_next_hour_price(df, model, lags):
X_test = pd.DataFrame()
for lag in range(1, lags + 1):
shifted_close = df['close'].shift(lag)
X_test[f'close_lag_{lag}'] = shifted_close
X_test = X_test.tail(1)
dtest = xgb.DMatrix(X_test)
next_hour_price = model.predict(dtest)
return next_hour_price
def evaluate_prediction_accuracy(y_test, y_pred):
accuracy = r2_score(y_test, y_pred)
return accuracy
def execute_trade(exchange, symbol, side, amount, leverage):
order = exchange.create_market_order(symbol, side, amount)
# Set leverage for the order
if leverage is not None and leverage != 1:
position = exchange.fetch_position(symbol)
if position is not None:
current_leverage = position['info']['leverage']
if current_leverage != leverage:
# Update leverage for the position
exchange.set_leverage(leverage, symbol)
return order
symbol = 'BTC/USDT'
timeframe = '1h'
limit = 100
lags = 12
test_size = 0.3
leverage = 5
ohlcv_data = fetch_ohlcv_data(symbol, timeframe, limit)
df = data_to_dataframe(ohlcv_data)
if st.button("hoo"):
st.write(df)
X, y = prepare_dataset(df, lags)
# Replace missing values with the mean of the column
X = X.fillna(X.mean())
y = y.fillna(y.mean())
#X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size)
#model, scaler = train_xgboost_model(X_train, y_train)
#y_pred = model.predict(X_test)
# Inverse transform the predicted values to get the original scale
#y_pred = scaler.inverse_transform(y_pred.reshape(-1, 1))
#accuracy = evaluate_prediction_accuracy(y_test, y_pred)
#X, y = prepare_dataset(df, lags)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size)
model = train_xgboost_model(X_train, y_train)
y_pred = model.predict(X_test)
accuracy = evaluate_prediction_accuracy(y_test, y_pred)
if accuracy > 0.9:
latest_data = df.tail(lags)
predicted_price = predict_next_hour_price(latest_data, model, lags)
current_price = latest_data['close'].iloc[-1]
if predicted_price > current_price:
# Buy BTC
amount = 0.001 # Set the amount you want to trade
order = execute_trade(exchange, symbol, 'buy', amount, leverage)
print(f"Bought {amount} BTC at {current_price} with {leverage}x leverage")
elif predicted_price < current_price:
# Sell BTC
amount = 0.001 # Set the amount you want to trade
order = execute_trade(exchange, symbol, 'sell', amount, leverage)
print(f"Sold {amount} BTC at {current_price} with {leverage}x leverage")
else:
print("Accuracy is low, not placing order.")