RSI Quantitative Strategy Practical Guide: Python Implementation Based on iTick Data Feed
In the field of quantitative trading, the iTick quotation API has become a core infrastructure for strategy developers due to its multi-market coverage and high-performance characteristics. Its foreign exchange API supports real-time market data push for major global currency pairs (such as EURUSD, USDJPY), providing tick-level Bid/Ask depth data and volatility indicators; the stock API covers A-share, Hong Kong stock, and US stock markets, including Level-2 transaction-by-transaction data and ten-level order book information. Through a unified RESTful interface, developers can freely obtain standardized OHLCV data, enabling the rapid development of multi-asset strategies such as foreign exchange and stocks. iTick's free quotation API not only supports historical data backtracking (up to 15 years of daily data) but also provides real-time data streams for strategy verification, making it particularly suitable for the live deployment of technical indicator strategies such as RSI. Its low-latency feature (average response time < 10ms) and full market coverage capability have helped thousands of quantitative traders implement their strategies.
I. Strategy Principle
The Relative Strength Index (RSI), proposed by Welles Wilder, is a classic technical indicator that measures market overbought/oversold conditions by calculating the magnitude of price fluctuations. RSI ranges from 0 to 100, with common judgment criteria:
RSI > 70: Overbought, potential reversal signal
RSI < 30: Oversold, potential reversal signal
Combine with trend lines or price breakthroughs to enhance signal effectiveness
[图片]
II. Data Preparation
This article uses high-frequency data provided by the iTick financial data platform, supporting multiple markets such as A-shares, futures, and digital currencies. Install the data interface library:
"""
iTick: is a data agency that provides reliable data source APIs for fintech companies and developers, covering foreign exchange API, stock API, cryptocurrency API, index API, etc., helping to build innovative trading and analysis tools. Currently, there are free plans available that can basically meet the needs of individual quantitative developers.
https://github.com/itick-org
https://itick.org
"""
pip install itrade # iTick data interface
Data acquisition example (taking CSI 300 index futures as an example):
from itrade import quote
Get historical data
df = quote.get_kline(
symbol="IF2303",
start_date="2023-01-01",
end_date="2024-01-01",
interval="1min"
)
Data preprocessing
df = df[['datetime', 'open', 'high', 'low', 'close', 'volume']]
df.set_index('datetime', inplace=True)
III. Strategy Implementation
- RSI Calculation Function
import pandas as pd
import numpy as np
def calculate_rsi(df, window=14):
delta = df['close'].diff(1)
gain = delta.where(delta > 0, 0)
loss = -delta.where(delta < 0, 0)
avg_gain = gain.rolling(window=window, min_periods=window).mean()
avg_loss = loss.rolling(window=window, min_periods=window).mean()
rs = avg_gain / avg_loss
rsi = 100 - (100 / (1 + rs))
df[f'RSI_{window}'] = rsi
return df
- Signal Generation Logic
def generate_signals(df, rsi_window=14):
df = calculate_rsi(df, rsi_window)
# Golden cross/dead cross signals
df['signal'] = 0
df.loc[df[f'RSI_{rsi_window}'] > 70, 'signal'] = -1 # Short in overbought zone
df.loc[df[f'RSI_{rsi_window}'] < 30, 'signal'] = 1 # Long in oversold zone
# Trend filtering (optional)
df['ma50'] = df['close'].rolling(50).mean()
df.loc[df['ma50'] < df['ma50'].shift(1), 'signal'] = 0 # Do not go long in a downtrend
df.loc[df['ma50'] > df['ma50'].shift(1), 'signal'] = 0 # Do not go short in an uptrend
return df
IV. Strategy Backtesting
- Basic Backtesting Framework
def backtest_strategy(df):
df['position'] = df['signal'].diff()
# Calculate trading returns
df['returns'] = np.log(df['close'] / df['close'].shift(1))
df['strategy_returns'] = df['position'] * df['returns']
# Calculate cumulative returns
df['cumulative_returns'] = df['strategy_returns'].cumsum()
# Calculate annualized returns, Sharpe ratio, etc.
total_days = len(df) / 252
sharpe_ratio = np.sqrt(252) * (df['strategy_returns'].mean() / df['strategy_returns'].std())
return df, sharpe_ratio
- Backtest Result Analysis
Execute backtest
df, sharpe = backtest_strategy(df)
print(f"Strategy Sharpe Ratio: {sharpe:.2f}")
print(f"Maximum Drawdown: {max_drawdown(df['cumulative_returns']):.2%}")
Visualization
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
plt.plot(df.index, df['cumulative_returns'], label='Strategy Returns')
plt.plot(df.index, df['close'].pct_change().cumsum(), label='Benchmark Returns')
plt.legend()
plt.show()
V. Strategy Optimization Directions
Parameter Optimization: Use GridSearchCV to find the optimal combination of RSI period and threshold
Multi-Time Frame: Combine daily and hourly signals to improve win rate
Risk Control: Set dynamic stop-loss (such as ATR channel stop-loss)
Money Management: Adjust positions based on volatility
VI. Advantages of iTick Data
Full Market Coverage: Supports multiple varieties such as A-shares, futures, options, and digital currencies
High-Frequency and Low-Latency: Provides Level-2 market data and tick-level data
Convenient Access: Supports Python/R/Matlab multi-language interfaces
Complete Historical Data: Provides more than ten years of historical market data
VII. Notes
RSI may become sluggish in trending markets; it is recommended to use it in conjunction with trend indicators
Strategy parameters need to be re-optimized regularly
Slippage and liquidity risks should be considered in live trading
It is recommended to use iTick's real-time data stream for strategy verification
Through the code framework in this article, readers can quickly implement RSI-based quantitative strategies and conduct strategy development and verification with iTick's professional financial data. In practical applications, parameters and risk control rules need to be adjusted according to specific market conditions.
Original article from:
https://itick.org/blog/rsi-strategy-hands-on-guide-with-itick-data-python
Top comments (0)