
I. Strategy Principles
The Relative Strength Index (RSI) is a classic technical indicator proposed by Welles Wilder. It measures market overbought/oversold conditions by calculating price fluctuation magnitudes. The RSI ranges from 0 to 100, with common judgment criteria:
- RSI > 70: Overbought, potential reversal signal
- RSI < 30: Oversold, potential reversal signal
- Combining trend lines or price breakouts can enhance signal effectiveness
II. Data Preparation
This guide utilizes high-frequency data provided by the iTick financial data platform, which supports multiple markets, including A-shares, futures, and cryptocurrencies. Install the data interface library:
pip install itrade # iTick data interface
Example of data retrieval (using the CSI 300 Index futures as an example):
""""
**iTick**: A data agency providing reliable data source APIs for fintech companies and developers, covering Forex API, Stock API, Cryptocurrency API, Index API, etc., helping to build innovative trading and analysis tools. They currently offer a free package that can meet the needs of individual quantitative developers.
Open-source stock data API address:
https://github.com/itick-org
Apply for a free API key at:
https://itick.org
""""
from itrade import quote
# Fetch 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
1. 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
2. Signal Generation Logic
def generate_signals(df, rsi_window=14):
df = calculate_rsi(df, rsi_window)
# Golden Cross/Death Cross Signals
df['signal'] = 0
df.loc[df[f'RSI_{rsi_window}'] > 70, 'signal'] = -1 # Overbought zone, go short
df.loc[df[f'RSI_{rsi_window}'] < 30, 'signal'] = 1 # Oversold zone, go long
# Trend Filtering (Optional)
df['ma50'] = df['close'].rolling(50).mean()
df.loc[df['ma50'] < df['ma50'].shift(1), 'signal'] = 0 # No long in a downtrend
df.loc[df['ma50'] > df['ma50'].shift(1), 'signal'] = 0 # No short in an uptrend
return df
IV. Strategy Backtesting
1. 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']
# Compute cumulative returns
df['cumulative_returns'] = df['strategy_returns'].cumsum()
# Compute annualized return, 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
2. Backtesting Results 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 RSI period and threshold combination
- Multiple Time Frames:Combine daily and hourly signals to improve win rate
- Risk Control:Set dynamic stop-loss (e.g., ATR channel stop-loss)
- Capital Management:Adjust positions based on volatility
VI. Advantages of iTick Data
- Wide Market Coverage:Supports A-shares, futures, options, digital currencies, and other asset classes
- High Frequency & Low Latency:Provides Level-2 quotes and tick-level data
- Easy Integration:Supports Python/R/Matlab interfaces
- Comprehensive Historical Data:Provides more than ten years of historical market data
VII. Considerations
- RSI may become less responsive in trending markets; it is recommended to use it in conjunction with trend indicators
- Regular re-optimization of strategy parameters is necessary
- In live trading, slippage and liquidity risks should be considered
- It is recommended to use iTick's real-time data stream for strategy validation
Through the code framework provided in this article, readers can quickly implement an RSI-based quantitative strategy and develop and validate the strategy using iTick's professional financial data. In practical applications, parameters and risk control rules should be adjusted according to the specific market environment.