tg1138 commited on
Commit
873b82e
·
1 Parent(s): 23c29d0

Upload untitled2.py

Browse files
Files changed (1) hide show
  1. untitled2.py +192 -0
untitled2.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Untitled2.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1AD0k2uVsW9mIm-3IOBCrDQ8iDI4PCKCf
8
+ """
9
+
10
+ pip install alpaca-trade-api
11
+
12
+ pip install ccxt
13
+
14
+ import numpy as np
15
+ import pandas as pd
16
+ import matplotlib.pyplot as plt
17
+ from sklearn.preprocessing import MinMaxScaler
18
+ from tensorflow.keras.models import Sequential, Model
19
+ from tensorflow.keras.layers import LSTM, Dense, Dropout, Conv1D, MaxPooling1D, Flatten, Input, concatenate
20
+ import ccxt
21
+ from sklearn.metrics import mean_absolute_error
22
+ import alpaca_trade_api as tradeapi
23
+ import time
24
+
25
+ # Initialize Alpaca API for cryptocurrency trading
26
+ api_key_crypto = 'PKBPQOK8HUFC98FPHFYA'
27
+ api_secret_crypto = 'hDesl4V2vc72c7zceUcyrE5Y5gyundwzPrEJZghu'
28
+ base_url_crypto = 'https://paper-api.alpaca.markets' # Use the paper trading environment for testing
29
+ alpaca_api_crypto = tradeapi.REST(api_key_crypto, api_secret_crypto, base_url_crypto, api_version='v2')
30
+
31
+ # Initialize the CCXT exchange object for cryptocurrency data
32
+ exchange = ccxt.coinbasepro()
33
+
34
+ # Configuration for cryptocurrency data
35
+ symbol_crypto = 'BTC/USD' # Replace with the cryptocurrency pair you want to analyze
36
+ timeframe_crypto = '1m' # 1-hour timeframe for cryptocurrency data
37
+ sequence_length_crypto = 30
38
+ refresh_interval_seconds_crypto = 60 # 1-hour refresh interval
39
+ max_iterations_crypto = 1000 # Set a limit to the number of iterations
40
+
41
+ # Configuration for cryptocurrency trading
42
+ initial_cash_crypto = 10 # Initial cash balance for cryptocurrency trading
43
+ crypto_buy_threshold = 0.02 # Buy threshold for cryptocurrency trading (2% increase)
44
+ crypto_sell_threshold = -0.02 # Sell threshold for cryptocurrency trading (2% decrease)
45
+
46
+ # Initialize portfolio for cryptocurrency trading
47
+ portfolio_crypto = {'cash': initial_cash_crypto, 'crypto_balance': 0}
48
+ position_crypto = None
49
+
50
+ def get_crypto_data(symbol, timeframe, sequence_length, max_iterations):
51
+ iterations = 0
52
+ while iterations < max_iterations:
53
+ try:
54
+ # Fetch historical cryptocurrency price data using CCXT
55
+ ohlcv = exchange.fetch_ohlcv(symbol, timeframe)
56
+ data = pd.DataFrame(ohlcv, columns=['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume'])
57
+ data['Timestamp'] = pd.to_datetime(data['Timestamp'], unit='ms')
58
+ data.set_index('Timestamp', inplace=True)
59
+
60
+ # Prepare data for prediction
61
+ prices = data['Close'].values.reshape(-1, 1)
62
+ scaler = MinMaxScaler()
63
+ prices_scaled = scaler.fit_transform(prices)
64
+
65
+ # Split data into training and testing sets
66
+ train_size = int(len(prices_scaled) * 0.8)
67
+ train_data = prices_scaled[:train_size]
68
+ test_data = prices_scaled[train_size:]
69
+
70
+ # Create sequences for training
71
+ X_train, y_train = [], []
72
+ for i in range(len(train_data) - sequence_length):
73
+ X_train.append(train_data[i:i+sequence_length])
74
+ y_train.append(train_data[i+sequence_length])
75
+
76
+ X_train, y_train = np.array(X_train), np.array(y_train)
77
+
78
+ # Build and train the model (as previously shown)
79
+ lstm_model = Sequential()
80
+ lstm_model.add(LSTM(50, activation='relu', input_shape=(sequence_length, 1)))
81
+ lstm_model.add(Dense(1))
82
+
83
+ cnn_input = Input(shape=(sequence_length, 1))
84
+ cnn_layer = Conv1D(filters=64, kernel_size=3, activation='relu')(cnn_input)
85
+ cnn_layer = MaxPooling1D(pool_size=2)(cnn_layer)
86
+ cnn_layer = Flatten()(cnn_layer)
87
+ cnn_output = Dense(1)(cnn_layer)
88
+
89
+ combined_model = concatenate([lstm_model.output, cnn_output])
90
+ output_layer = Dense(1)(combined_model)
91
+
92
+ model = Model(inputs=[lstm_model.input, cnn_input], outputs=output_layer)
93
+ model.compile(optimizer='adam', loss='mean_squared_error')
94
+ model.fit([X_train, X_train], y_train, epochs=10, batch_size=64)
95
+
96
+ # Prepare test data for evaluation
97
+ X_test, y_test = [], []
98
+ for i in range(len(test_data) - sequence_length):
99
+ X_test.append(test_data[i:i+sequence_length])
100
+ y_test.append(test_data[i+sequence_length])
101
+
102
+ X_test, y_test = np.array(X_test), np.array(y_test)
103
+
104
+ # Make predictions on the test data
105
+ predictions = model.predict([X_test, X_test])
106
+
107
+ # Inverse transform the predictions to the original scale
108
+ predictions = scaler.inverse_transform(predictions)
109
+
110
+ # Get the most recent data point for prediction
111
+ last_data_point = prices_scaled[-sequence_length:]
112
+ last_data_point = np.array([last_data_point])
113
+
114
+ # Print the current time period's data
115
+ print(f'Crypto Close Price: {data["Close"].iloc[-1]:.2f} USD')
116
+
117
+ # Print the forecasted cryptocurrency price for the next period and its time
118
+ print(f'Forecasted Crypto Price for the Next Period: ${predictions[-1][0]:.2f}')
119
+
120
+ # Calculate the Mean Absolute Error (MAE) between predictions and actual close prices
121
+ mae = mean_absolute_error(y_test, predictions)
122
+ print(f"Mean Absolute Error (MAE): {mae:.2f}")
123
+
124
+ # Handle cryptocurrency trading
125
+ handle_crypto_trading(data['Close'].iloc[-1], predictions[-1][0])
126
+
127
+ # Print portfolio status (combined portfolio)
128
+ portfolio_value_crypto = portfolio_crypto['cash'] + (portfolio_crypto['crypto_balance'] * data['Close'].iloc[-1])
129
+ print(f"Portfolio Value: Crypto: ${portfolio_value_crypto:.2f}")
130
+
131
+ # Sleep for the specified interval
132
+ time.sleep(refresh_interval_seconds_crypto)
133
+
134
+ # Increment the iterations counter
135
+ iterations += 1
136
+
137
+ except Exception as e:
138
+ print(f"An error occurred in cryptocurrency prediction: {str(e)}")
139
+ # Handle errors gracefully, e.g., retry or log the error
140
+ time.sleep(refresh_interval_seconds_crypto) # Sleep before retrying
141
+
142
+ def handle_crypto_trading(current_price, forecasted_price):
143
+ global portfolio_crypto
144
+ global position_crypto
145
+ print(forecasted_price - current_price)
146
+ # Buy signal (if the forecasted price increase exceeds the threshold)
147
+ if (forecasted_price - current_price) / current_price >= crypto_buy_threshold:
148
+
149
+ # Calculate the quantity to buy based on available cash
150
+ buy_quantity = portfolio_crypto['cash'] / current_price
151
+ if buy_quantity > 0:
152
+ # Execute the buy order
153
+ # Adjust portfolio and position variables accordingly
154
+ print(f"Buy signal - Bought {buy_quantity:.6f} BTC at ${current_price:.2f}")
155
+ position_crypto = alpaca_api_crypto.submit_order(
156
+ symbol=symbol_crypto.split('/')[0]+symbol_crypto.split('/')[1], # Extract the base asset from the symbol
157
+ qty=buy_quantity,
158
+ side='buy',
159
+ type='limit',
160
+ time_in_force='gtc',
161
+ limit_price=current_price
162
+ )
163
+ portfolio_crypto['cash'] -= buy_quantity * current_price
164
+ portfolio_crypto['crypto_balance'] += buy_quantity
165
+
166
+ # Sell signal (if the forecasted price decrease exceeds the threshold)
167
+ elif (forecasted_price - current_price) / current_price <= crypto_sell_threshold:
168
+ # Ensure there's a position to sell
169
+ if position_crypto is not None:
170
+ # Calculate the quantity to sell based on the crypto balance
171
+ sell_quantity = portfolio_crypto['crypto_balance']
172
+ if sell_quantity > 0:
173
+ # Execute the sell order
174
+ # Adjust portfolio and position variables accordingly
175
+ print(f"Sell signal - Sold {sell_quantity:.6f} BTC at ${current_price:.2f}")
176
+ alpaca_api_crypto.cancel_order(position_crypto.id)
177
+ alpaca_api_crypto.close_position(symbol=symbol_crypto.split('/')[0]+symbol_crypto.split('/')[1]) # Close the position
178
+ position_crypto = None
179
+ portfolio_crypto['cash'] += sell_quantity * current_price
180
+ portfolio_crypto['crypto_balance'] -= sell_quantity
181
+
182
+ # Define the main function to start cryptocurrency trading
183
+ def main():
184
+ while True:
185
+ try:
186
+ get_crypto_data(symbol_crypto, timeframe_crypto, sequence_length_crypto, max_iterations_crypto)
187
+ except Exception as e:
188
+ print(f"An error occurred in cryptocurrency trading: {str(e)}")
189
+ time.sleep(refresh_interval_seconds_crypto) # Sleep before retrying
190
+
191
+ if __name__ == "__main__":
192
+ main()