Hopper1394 commited on
Commit
f0cfef4
1 Parent(s): ba5c7ef

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +142 -0
app.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BINANCE_API_KEY = 'https://api.binance.com/api/v3/ticker/price?symbol='
2
+ ALPHA_VANTAGE_API_KEY = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=IBM&apikey=demo'
3
+ YAHOO_FINANCE_API_KEY = 'your_yahoo_finance_api_key'
4
+ TRADING_VIEW_API_KEY = 'your_trading_view_api_key'
5
+ BINOMO_API_KEY = 'your_binomo_api_key'
6
+ TELEGRAM_BOT_API_KEY = '7074501421:AAEOoCMvXxr_T6sYIXAvHIDr515pLZ_ERtE'
7
+
8
+ # data_acquisition.py
9
+ import requests
10
+ import pandas as pd
11
+ import numpy as np
12
+ from sklearn.preprocessing import StandardScaler
13
+ from tensorflow.keras.models import Sequential
14
+ from tensorflow.keras.layers import LSTM, Dense, Dropout
15
+ from telegram.ext import Updater, CommandHandler
16
+
17
+ def fetch_binance_data(pair):
18
+ url = f"https://api.binance.com/api/v3/klines?symbol={pair}&interval=1h"
19
+ response = requests.get(url)
20
+ data = response.json()
21
+ df = pd.DataFrame(data, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_asset_volume', 'number_of_trades', 'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume', 'ignore'])
22
+ df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
23
+ return df[['timestamp', 'open', 'high', 'low', 'close', 'volume']]
24
+
25
+ def fetch_alpha_vantage_data(pair):
26
+ symbol = pair.split("USDT")[0] # Assuming pair like BTCUSDT
27
+ url = f"https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={symbol}&interval=60min&apikey={ALPHA_VANTAGE_API_KEY}"
28
+ response = requests.get(url)
29
+ data = response.json()
30
+ time_series_key = 'Time Series (60min)'
31
+ if time_series_key not in data:
32
+ raise ValueError(f"Error fetching data from Alpha Vantage: {data}")
33
+ df = pd.DataFrame(data[time_series_key]).T
34
+ df.columns = ['open', 'high', 'low', 'close', 'volume']
35
+ df.index = pd.to_datetime(df.index)
36
+ return df.reset_index().rename(columns={'index': 'timestamp'})
37
+
38
+ def fetch_yahoo_finance_data(pair):
39
+ url = f"https://yfapi.net/v8/finance/chart/{pair}?interval=60m"
40
+ headers = {'x-api-key': YAHOO_FINANCE_API_KEY}
41
+ response = requests.get(url, headers=headers)
42
+ data = response.json()
43
+ timestamps = data['chart']['result'][0]['timestamp']
44
+ ohlc = data['chart']['result'][0]['indicators']['quote'][0]
45
+ df = pd.DataFrame({
46
+ 'timestamp': pd.to_datetime(timestamps, unit='s'),
47
+ 'open': ohlc['open'],
48
+ 'high': ohlc['high'],
49
+ 'low': ohlc['low'],
50
+ 'close': ohlc['close'],
51
+ 'volume': ohlc['volume']
52
+ })
53
+ return df
54
+
55
+ def fetch_trading_view_data(pair):
56
+ # Placeholder for TradingView API data fetching
57
+ raise NotImplementedError("TradingView API integration not implemented.")
58
+
59
+ def fetch_binomo_data(pair):
60
+ # Placeholder for Binomo API data fetching
61
+ raise NotImplementedError("Binomo API integration not implemented.")
62
+
63
+ def get_combined_data(pair):
64
+ df_binance = fetch_binance_data(pair)
65
+ df_alpha = fetch_alpha_vantage_data(pair)
66
+ df_yahoo = fetch_yahoo_finance_data(pair)
67
+ # Merge dataframes on timestamp
68
+ df = pd.merge(df_binance, df_alpha, on='timestamp', suffixes=('_binance', '_alpha'))
69
+ df = pd.merge(df, df_yahoo, on='timestamp', suffixes=('', '_yahoo'))
70
+ # Drop any redundant columns or handle conflicts
71
+ return df
72
+
73
+ def preprocess_data(df):
74
+ df = df.dropna()
75
+ scaler = StandardScaler()
76
+ scaled_data = scaler.fit_transform(df[['open', 'high', 'low', 'close', 'volume']])
77
+ return scaled_data, scaler
78
+
79
+ def create_dataset(data, time_step=60):
80
+ X, Y = [], []
81
+ for i in range(len(data) - time_step - 1):
82
+ a = data[i:(i + time_step), :]
83
+ X.append(a)
84
+ Y.append(data[i + time_step, 3]) # Assuming 'close' price is the target
85
+ return np.array(X), np.array(Y)
86
+
87
+ def build_model(input_shape):
88
+ model = Sequential()
89
+ model.add(LSTM(50, return_sequences=True, input_shape=input_shape))
90
+ model.add(LSTM(50, return_sequences=False))
91
+ model.add(Dropout(0.2))
92
+ model.add(Dense(25))
93
+ model.add(Dense(1))
94
+ model.compile(optimizer='adam', loss='mean_squared_error')
95
+ return model
96
+
97
+ def train_model(df):
98
+ data, scaler = preprocess_data(df)
99
+ X, Y = create_dataset(data)
100
+ X_train, Y_train = X[:int(len(X) * 0.8)], Y[:int(len(Y) * 0.8)]
101
+ X_val, Y_val = X[int(len(X) * 0.8):], Y[int(len(Y) * 0.8):]
102
+ model = build_model((X_train.shape[1], X_train.shape[2]))
103
+ model.fit(X_train, Y_train, validation_data=(X_val, Y_val), epochs=20, batch_size=32)
104
+ return model, scaler
105
+
106
+ def generate_signal(pair):
107
+ df = get_combined_data(pair)
108
+ model, scaler = train_model(df)
109
+ recent_data = df.tail(60).drop(columns=['timestamp'])
110
+ scaled_recent_data = scaler.transform(recent_data)
111
+ prediction = model.predict(np.expand_dims(scaled_recent_data, axis=0))
112
+ last_close = df['close'].iloc[-1]
113
+ if prediction > last_close:
114
+ return "Buy"
115
+ else:
116
+ return "Sell"
117
+
118
+ def start(update, context):
119
+ context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a trading bot, how can I help you today?")
120
+
121
+ def signal(update, context):
122
+ pair = context.args[0] if context.args else 'BTCUSDT'
123
+ try:
124
+ trade_signal = generate_signal(pair)
125
+ context.bot.send_message(chat_id=update.effective_chat.id, text=f"Trade Signal for {pair}: {trade_signal}")
126
+ except Exception as e:
127
+ context.bot.send_message(chat_id=update.effective_chat.id, text=f"Error: {e}")
128
+
129
+ def main():
130
+ updater = Updater(token=TELEGRAM_BOT_API_KEY, use_context=True)
131
+ dispatcher = updater.dispatcher
132
+
133
+ start_handler = CommandHandler('start', start)
134
+ signal_handler = CommandHandler('signal', signal)
135
+
136
+ dispatcher.add_handler(start_handler)
137
+ dispatcher.add_handler(signal_handler)
138
+
139
+ updater.start_polling()
140
+
141
+ if __name__ == '__main__':
142
+ main()