Pezh commited on
Commit
b6a287b
1 Parent(s): fb532ef

Create mas.py

Browse files
Files changed (1) hide show
  1. mas.py +88 -0
mas.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ccxt
2
+ import pandas as pd
3
+ import xgboost as xgb
4
+ from sklearn.metrics import r2_score
5
+ from sklearn.model_selection import train_test_split
6
+ import time
7
+
8
+ exchange = ccxt.mexc({
9
+ 'apiKey': 'YOUR_API_KEY',
10
+ 'secret': 'YOUR_SECRET_KEY',
11
+ 'enableRateLimit': True,
12
+ })
13
+
14
+ def fetch_ohlcv_data(symbol, timeframe, limit):
15
+ return exchange.fetch_ohlcv(symbol, timeframe, since=None, limit=limit)
16
+
17
+ def data_to_dataframe(data):
18
+ df = pd.DataFrame(data, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
19
+ df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
20
+ df.set_index('timestamp', inplace=True)
21
+ return df
22
+
23
+ def prepare_dataset(df, lags):
24
+ X = pd.DataFrame()
25
+ y = pd.DataFrame()
26
+
27
+ for lag in range(1, lags + 1):
28
+ shifted_close = df['close'].shift(lag)
29
+ X[f'close_lag_{lag}'] = shifted_close
30
+
31
+ y = df['close'].shift(-1)
32
+ return X, y
33
+
34
+ def train_xgboost_model(X_train, y_train):
35
+ dtrain = xgb.DMatrix(X_train, label=y_train)
36
+ params = {
37
+ 'objective': 'reg:squarederror',
38
+ 'eval_metric': 'rmse',
39
+ }
40
+
41
+ model = xgb.train(params, dtrain)
42
+ return model
43
+
44
+ def predict_next_hour_price(df, model, lags):
45
+ X_test = pd.DataFrame()
46
+
47
+ for lag in range(1, lags + 1):
48
+ shifted_close = df['close'].shift(lag)
49
+ X_test[f'close_lag_{lag}'] = shifted_close
50
+
51
+ X_test = X_test.tail(1)
52
+ dtest = xgb.DMatrix(X_test)
53
+ next_hour_price = model.predict(dtest)
54
+ return next_hour_price
55
+
56
+ def evaluate_prediction_accuracy(y_test, y_pred):
57
+ accuracy = r2_score(y_test, y_pred)
58
+ return accuracy
59
+
60
+ symbol = 'BTC/USDT'
61
+ timeframe = '1h'
62
+ limit = 100000
63
+ lags = 12
64
+ test_size = 0.3
65
+
66
+ # Fetch initial data
67
+ ohlcv_data = fetch_ohlcv_data(symbol, timeframe, limit)
68
+ df = data_to_dataframe(ohlcv_data)
69
+
70
+ # Prepare dataset and train the model
71
+ X, y = prepare_dataset(df, lags)
72
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size)
73
+ model = train_xgboost_model(X_train, y_train)
74
+
75
+ while True:
76
+ # Fetch new data every hour
77
+ ohlcv_data = fetch_ohlcv_data(symbol, timeframe, limit)
78
+ df = data_to_dataframe(ohlcv_data)
79
+
80
+ # Make prediction
81
+ latest_data = df.tail(lags)
82
+ predicted_price = predict_next_hour_price(latest_data, model, lags)
83
+
84
+ # Print predicted next hour price
85
+ print(f"Predicted next hour price: ${predicted_price[0]}")
86
+
87
+ # Sleep for 1 hour (3600 seconds)
88
+ time.sleep(3600)