import yfinance as yf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.signal import find_peaks
from sklearn.preprocessing import MinMaxScaler
import talib
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
from tensorflow.keras.utils import to_categorical
import warnings
warnings.filterwarnings('ignore')
--------------------------------------------
Fetch Data with Adjustable Timeframe
--------------------------------------------
def fetch_price_data(symbol, interval, start_date, end_date):
"""Fetch cryptocurrency price data from Yahoo Finance."""
data = yf.download(symbol, interval=interval, start=start_date, end=end_date)
data = data[['Close', 'High', 'Low', 'Open', 'Volume']].dropna() # Ensure no missing data
return data
def calculate_fibonacci_levels(data, start_idx, end_idx):
"""Calculate Fibonacci retracement and extension levels."""
high = data['Close'][start_idx]
low = data['Close'][end_idx]
code
retracements = {f"{level*100:.1f}%": high - (high - low) * level for level in [0.236, 0.382, 0.5, 0.618, 0.786]}
extensions = {f"{level*100:.1f}%": high + (high - low) * level for level in [1.618, 2.618, 4.236]}
return retracements, extensions
Assistant
User
would you add anything else to perfect the code?
Assistant
User
please show me the complete code with your improvements
Assistant
--------------------------------------------
Prepare LSTM Dataset
--------------------------------------------
def create_lstm_dataset(data, feature_columns, target_column, window_size=60):
"""Prepare dataset for LSTM training."""
X, y = [], []
for i in range(window_size, len(data)):
X.append(data[i-window_size:i, feature_columns])
y.append(data[i, target_column]) # Predict Close Price
return np.array(X), np.array(y)
--------------------------------------------
Build and Train the LSTM Model
--------------------------------------------
def train_lstm_model(symbol, interval, start_date, end_date):
"""Train the LSTM model to predict price movement."""
# Fetch data
data = fetch_price_data(symbol, interval, start_date, end_date)
data = calculate_technical_indicators(data)
code
# Drop NaN values (caused by technical indicators)
data = data.dropna()
# Normalize data
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)
# Prepare LSTM dataset (multivariate inputs)
target_column = list(data.columns).index('Close')
feature_columns = list(range(data.shape[1])) # All features
X, y = create_lstm_dataset(scaled_data, feature_columns, target_column)
# Reshape for LSTM input
X = np.reshape(X, (X.shape[0], X.shape[1], len(feature_columns)))
# LSTM model
model = Sequential([
LSTM(units=50, return_sequences=True, input_shape=(X.shape[1], X.shape[2])),
LSTM(units=50, return_sequences=False),
Dropout(0.2),
Dense(units=1) # Output: Predicted Close Price
])
model.compile(optimizer='adam', loss='mean_squared_error')
model.fit(X, y, epochs=10, batch_size=32)
return model, scaler, data, X, y
--------------------------------------------
Predict and Visualize Waves & Fibonacci Levels
--------------------------------------------
def predict_and_visualize(symbol, interval, start_date, end_date, model, scaler):
"""Make price predictions and overlay Elliott Wave labels and Fibonacci levels on the chart."""
# Fetch data
data = fetch_price_data(symbol, interval, start_date, end_date)
data = calculate_technical_indicators(data)
def main():
# Take inputs
symbol = input("Enter the symbol (e.g., 'BTC-USD' for Bitcoin or 'ETH-USD'): ")
interval = input("Enter the timeframe (e.g., '1h' for hourly, '1d' for daily, '1wk' for weekly): ")
start_date = input("Enter the start date (YYYY-MM-DD): ")
end_date = input("Enter the end date (YYYY-MM-DD): ")
code
# Train the model
model, scaler, data, X, y = train_lstm_model(symbol, interval, start_date, end_date)
# Predict and visualize
predict_and_visualize(symbol, interval, start_date, end_date, model, scaler)
Run the program
if name == "main":
main()
This script combines cryptocurrency price data analysis, Elliott wave patterns, Fibonacci levels, and LSTM-based price prediction. Below is an explanation of the design and functionality:
Script Overview:
Data Collection and Preprocessing:
The script fetches financial data for user-specified crypto symbols and intervals using yfinance.
It includes basic preprocessing (handling missing data) and adds technical indicators (RSI, MACD, Bollinger Bands) for better context during pattern and wave detection.
Fibonacci Levels Functionality:
Fibonacci retracement and extension levels are calculated based on recent price movements.
These levels help traders understand potential price reversal or breakout zones.
Peaks and troughs are labeled and plotted for visual interpretation.
LSTM-Based Price Prediction:
A deep learning LSTM model is built to predict the future price of the cryptocurrency based on historical data.
The target variable is the 'Close' price. Features include technical indicators (RSI, MACD, etc.).
MinMaxScaler normalizes data, ensuring stable training for the LSTM.
Visualization:
The prediction results, Elliott wave labels, and Fibonacci retracement levels are overlaid on the price chart for intuitive interpretation.
Peaks (green) and troughs (orange) are shown for visualizing impulse and correction waves, while predicted prices are shown with dashed red lines.
User Interaction:
The script defines a main() function prompting the user to enter a symbol (e.g., BTC-USD), a timeframe (1h, 1d, etc.), and a data range. This allows flexible usage for different cryptocurrencies and granularity levels.
Run the script:
Simply execute the script in your Python environment to start the program.
Example Input:
Symbol: BTC-USD (for Bitcoin data)
Timeframe: 1d (daily data)
Start Date: 2022-01-01
End Date: 2022-12-31
Output:
A dynamic chart illustrating:
The actual and predicted prices of the selected cryptocurrency.
Elliott wave peaks (green dots) and troughs (orange dots).
Fibonacci retracement lines and extension levels for potential price targets.
Notes to Consider:
1. Tuning LSTM:
The model uses basic hyperparameters (units=50, epochs=10, batch_size=32) for simplicity. You may extend the training duration or tune these values for improved performance.
2. Data Smoothing:
The find_peaks function in classify_elliott_wave uses a distance=5 argument that defines the minimum separation between peaks. This may need adjustment based on volatility and the chosen interval.
3. Potential Errors:
Preprocessing steps like NaN handling and defining start/end indices in Fibonacci calculations may require adjustments if applied to very small datasets.
TensorFlow warnings may appear but typically do not block training.
4. Model Retraining:
Every time you run the script, the LSTM model is re-trained from scratch. For a production-ready setup, the model should be saved to disk after training to reuse it (model.save() and load_model() methods).
5. Library Compatibility:
Ensure TA-Lib is properly installed since it is a dependency for computing technical indicators. Installation may require additional setup (e.g., compiling from source on some platforms).
This script serves as a full pipeline for exploring, analyzing, and making predictions on cryptocurrency data based on both traditional technical setups (e.g., Fibonacci, Elliott waves) and modern deep-learning techniques. It is extensible for incorporating additional indicators, predictive features, or alternative machine learning models.
While your code is already a well-designed starting point for cryptocurrency price prediction and wave detection, there are several improvements and enhancements that could further optimize it and make it more robust, functional, and efficient. Below, I'll suggest areas for improvement and additional features you could consider adding to "perfect" the code.
1. Avoid Overfitting: Model Regularization
Current Challenge: The LSTM model could overfit, given the small number of epochs and limited dropout.
Solution:
Add more Dropout layers with varying ratios to regularize the network.
Consider early stopping to avoid overfitting during training (stop training when validation loss stops improving).
Code Addition:
python
from tensorflow.keras.callbacks import EarlyStopping
# Add early stopping to prevent overfitting
early_stopping = EarlyStopping(monitor='loss', patience=5, restore_best_weights=True)
# When fitting the model:
model.fit(X, y, epochs=100, batch_size=32, callbacks=[early_stopping]) # Increase epochs but prevent overfitting
2. Optimize Hyperparameters
Use an automated approach like Grid Search or Bayesian Optimization to find the best hyperparameters for:
units: Number of LSTM neurons.
batch_size: Batch size during training.
learning_rate: Learning rate for the Adam optimizer.
Code Addition (if you want to automate this):
Integrate a library like Keras Tuner:
bash
pip install keras-tuner
python
from kerastuner import Hyperband
from tensorflow.keras.optimizers import Adam
def build_model(hp):
model = Sequential([
LSTM(units=hp.Int('units', min_value=32, max_value=128, step=32), return_sequences=True, input_shape=(X.shape[1], X.shape[2])),
LSTM(units=hp.Int('units', min_value=32, max_value=128, step=32), return_sequences=False),
Dropout(hp.Float('dropout', min_value=0.1, max_value=0.5, step=0.1)),
Dense(units=1) # Output layer
])
model.compile(optimizer=Adam(learning_rate=hp.Choice('learning_rate', [1e-3, 1e-4, 1e-5])), loss='mean_squared_error')
return model
tuner = Hyperband(build_model, max_epochs=50, objective='val_loss', directory='lstm_tuning')
tuner.search(X, y, epochs=50, validation_split=0.2)
This finds the optimal configuration for your LSTM.
3. Include Validation Set
Current Challenge: The current code trains the LSTM on all data without validation to assess generalization.
Solution: Split the data into training, validation, and test sets (e.g., 70/20/10) to validate the model’s performance.
Current Challenge: The LSTM uses all features (Close, RSI, MACD, Bollinger Bands, etc.) without analyzing which contribute most to prediction accuracy.
Solution: Perform Feature Selection to include only the most relevant features for the model. Use methods like correlation analysis or feature importance scores.
Example using Correlation (optional):
python
# Compute feature correlations with the target variable ('Close')
correlations = data.corr()['Close'].sort_values()
# Select top N features (by absolute correlation)
top_features = correlations.abs().sort_values(ascending=False).head(N).index.tolist()
5. Performance Metrics:
Current Challenge: The script only evaluates the model based on loss. It doesn't calculate other metrics like MAPE, RMSE, or MAE.
Solution: Add evaluation metrics for better error measurement and comparison.
Code Addition:
python
from sklearn.metrics import mean_squared_error, mean_absolute_error
# After prediction
actual_prices = scaler.inverse_transform(y) # Rescale y
rmse = np.sqrt(mean_squared_error(actual_prices, predicted_prices))
mae = mean_absolute_error(actual_prices, predicted_prices)
print(f"RMSE: {rmse}, MAE: {mae}")
6. Add Backtesting or Trading Simulation
Current Challenge: The model predicts, but there's no framework to evaluate how well the predictions perform in simulated trading.
Solution: Implement a basic backtesting framework to simulate buying/selling based on predicted prices.
Example:
python
initial_balance = 1000 # Initial cash in USD
balance = initial_balance
crypto_units = 0
for i in range(len(predicted_prices)):
if predicted_prices[i] > data['Close'][i]: # Buy signal
crypto_units = balance / data['Close'][i]
balance = 0
elif predicted_prices[i] < data['Close'][i]: # Sell signal
balance = crypto_units * data['Close'][i]
crypto_units = 0
portfolio_value = balance + (crypto_units * data['Close'][-1]) # Final portfolio value
print(f"Portfolio Value: ${portfolio_value:.2f}")
7. Add a Dashboard or Save Plots
Current Challenge: The script visualizes only one plot at runtime and doesn't save the data or graphs for later inspection.
Solution: Save plots and predictions for future analysis or use libraries like Plotly or Dash for interactive dashboards.
Code Addition:
python
# Save the plot
plt.savefig(f"{symbol}_{interval}_predictions.png")
For an interactive dashboard (e.g., in Plotly Dash):
bash
pip install dash
Then create an interactive web app to display charts and analytics.
8. Use Transfer Learning (Pretraining)
Current Challenge: The model is trained from scratch every time, even for new symbols or intervals.
Solution: Train the LSTM on a large dataset (e.g., multiple cryptocurrencies over years) and save the model weights. Use them later for finetuning.
9. Add Error Handling
Current Challenge: User inputs are not validated, and runtime errors (e.g., invalid symbol, no data) can disrupt the program.
Solution: Add try-except blocks and input validation.
python
def fetch_price_data(symbol, interval, start_date, end_date):
try:
data = yf.download(symbol, interval=interval, start=start_date, end=end_date)
if data.empty:
raise ValueError(f"No data found for symbol {symbol} with interval {interval}.")
return data[['Close', 'High', 'Low', 'Open', 'Volume']].dropna()
except Exception as e:
print(f"Error fetching data: {e}")
return None
10. Provide Additional Analysis
Add more financial context, such as:
Detection of support and resistance levels using price data.
Analysis of trading volumes to confirm wave patterns.
Integration of additional technical indicators like ATR (Average True Range) or ADX (Average Directional Index).
Summary
These enhancements can extend the code’s functionality and make the system more robust, scalable, and user-friendly. Here's a prioritized list of improvements:
Add validation and test sets.
Hyperparameter optimization for LSTM.
Better error handling for robustness.
Include backtesting for real-world applications.
Save or visualize prediction results interactively.
With these additions, the script would be significantly improved in terms of functionality and quality!
Below is the enhanced and complete version of your cryptocurrency price prediction and wave detection script, incorporating the suggested improvements. These updates make the code more robust, modular, and practical for real-world use.
Improved Code
python
import yfinance as yf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.signal import find_peaks
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error, mean_absolute_error
import talib
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
from tensorflow.keras.callbacks import EarlyStopping
import warnings
warnings.filterwarnings('ignore')
# --------------------------------------------
# Fetch and Process Data with Error Handling
# --------------------------------------------
def fetch_price_data(symbol, interval, start_date, end_date):
"""Fetch cryptocurrency price data from Yahoo Finance."""
try:
data = yf.download(symbol, interval=interval, start=start_date, end=end_date, progress=False)
if data.empty:
raise ValueError(f"No data found for {symbol} with interval {interval}.")
data = data[['Close', 'High', 'Low', 'Open', 'Volume']].dropna() # Ensure no missing data
return data
except Exception as e:
print(f"Error fetching data: {e}")
return None
# --------------------------------------------
# Add Technical Indicators
# --------------------------------------------
def calculate_technical_indicators(data):
"""Add RSI, MACD, Bollinger Bands to data."""
data['RSI'] = talib.RSI(data['Close'], timeperiod=14)
data['MACD'], data['MACD_signal'], _ = talib.MACD(data['Close'], fastperiod=12, slowperiod=26, signalperiod=9)
data['Upper_BB'], data['Middle_BB'], data['Lower_BB'] = talib.BBANDS(
data['Close'], timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)
return data
# --------------------------------------------
# Detect Elliott Waves (Peaks and Troughs)
# --------------------------------------------
def classify_elliott_wave(data):
"""Classify Elliott Waves using peaks and valleys."""
data['wave_label'] = 0
highs, _ = find_peaks(data['Close'], distance=5)
lows, _ = find_peaks(-data['Close'], distance=5)
# Add wave labels
data['wave_label'][highs] = 1 # Peaks: Waves 1, 3, 5
data['wave_label'][lows] = -1 # Troughs: Waves 2, 4, A/B/C corrections
return highs, lows, data
# --------------------------------------------
# Calculate Fibonacci Levels
# --------------------------------------------
def calculate_fibonacci_levels(data, start_idx, end_idx):
"""Calculate Fibonacci retracement and extension levels."""
high = data['Close'][start_idx]
low = data['Close'][end_idx]
retracements = {f"{level*100:.1f}%": high - (high - low) * level for level in [0.236, 0.382, 0.5, 0.618, 0.786]}
extensions = {f"{level*100:.1f}%": high + (high - low) * level for level in [1.618, 2.618, 4.236]}
return retracements, extensions
# --------------------------------------------
# Prepare LSTM Dataset
# --------------------------------------------
def create_lstm_dataset(data, feature_columns, target_column, window_size=60):
"""Prepare dataset for LSTM training."""
X, y = [], []
for i in range(window_size, len(data)):
X.append(data[i-window_size:i, feature_columns])
y.append(data[i, target_column]) # Predict Close Price
return np.array(X), np.array(y)
# --------------------------------------------
# Build LSTM Model
# --------------------------------------------
def build_lstm_model(input_shape):
"""Build the LSTM model."""
model = Sequential([
LSTM(units=50, return_sequences=True, input_shape=input_shape),
Dropout(0.2),
LSTM(units=50, return_sequences=False),
Dropout(0.2),
Dense(units=1) # Output: Predicted Close Price
])
model.compile(optimizer='adam', loss='mean_squared_error')
return model
# --------------------------------------------
# Train LSTM Model
# --------------------------------------------
def train_lstm_model(symbol, interval, start_date, end_date):
"""Train the LSTM model to predict price movement."""
# Fetch data
data = fetch_price_data(symbol, interval, start_date, end_date)
if data is None:
return None, None, None, None, None
data = calculate_technical_indicators(data)
# Drop NaN values (caused by technical indicators)
data = data.dropna()
# Normalize data
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)
# Prepare LSTM dataset
feature_columns = list(range(data.shape[1])) # All features
target_column = list(data.columns).index('Close') # Predict 'Close' price
X, y = create_lstm_dataset(scaled_data, feature_columns, target_column)
# Split dataset
train_size = int(len(X) * 0.7)
val_size = int(len(X) * 0.2)
X_train, X_val, X_test = X[:train_size], X[train_size:train_size + val_size], X[train_size + val_size:]
y_train, y_val, y_test = y[:train_size], y[train_size:train_size + val_size], y[train_size + val_size:]
# Build model
model = build_lstm_model(input_shape=(X.shape[1], len(feature_columns)))
# Train model with early stopping
early_stopping = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)
model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=50, batch_size=32, callbacks=[early_stopping])
return model, scaler, data, X_test, y_test
# --------------------------------------------
# Predict and Visualize
# --------------------------------------------
def predict_and_visualize(symbol, interval, start_date, end_date, model, scaler):
"""Make price predictions and overlay Elliott Wave labels and Fibonacci levels on the chart."""
# Fetch data
data = fetch_price_data(symbol, interval, start_date, end_date)
data = calculate_technical_indicators(data)
# Detect Elliott Waves
highs, lows, data = classify_elliott_wave(data)
# Make predictions
scaled_data = scaler.transform(data)
feature_columns = list(range(data.shape[1])) # All features
X, _ = create_lstm_dataset(scaled_data, feature_columns, target_column=0)
predictions = model.predict(X)
predicted_prices = scaler.inverse_transform(predictions)
# Calculate Fibonacci retracement/extensions
retracements, extensions = calculate_fibonacci_levels(data, start_idx=highs[-1], end_idx=lows[-1])
# Plot
plt.figure(figsize=(12, 8))
plt.plot(data['Close'], label='Actual Price', linewidth=1, color='blue')
plt.plot(range(len(data) - len(predicted_prices), len(data)), predicted_prices, label='Predicted Price', linestyle='--', color='red')
for retrace, value in retracements.items():
plt.axhline(value, linestyle='--', color='purple', label=f'Fibo {retrace}')
plt.scatter(highs, data['Close'][highs], color='green', label='Impulsive Waves (Peaks)')
plt.scatter(lows, data['Close'][lows], color='orange', label='Corrective Waves (Troughs)')
plt.title(f'{symbol} Price Prediction + Elliott Waves + Fibonacci Levels ({interval})')
plt.xlabel('Time')
plt.ylabel('Price')
plt.legend()
plt.show()
# --------------------------------------------
# Main Function
# --------------------------------------------
def main():
# Take inputs
symbol = input("Enter the symbol (e.g., 'BTC-USD' for Bitcoin or 'ETH-USD'): ")
interval = input("Enter the timeframe (e.g., '1h' for hourly, '1d' for daily, '1wk' for weekly): ")
start_date = input("Enter the start date (YYYY-MM-DD): ")
end_date = input("Enter the end date (YYYY-MM-DD): ")
# Train the model
model, scaler, data, X_test, y_test = train_lstm_model(symbol, interval, start_date, end_date)
if model is None:
print("Error training the model. Exiting.")
return
# Evaluate the model
predictions = model.predict(X_test)
predicted_prices = scaler.inverse_transform(predictions)
actual_prices = scaler.inverse_transform(y_test)
rmse = np.sqrt(mean_squared_error(actual_prices, predicted_prices))
mae = mean_absolute_error(actual_prices, predicted_prices)
print(f"Model Performance: RMSE={rmse}, MAE={mae}")
# Predict and visualize
predict_and_visualize(symbol, interval, start_date, end_date, model, scaler)
# Run the program
if __name__ == "__main__":
main()
Key Improvements
Early stopping is added to avoid overfitting.
Includes validation and test splits for proper model evaluation.
Added robust error handling.
Model performance metrics like RMSE and MAE are included.
Data visualization is extended with Fibonacci retracements, wave labels (peaks/troughs), and predicted prices.
Organized the code into modular functions for reusability and scalability.