bot_dl / untitled2.py
tg1138's picture
Upload untitled2.py
873b82e
# -*- coding: utf-8 -*-
"""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
# Initialize Alpaca API for cryptocurrency trading
api_key_crypto = 'PKBPQOK8HUFC98FPHFYA'
api_secret_crypto = 'hDesl4V2vc72c7zceUcyrE5Y5gyundwzPrEJZghu'
base_url_crypto = 'https://paper-api.alpaca.markets' # Use the paper trading environment for testing
alpaca_api_crypto = tradeapi.REST(api_key_crypto, api_secret_crypto, base_url_crypto, api_version='v2')
# Initialize the CCXT exchange object for cryptocurrency data
exchange = ccxt.coinbasepro()
# Configuration for cryptocurrency data
symbol_crypto = 'BTC/USD' # Replace with the cryptocurrency pair you want to analyze
timeframe_crypto = '1m' # 1-hour timeframe for cryptocurrency data
sequence_length_crypto = 30
refresh_interval_seconds_crypto = 60 # 1-hour refresh interval
max_iterations_crypto = 1000 # Set a limit to the number of iterations
# Configuration for cryptocurrency trading
initial_cash_crypto = 10 # Initial cash balance for cryptocurrency trading
crypto_buy_threshold = 0.02 # Buy threshold for cryptocurrency trading (2% increase)
crypto_sell_threshold = -0.02 # Sell threshold for cryptocurrency trading (2% decrease)
# Initialize portfolio for cryptocurrency trading
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:
# Fetch historical cryptocurrency price data using CCXT
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)
# Prepare data for prediction
prices = data['Close'].values.reshape(-1, 1)
scaler = MinMaxScaler()
prices_scaled = scaler.fit_transform(prices)
# Split data into training and testing sets
train_size = int(len(prices_scaled) * 0.8)
train_data = prices_scaled[:train_size]
test_data = prices_scaled[train_size:]
# Create sequences for training
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)
# Build and train the model (as previously shown)
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)
# Prepare test data for evaluation
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)
# Make predictions on the test data
predictions = model.predict([X_test, X_test])
# Inverse transform the predictions to the original scale
predictions = scaler.inverse_transform(predictions)
# Get the most recent data point for prediction
last_data_point = prices_scaled[-sequence_length:]
last_data_point = np.array([last_data_point])
# Print the current time period's data
print(f'Crypto Close Price: {data["Close"].iloc[-1]:.2f} USD')
# Print the forecasted cryptocurrency price for the next period and its time
print(f'Forecasted Crypto Price for the Next Period: ${predictions[-1][0]:.2f}')
# Calculate the Mean Absolute Error (MAE) between predictions and actual close prices
mae = mean_absolute_error(y_test, predictions)
print(f"Mean Absolute Error (MAE): {mae:.2f}")
# Handle cryptocurrency trading
handle_crypto_trading(data['Close'].iloc[-1], predictions[-1][0])
# Print portfolio status (combined portfolio)
portfolio_value_crypto = portfolio_crypto['cash'] + (portfolio_crypto['crypto_balance'] * data['Close'].iloc[-1])
print(f"Portfolio Value: Crypto: ${portfolio_value_crypto:.2f}")
# Sleep for the specified interval
time.sleep(refresh_interval_seconds_crypto)
# Increment the iterations counter
iterations += 1
except Exception as e:
print(f"An error occurred in cryptocurrency prediction: {str(e)}")
# Handle errors gracefully, e.g., retry or log the error
time.sleep(refresh_interval_seconds_crypto) # Sleep before retrying
def handle_crypto_trading(current_price, forecasted_price):
global portfolio_crypto
global position_crypto
print(forecasted_price - current_price)
# Buy signal (if the forecasted price increase exceeds the threshold)
if (forecasted_price - current_price) / current_price >= crypto_buy_threshold:
# Calculate the quantity to buy based on available cash
buy_quantity = portfolio_crypto['cash'] / current_price
if buy_quantity > 0:
# Execute the buy order
# Adjust portfolio and position variables accordingly
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], # Extract the base asset from the symbol
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
# Sell signal (if the forecasted price decrease exceeds the threshold)
elif (forecasted_price - current_price) / current_price <= crypto_sell_threshold:
# Ensure there's a position to sell
if position_crypto is not None:
# Calculate the quantity to sell based on the crypto balance
sell_quantity = portfolio_crypto['crypto_balance']
if sell_quantity > 0:
# Execute the sell order
# Adjust portfolio and position variables accordingly
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]) # Close the position
position_crypto = None
portfolio_crypto['cash'] += sell_quantity * current_price
portfolio_crypto['crypto_balance'] -= sell_quantity
# Define the main function to start cryptocurrency trading
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) # Sleep before retrying
if __name__ == "__main__":
main()