# abdallah abdelkarim
# Algorithmic Trading with Python: Using Machine Learning for Market Prediction
# In the ever-evolving landscape of financial markets, the fusion of machine learning and algorithmic trading
# has opened new avenues for investors seeking to optimize their strategies and outperform traditional
# benchmarks. This comprehensive tutorial will guide you through the process of leveraging Python, a powerful
# programming language, to harness machine learning for market prediction. By the end of this journey,
# you’ll have a solid foundation to embark on your own algorithmic # trading adventures, equipped with
# real-world applications and stunning visualizations to showcase your insights
# nSetting the Stage: The Power of Python in Finance
# Python has emerged as a lingua franca for data scientists and financial analysts alike, thanks
# to its simplicity, versatility and robust ecosystem of libraries. Before diving into the intricacies
# of algorithmic trading and machine learning, let’s ensure our environment is ready.
# pip install yfinance numpy pandas matplotlib plotly mplfinance scikit-learn
# Our first step is to import these libraries, setting the stage for our financial data analysis and machine
# learning endeavors.
import yfinance as yf
import numpy as np
import pandas as pd
import [Link] as plt
import plotly.graph_objects as go
import mplfinance as mpf
from sklearn.model_selection import train_test_split
from [Link] import RandomForestRegressor
from [Link] import mean_squared_error
# Diving into Data: Fetching Financial Time Series
# Choosing the right asset for analysis can significantly impact the insights and predictions we derive.
# For this tutorial, let’s focus on a less conventional yet intriguing market: cryptocurrency.
# Specifically, we’ll analyze Bitcoin (BTC), a leading altcoin with substantial market movements and
# trading volume.
# Define the ticker symbol
tickerSymbol = 'BTC-USD'
# Get data on this ticker
tickerData = [Link](tickerSymbol)
# Get the historical prices for this ticker
tickerDf = [Link](period='1d', start='2020-01-01', end='2024-03-12')
# Display the first few rows
print([Link]())
Open High Low Close \
Date
2020-01-01 00:00:00+00:00 7194.892090 7254.330566 7174.944336 7200.174316
2020-01-02 00:00:00+00:00 7202.551270 7212.155273 6935.270020 6985.470215
2020-01-03 00:00:00+00:00 6984.428711 7413.715332 6914.996094 7344.884277
2020-01-04 00:00:00+00:00 7345.375488 7427.385742 7309.514160 7410.656738
2020-01-05 00:00:00+00:00 7410.451660 7544.497070 7400.535645 7411.317383
Volume Dividends Stock Splits
Date
2020-01-01 00:00:00+00:00 18565664997 0.0 0.0
2020-01-02 00:00:00+00:00 20802083465 0.0 0.0
2020-01-03 00:00:00+00:00 28111481032 0.0 0.0
2020-01-04 00:00:00+00:00 18444271275 0.0 0.0
2020-01-05 00:00:00+00:00 19725074095 0.0 0.0
# With our data in hand, it’s time to visualize Ethereum’s price movements to gain initial insights.
# Visualizing the Market: Plotting Price Movements
# A picture is worth a thousand words, especially in financial analysis. Let’s create a candlestick chart
# to visualize Ethereum’s price movements over time.
# Candlestick chart of Ethereum's price
[Link](tickerDf, type='candle', volume=True, style='charles', )
/Users/abdelkarimabdallah/anaconda3/lib/python3.11/site-packages/mplfinance/_arg_validators.py:84: UserWarning:
=================================================================
WARNING: YOU ARE PLOTTING SO MUCH DATA THAT IT MAY NOT BE
POSSIBLE TO SEE DETAILS (Candles, Ohlc-Bars, Etc.)
For more information see:
- [Link]
TO SILENCE THIS WARNING, set `type='line'` in `[Link]()`
OR set kwarg `warn_too_much_data=N` where N is an integer
LARGER than the number of data points you want to plot.
================================================================
[Link]('\n\n ================================================================= '+
# Preparing the Data: Feature Engineering for Machine Learning
# To leverage machine learning for market prediction, we need to engineer features that capture market trends
# and patterns. Let’s create moving averages as our features.
# Calculate moving averages
tickerDf['MA5'] = tickerDf['Close'].rolling(window=5).mean()
tickerDf['MA10'] = tickerDf['Close'].rolling(window=10).mean()
# Drop NaN values
tickerDf = [Link]()
# Display the new DataFrame
print([Link]())
Open High Low Close \
Date
2020-01-10 00:00:00+00:00 7878.307617 8166.554199 7726.774902 8166.554199
2020-01-11 00:00:00+00:00 8162.190918 8218.359375 8029.642090 8037.537598
2020-01-12 00:00:00+00:00 8033.261719 8200.063477 8009.059082 8192.494141
2020-01-13 00:00:00+00:00 8189.771973 8197.788086 8079.700684 8144.194336
2020-01-14 00:00:00+00:00 8140.933105 8879.511719 8140.933105 8827.764648
Volume Dividends Stock Splits MA5 \
Date
2020-01-10 00:00:00+00:00 28714583844 0.0 0.0 8011.679980
2020-01-11 00:00:00+00:00 25521165085 0.0 0.0 8065.343652
2020-01-12 00:00:00+00:00 22903438381 0.0 0.0 8071.104004
2020-01-13 00:00:00+00:00 22482910688 0.0 0.0 8083.970312
2020-01-14 00:00:00+00:00 44841784107 0.0 0.0 8273.708984
MA10
Date
2020-01-10 00:00:00+00:00 7641.090283
2020-01-11 00:00:00+00:00 7724.826611
2020-01-12 00:00:00+00:00 7845.529004
2020-01-13 00:00:00+00:00 7925.460010
2020-01-14 00:00:00+00:00 8067.170801
# Splitting the Data: Training and Testing Sets
# A crucial step in machine learning is splitting our data into training and testing sets, ensuring our model
# can generalize well to unseen data.
# Define features and target
X = tickerDf[['MA5', 'MA10']]
y = tickerDf['Close']
# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Building the # Model: Random Forest for Regression
# With our data prepared, let’s build a Random Forest model to predict BITCOIN closing prices based
# on our moving averages.
# Initialize and train the Random Forest model
model = RandomForestRegressor(n_estimators=100, random_state=42)
[Link](X_train, y_train)
# Predictions
predictions = [Link](X_test)
# Evaluate the model
mse = mean_squared_error(y_test, predictions)
print(f"Mean Squared Error: {mse}")
Mean Squared Error: 1591357.8075847782
# Visualizing Predictions: Comparing Actual vs. Predicted Prices
# To assess our model’s performance visually, let’s plot the actual vs. predicted closing prices of Bitcoin.
# Create a DataFrame for plotting
comparison_df = [Link]({'Actual': y_test, 'Predicted': predictions})
comparison_df = comparison_df.head(25)
# Plotting
comparison_df.plot(kind='bar', figsize=(10, 6))
[Link](which='major', linestyle='-', linewidth='0.5', color='green')
[Link](which='minor', linestyle=':', linewidth='0.5', color='black')
# Conclusion
# Throughout this tutorial, we’ve traversed the landscape of algorithmic trading with Python, from fetching and
# visualizing financial data to engineering features and building a machine learning model for market
# prediction. The journey from raw data to actionable insights exemplifies the power of Python in financial
# analysis and machine learning.
# As we conclude, remember that the world of algorithmic trading is vast and complex. The techniques
# and insights gained here are just the beginning. Continuous learning, experimentation and adaptation are key
# to success in leveraging machine learning for market prediction.
Loading [MathJax]/jax/output/CommonHTML/fonts/TeX/[Link]