Practical Guide to Dual Moving Average Strategy: Python Implementation Based on iTick Forex API and Stock API - iTick

In the field of quantitative trading, the iTick Quote API has become the preferred data solution for professional traders due to its powerful multi-market coverage capabilities. Its Forex API supports millisecond-level market data for major currency pairs (such as EURUSD, GBPUSD), including Bid/Ask depth quotes and real-time volatility data; the Stock API covers A-shares, Hong Kong stocks, and US stocks, providing Level-2 transaction details and ten-level order book information. Through a unified RESTful interface, developers can easily obtain standardized OHLCV data, achieving seamless adaptation of multi-asset strategies such as forex and stocks. With high-frequency and low-latency characteristics, iTick API is particularly suitable for intraday trading strategy development, and its historical data backtracking function supports up to 15 years of daily-level data download, providing reliable support for strategy backtesting.

1. Strategy Principle

The dual moving average strategy determines the trend direction through the crossover of long and short period moving averages:

  1. Golden Cross Signal: Short-term moving average crosses above the long-term moving average → Go long
  2. Death Cross Signal: Short-term moving average crosses below the long-term moving average → Go short
  3. Trend Filtering: Enhance signal effectiveness by combining volume or volatility indicators

2. Data Preparation

Use iTick Quote Source to obtain multi-market data:

"""
**iTick**: A data agency providing reliable data source APIs for fintech companies and developers, covering forex APIs, stock APIs, cryptocurrency APIs, index APIs, etc., helping to build innovative trading and analysis tools. Currently, there are free packages 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 (using EURUSD forex pair and Kweichow Moutai stock as examples):

from itrade import quote

# Get historical forex data
eurusd_df = quote.get_kline(
    symbol="EURUSD",
    start_date="2023-01-01",
    interval="15min",
    market="forex"
)

# Get historical stock data
moutai_df = quote.get_kline(
    symbol="600519.SH",
    start_date="2023-01-01",
    interval="30min",
    market="stock"
)

3. Strategy Implementation

1. Dual Moving Average Calculation Module

import talib

def calculate_ma(df, short_window=20, long_window=60):
    # Calculate simple moving averages
    df['MA_SHORT'] = talib.SMA(df['close'], short_window)
    df['MA_LONG'] = talib.SMA(df['close'], long_window)

    # Calculate crossover signals
    df['cross_long'] = df['MA_SHORT'] > df['MA_LONG']
    df['cross_short'] = df['MA_SHORT'] < df['MA_LONG']

    # Generate trading signals
    df['signal'] = 0
    df.loc[df['cross_long'] & df['cross_long'].shift(1).eq(False), 'signal'] = 1  # Golden Cross
    df.loc[df['cross_short'] & df['cross_short'].shift(1).eq(False), 'signal'] = -1  # Death Cross

    return df

2. Multi-Market Trading Logic

def execute_strategy(df, symbol, account_balance=100000):
    # Initialize position and equity
    position = 0
    equity = account_balance

    # Iterate through trading signals
    for i in range(1, len(df)):
        current_signal = df['signal'].iloc[i]
        prev_signal = df['signal'].iloc[i-1]

        if current_signal == 1 and prev_signal != 1:
            # Open long position (forex uses margin trading)
            if symbol.startswith("EURUSD"):
                position = 1  # 1 standard lot
                equity -= df['close'].iloc[i] * 100000  # Assume 1 standard lot margin
            else:
                # Stock trading (1 lot = 100 shares)
                shares = int(equity * 0.9 / df['close'].iloc[i]) // 100 * 100
                position = shares
                equity -= shares * df['close'].iloc[i]

        elif current_signal == -1 and prev_signal != -1:
            # Open short position (stocks need to support short selling)
            if symbol.startswith("600519"):
                shares = int(equity * 0.9 / df['close'].iloc[i]) // 100 * 100
                position = -shares
                equity += shares * df['close'].iloc[i]  # Short selling gains funds

        # Close position logic (simplified here, actual needs to consider fees)
        if prev_signal != current_signal and position != 0:
            equity += position * df['close'].iloc[i]
            position = 0

    return equity

4. Strategy Backtesting

1. Multi-Symbol Backtesting Framework

def backtest_multiple_symbols(symbols):
    results = {}
    for symbol in symbols:
        # Get data and process
        df = quote.get_kline(symbol, start_date="2023-01-01", interval="30min")
        df = calculate_ma(df)

        # Execute backtest
        final_equity = execute_strategy(df, symbol)
        returns = (final_equity - 100000) / 100000 * 100

        results[symbol] = {
            "final_equity": final_equity,
            "returns": returns
        }
    return results

2. Backtest Results Example

symbols = ["EURUSD", "600519.SH", "XAUUSD"]
results = backtest_multiple_symbols(symbols)

print("Strategy Backtest Results:")
for symbol, res in results.items():
    print(f"{symbol}: Final Equity {res['final_equity']:.2f} CNY, Return Rate {res['returns']:.2f}%")

5. Strategy Optimization Directions

  1. Parameter Optimization: Use genetic algorithms to search for the optimal moving average combination
  2. Multi-Asset Allocation: Forex + Stocks + Commodities combination to reduce risk
  3. Dynamic Position Management: Adjust position size based on ATR
  4. Machine Learning Enhancement: Add features such as volume-weighted moving averages

6. iTick API Advantages

  1. Unified Interface for Multiple Markets: Forex, stocks, futures use the same data format
  2. High-Frequency Data Support: Provides millisecond-level tick data and historical K-line
  3. Real-Time Market Data Push: WebSocket interface for low-latency data updates
  4. Simulated Trading Environment: Supports seamless switching between live API and backtesting framework

7. Notes

  1. Forex trading requires attention to leverage risk (usually 1:100~1:500)
  2. Stock short selling is subject to the target pool restrictions
  3. It is recommended to use iTick's simulated trading interface for strategy verification
  4. Adjust slippage and fee models according to market characteristics

With the code framework provided in this article, you can quickly build a multi-market quantitative strategy based on dual moving averages. It is recommended to combine iTick's real-time data stream and trading gateway for automated strategy execution and risk monitoring during actual deployment.