Python Machine Learning Predictions using an LSTM - Part 3
Let’s enhance your trading project further by incorporating machine learning predictions using an LSTM (Long Short-Term Memory) model, real-time visualizations using Dash, and live trading execution.
Step 1: Predicting Prices with LSTM
LSTM is excellent for time-series predictions like stock prices or cryptocurrency trends.
1. Install Required Libraries
pip install numpy pandas matplotlib tensorflow scikit-learn
2. Prepare Historical Data
Fetch data from Alpaca or Binance:
import pandas as pd
from binance.client import Client
# Binance API keys
BINANCE_API_KEY = 'your_binance_api_key'
BINANCE_SECRET_KEY = 'your_binance_secret_key'
client = Client(BINANCE_API_KEY, BINANCE_SECRET_KEY)
def fetch_data(symbol='BTCUSDT', interval=Client.KLINE_INTERVAL_1HOUR, lookback='30 days ago UTC'):
klines = client.get_historical_klines(symbol, interval, lookback)
df = pd.DataFrame(klines, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume', ..., 'ignore'])
df['close'] = pd.to_numeric(df['close'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
return df[['timestamp', 'close']]
data = fetch_data()
data.set_index('timestamp', inplace=True)
3. Build and Train the LSTM Model
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
# Normalize data
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data['close'].values.reshape(-1, 1))
# Create training sequences
def create_sequences(data, seq_len=50):
sequences = []
for i in range(len(data) - seq_len):
seq = data[i:i + seq_len]
label = data[i + seq_len]
sequences.append((seq, label))
return sequences
seq_len = 50
sequences = create_sequences(scaled_data, seq_len)
X, y = zip(*sequences)
X, y = np.array(X), np.array(y)
# Split data
train_size = int(0.8 * len(X))
X_train, X_test = X[:train_size], X[train_size:]
y_train, y_test = y[:train_size], y[train_size:]
# Build LSTM model
model = Sequential([
LSTM(50, return_sequences=True, input_shape=(seq_len, 1)),
LSTM(50),
Dense(1)
])
model.compile(optimizer='adam', loss='mean_squared_error')
# Train model
model.fit(X_train, y_train, epochs=10, batch_size=32)
4. Make Predictions
predictions = model.predict(X_test)
predictions = scaler.inverse_transform(predictions)
import matplotlib.pyplot as plt
plt.plot(data.index[-len(y_test):], scaler.inverse_transform(y_test.reshape(-1, 1)), label='Actual')
plt.plot(data.index[-len(predictions):], predictions, label='Predicted')
plt.legend()
plt.show()
Step 2: Real-Time Visualizations with Dash
Dash provides interactive, real-time dashboards.
1. Install Dash
pip install dash
2. Create Dash App
from dash import Dash, dcc, html
import plotly.graph_objs as go
app = Dash(__name__)
app.layout = html.Div([
html.H1('Trading Dashboard'),
dcc.Graph(id='price-chart'),
dcc.Interval(id='update-interval', interval=60000, n_intervals=0) # Update every minute
])
@app.callback(
dash.dependencies.Output('price-chart', 'figure'),
[dash.dependencies.Input('update-interval', 'n_intervals')]
)
def update_chart(n_intervals):
live_data = fetch_data(lookback='1 day') # Get live data
return {
'data': [
go.Scatter(x=live_data.index, y=live_data['close'], mode='lines', name='Price')
],
'layout': go.Layout(title='Live Price', xaxis={'title': 'Time'}, yaxis={'title': 'Price'})
}
if __name__ == '__main__':
app.run_server(debug=True)
Run the app, and open the browser at http://127.0.0.1:8050/.
Step 3: Execute Live Trades
1. Integrate Predictions with Trades
Use your trained LSTM model to decide when to buy or sell:
latest_seq = scaled_data[-seq_len:].reshape(1, seq_len, 1)
predicted_price = scaler.inverse_transform(model.predict(latest_seq))[0, 0]
current_price = data['close'].iloc[-1]
if predicted_price > current_price * 1.02: # Buy if predicted price is 2% higher
api.submit_order(symbol='BTCUSD', qty=0.01, side='buy', type='market')
elif predicted_price < current_price * 0.98: # Sell if predicted price is 2% lower
api.submit_order(symbol='BTCUSD', qty=0.01, side='sell', type='market')
Step 4: Deploy the Complete Solution
Backend: Use Flask/Dash for analytics and execution.
Frontend: Combine Dash with React for a polished UI.
Cloud Hosting: Deploy on AWS, Heroku, or GCP with secure API key storage.
Comments
Post a Comment