| |
| """Untitled2.ipynb |
| |
| Automatically generated by Colaboratory. |
| |
| Original file is located at |
| https://colab.research.google.com/drive/1AD0k2uVsW9mIm-3IOBCrDQ8iDI4PCKCf |
| """ |
|
|
| pip install alpaca-trade-api |
|
|
| pip install ccxt |
|
|
| import numpy as np |
| import pandas as pd |
| import matplotlib.pyplot as plt |
| from sklearn.preprocessing import MinMaxScaler |
| from tensorflow.keras.models import Sequential, Model |
| from tensorflow.keras.layers import LSTM, Dense, Dropout, Conv1D, MaxPooling1D, Flatten, Input, concatenate |
| import ccxt |
| from sklearn.metrics import mean_absolute_error |
| import alpaca_trade_api as tradeapi |
| import time |
|
|
| |
| api_key_crypto = 'PKBPQOK8HUFC98FPHFYA' |
| api_secret_crypto = 'hDesl4V2vc72c7zceUcyrE5Y5gyundwzPrEJZghu' |
| base_url_crypto = 'https://paper-api.alpaca.markets' |
| alpaca_api_crypto = tradeapi.REST(api_key_crypto, api_secret_crypto, base_url_crypto, api_version='v2') |
|
|
| |
| exchange = ccxt.coinbasepro() |
|
|
| |
| symbol_crypto = 'BTC/USD' |
| timeframe_crypto = '1m' |
| sequence_length_crypto = 30 |
| refresh_interval_seconds_crypto = 60 |
| max_iterations_crypto = 1000 |
|
|
| |
| initial_cash_crypto = 10 |
| crypto_buy_threshold = 0.02 |
| crypto_sell_threshold = -0.02 |
|
|
| |
| portfolio_crypto = {'cash': initial_cash_crypto, 'crypto_balance': 0} |
| position_crypto = None |
|
|
| def get_crypto_data(symbol, timeframe, sequence_length, max_iterations): |
| iterations = 0 |
| while iterations < max_iterations: |
| try: |
| |
| ohlcv = exchange.fetch_ohlcv(symbol, timeframe) |
| data = pd.DataFrame(ohlcv, columns=['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume']) |
| data['Timestamp'] = pd.to_datetime(data['Timestamp'], unit='ms') |
| data.set_index('Timestamp', inplace=True) |
|
|
| |
| prices = data['Close'].values.reshape(-1, 1) |
| scaler = MinMaxScaler() |
| prices_scaled = scaler.fit_transform(prices) |
|
|
| |
| train_size = int(len(prices_scaled) * 0.8) |
| train_data = prices_scaled[:train_size] |
| test_data = prices_scaled[train_size:] |
|
|
| |
| X_train, y_train = [], [] |
| for i in range(len(train_data) - sequence_length): |
| X_train.append(train_data[i:i+sequence_length]) |
| y_train.append(train_data[i+sequence_length]) |
|
|
| X_train, y_train = np.array(X_train), np.array(y_train) |
|
|
| |
| lstm_model = Sequential() |
| lstm_model.add(LSTM(50, activation='relu', input_shape=(sequence_length, 1))) |
| lstm_model.add(Dense(1)) |
|
|
| cnn_input = Input(shape=(sequence_length, 1)) |
| cnn_layer = Conv1D(filters=64, kernel_size=3, activation='relu')(cnn_input) |
| cnn_layer = MaxPooling1D(pool_size=2)(cnn_layer) |
| cnn_layer = Flatten()(cnn_layer) |
| cnn_output = Dense(1)(cnn_layer) |
|
|
| combined_model = concatenate([lstm_model.output, cnn_output]) |
| output_layer = Dense(1)(combined_model) |
|
|
| model = Model(inputs=[lstm_model.input, cnn_input], outputs=output_layer) |
| model.compile(optimizer='adam', loss='mean_squared_error') |
| model.fit([X_train, X_train], y_train, epochs=10, batch_size=64) |
|
|
| |
| X_test, y_test = [], [] |
| for i in range(len(test_data) - sequence_length): |
| X_test.append(test_data[i:i+sequence_length]) |
| y_test.append(test_data[i+sequence_length]) |
|
|
| X_test, y_test = np.array(X_test), np.array(y_test) |
|
|
| |
| predictions = model.predict([X_test, X_test]) |
|
|
| |
| predictions = scaler.inverse_transform(predictions) |
|
|
| |
| last_data_point = prices_scaled[-sequence_length:] |
| last_data_point = np.array([last_data_point]) |
|
|
| |
| print(f'Crypto Close Price: {data["Close"].iloc[-1]:.2f} USD') |
|
|
| |
| print(f'Forecasted Crypto Price for the Next Period: ${predictions[-1][0]:.2f}') |
|
|
| |
| mae = mean_absolute_error(y_test, predictions) |
| print(f"Mean Absolute Error (MAE): {mae:.2f}") |
|
|
| |
| handle_crypto_trading(data['Close'].iloc[-1], predictions[-1][0]) |
|
|
| |
| portfolio_value_crypto = portfolio_crypto['cash'] + (portfolio_crypto['crypto_balance'] * data['Close'].iloc[-1]) |
| print(f"Portfolio Value: Crypto: ${portfolio_value_crypto:.2f}") |
|
|
| |
| time.sleep(refresh_interval_seconds_crypto) |
|
|
| |
| iterations += 1 |
|
|
| except Exception as e: |
| print(f"An error occurred in cryptocurrency prediction: {str(e)}") |
| |
| time.sleep(refresh_interval_seconds_crypto) |
|
|
| def handle_crypto_trading(current_price, forecasted_price): |
| global portfolio_crypto |
| global position_crypto |
| print(forecasted_price - current_price) |
| |
| if (forecasted_price - current_price) / current_price >= crypto_buy_threshold: |
|
|
| |
| buy_quantity = portfolio_crypto['cash'] / current_price |
| if buy_quantity > 0: |
| |
| |
| print(f"Buy signal - Bought {buy_quantity:.6f} BTC at ${current_price:.2f}") |
| position_crypto = alpaca_api_crypto.submit_order( |
| symbol=symbol_crypto.split('/')[0]+symbol_crypto.split('/')[1], |
| qty=buy_quantity, |
| side='buy', |
| type='limit', |
| time_in_force='gtc', |
| limit_price=current_price |
| ) |
| portfolio_crypto['cash'] -= buy_quantity * current_price |
| portfolio_crypto['crypto_balance'] += buy_quantity |
|
|
| |
| elif (forecasted_price - current_price) / current_price <= crypto_sell_threshold: |
| |
| if position_crypto is not None: |
| |
| sell_quantity = portfolio_crypto['crypto_balance'] |
| if sell_quantity > 0: |
| |
| |
| print(f"Sell signal - Sold {sell_quantity:.6f} BTC at ${current_price:.2f}") |
| alpaca_api_crypto.cancel_order(position_crypto.id) |
| alpaca_api_crypto.close_position(symbol=symbol_crypto.split('/')[0]+symbol_crypto.split('/')[1]) |
| position_crypto = None |
| portfolio_crypto['cash'] += sell_quantity * current_price |
| portfolio_crypto['crypto_balance'] -= sell_quantity |
|
|
| |
| def main(): |
| while True: |
| try: |
| get_crypto_data(symbol_crypto, timeframe_crypto, sequence_length_crypto, max_iterations_crypto) |
| except Exception as e: |
| print(f"An error occurred in cryptocurrency trading: {str(e)}") |
| time.sleep(refresh_interval_seconds_crypto) |
|
|
| if __name__ == "__main__": |
| main() |