Ecco un esempio di codice Python per un modello di trading basato su LSTM (Long Short-Term Memory) per Google (GOOGL). Questo è un modello dimostrativo che richiede ulteriori ottimizzazioni per l'uso reale.
import yfinance as yf
import pandas as pd
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
# 1. Data Collection
data = yf.download('GOOGL', start='2010-01-01', end='2023-12-31')
# 2. Feature Engineering
data['MA50'] = data['Close'].rolling(window=50).mean()
data['MA200'] = data['Close'].rolling(window=200).mean()
def calculate_rsi(data, window=14):
delta = data.diff()
gain = delta.where(delta > 0, 0)
loss = -delta.where(delta < 0, 0)
avg_gain = gain.rolling(window=window).mean()
avg_loss = loss.rolling(window=window).mean()
rs = avg_gain / avg_loss
return 100 - (100 / (1 + rs))
data['RSI'] = calculate_rsi(data['Close'])
data['Volatility'] = data['Close'].rolling(window=20).std()
data.dropna(inplace=True)
# 3. Target Variable (1 if price increases next day)
data['Target'] = (data['Close'].shift(-1) > data['Close']).astype(int)
# 4. Data Preparation
features = ['Close', 'Volume', 'MA50', 'MA200', 'RSI', 'Volatility']
X = data[features].values
y = data['Target'].values
scaler = MinMaxScaler()
X_scaled = scaler.fit_transform(X)
def create_sequences(X, y, time_steps=60):
Xs, ys = [], []
for i in range(len(X) - time_steps):
Xs.append(X[i:(i + time_steps)])
ys.append(y[i + time_steps])
return np.array(Xs), np.array(ys)
time_steps = 60
X_seq, y_seq = create_sequences(X_scaled, y, time_steps)
# 5. Train/Test Split
split = int(0.8 * len(X_seq))
X_train, X_test = X_seq[:split], X_seq[split:]
y_train, y_test = y_seq[:split], y_seq[split:]
# 6. Model Architecture
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(time_steps, X_train.shape[2])))
model.add(Dropout(0.2))
model.add(LSTM(50, return_sequences=False))
model.add(Dropout(0.2))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# 7. Training
model.fit(X_train, y_train, epochs=50, batch_size=32, validation_split=0.1)
# 8. Predictions
predictions = model.predict(X_test)
predicted_classes = (predictions > 0.5).astype(int).flatten()
# 9. Backtesting
test_dates = data.index[time_steps + split:]
portfolio_value = 10000 # Starting capital
portfolio_history = []
current_position = False
entry_price = 0
for i in range(len(test_dates)):
current_date = test_dates[i]
current_price = data.loc[current_date, 'Close']
if i < len(predicted_classes):
prediction = predicted_classes[i]
# Trading logic
if prediction == 1 and not current_position:
# Buy signal
current_position = True
entry_price = current_price
elif prediction == 0 and current_position:
# Sell signal
portfolio_value *= (current_price / entry_price)
current_position = False
# Update portfolio value
if current_position:
portfolio_history.append(portfolio_value * (current_price / entry_price))
else:
portfolio_history.append(portfolio_value)
# 10. Performance Plot
plt.figure(figsize=(14,7))
plt.plot(test_dates, portfolio_history)
plt.title('Portfolio Value Over Time')
plt.xlabel('Date')
plt.ylabel('Portfolio Value ($)')
plt.show()
print(f"Final Portfolio Value: ${portfolio_history[-1]:.2f}")
Note importanti:
-
Questo è un modello dimostrativo e richiede:
- Ottimizzazione degli iperparametri
- Validazione su più mercati
- Gestione del rischio più sofisticata
- Considerazione dei costi di transazione
-
Componenti chiave per massimizzare i profitti:
- Feature engineering avanzato (sentiment analysis, correlazioni di mercato)
- Architetture ibride (CNN-LSTM)
- Reinforcement learning per l'ottimizzazione della strategia
- Gestione del rischio dinamica
-
Per l'uso reale è necessario:
- Collegamento a API di trading
- Monitoraggio in tempo reale
- Sistema di backtesting completo
- Gestione del rischio quantitativa
Vuoi che approfondisca qualche aspetto specifico del codice?