Building a Cryptocurrency Trading Strategy: Technical Analysis with Python and CCXT
Let’s break down the code into the specified parts:
Part 1: Importing Libraries
import pandas as pd
import ccxt
import talib
import pandas_ta as ta
Explanation: This part imports essential libraries for data manipulation and technical analysis.
Use Cases:
pandas
: Used for handling data in tabular format.ccxt
: Provides a unified way to access cryptocurrency trading data from various exchanges.talib
: Library for technical analysis indicators.pandas_ta
: Extension of Pandas library with additional technical analysis indicators.
Part 2: Function to Fetch Data
def fetch_data(symbol, timeframe='1m', limit=599):
exchange = ccxt.huobi()
ohlcv = exchange.fetch_ohlcv(symbol, timeframe, limit=limit)
df = pd.DataFrame(ohlcv, columns=['timestamp', 'Open', 'High', 'Low', 'Close', 'Volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
df.set_index('timestamp', inplace=True)
return df
Explanation: This function fetches historical OHLCV data for a specified trading pair and time frame from the Huobi exchange and returns it as a Pandas DataFrame.
Use Cases:
- Analyzing historical price data for a specific cryptocurrency pair.
- Backtesting trading strategies using historical data.
Part 3: Function to Generate Signals
def generate_signals(data):
# Calculate MACD
data['macd_red'], data['macd_signal_blue'], candle_macd = talib.MACD(data['Close'], fastperiod=34, slowperiod=144, signalperiod=9)
# Calculate RSI
data['rsi'] = talib.RSI(data['Close'])
# Calculate Bollinger Bands
data['upper_band'], data['middle_band'], data['lower_band'] = talib.BBANDS(data['Close'])
# Calculate Donchian Channel
data['upper_dc'], data['lower_dc'] = talib.MAX(data['High'], timeperiod=20), talib.MIN(data['Low'], timeperiod=20)
return data
Explanation: This function calculates various technical indicators like MACD, RSI, Bollinger Bands, and Donchian Channel and adds them as columns to the input DataFrame.
Use Cases:
- Identifying trends and momentum in the market using MACD.
- Assessing overbought or oversold conditions with RSI.
- Analyzing volatility with Bollinger Bands.
- Identifying breakout or breakdown levels with the Donchian Channel.
Part 4: Function to Analyze Signals
def analyze_signals(data):
signals = pd.DataFrame(index=data.index)
# MACD signals
signals['macd_buy'] = (data['macd_red'] > data['macd_signal_blue'])
signals['macd_sell'] = (data['macd_red'] < data['macd_signal_blue'])
# RSI signals
signals['rsi_overbought'] = (data['rsi'] > 70)
signals['rsi_oversold'] = (data['rsi'] < 30)
signals['rsi_middle'] = (data['rsi'] > 30) & (data['rsi'] < 70)
# Bollinger Bands signals
signals['bollinger_buy'] = data['Close'] < data['lower_band']
signals['bollinger_sell'] = data['Close'] > data['upper_band']
signals["bollinger_middle_line_buy"] = (data['middle_band'] < data['Close'])
signals["bollinger_middle_line_sell"] = (data['middle_band'] > data['Close'])
# Donchian Channel signals
signals['donchian_buy'] = data['Close'] > data['upper_dc']
signals['donchian_sell'] = data['Close'] < data['lower_dc']
signals['donchian_buy_middle'] = data['Close'] > data['upper_dc']
signals['donchian_sell_middle'] = data['Close'] < data['lower_dc']
# Print only the last row of the signals DataFrame
print(signals.iloc[-1])
return signals
Explanation: This function analyzes the calculated signals from Part 3 and generates buy/sell signals based on specific conditions for each indicator.
Use Cases:
- Generating trading signals for algorithmic trading strategies.
- Providing insights into potential entry and exit points based on technical analysis.
Part 5: Example Usage
# Example Usage
symbol = 'BTC/USDT'
data = fetch_data(symbol)
data = generate_signals(data)
display(data)
signals = analyze_signals(data)
Explanation: This part demonstrates how to use the functions. It fetches historical data for the ‘BTC/USDT’ trading pair, generates signals based on technical indicators, displays the modified DataFrame, and analyzes the signals to generate buy/sell signals.
Use Cases:
- Implementing and testing a basic trading strategy.
- Understanding how different indicators align with historical price data.
Each part is labeled with a comment indicating its purpose in the code. You can run these parts sequentially in a Python environment.
Do it on your own RISK
link to Github