Creating a Momentum-Based Indicator with Python for Trading
Written on
Chapter 1: Understanding Technical Indicators
Technical indicators are widely used in trading, and many traders opt to create custom indicators tailored to their risk tolerance, return expectations, and analytical strategies. This article aims to develop a straightforward contrarian indicator and conduct a back-test. The primary objective is not to discover a winning indicator but to understand the development process and formulate trading rules.
I have recently launched a new book following the success of my previous publication. It includes advanced trend-following indicators and strategies, along with a dedicated GitHub page for ongoing updates to the code. This book features original colors optimized for printing costs. If this piques your interest, please check out the Amazon link below or reach out to me on LinkedIn for the PDF version.
Chapter 2: The Concept of Momentum
Momentum in the market refers to the tendency of prices to move consistently in one direction—either upward or downward. Understanding this concept allows traders to capitalize on it in various ways:
- Trend-Following Strategy: Riding the momentum by initiating trades in the same direction.
- Contrarian Strategy: Fading the momentum by trading in the opposite direction.
Depending on personal preferences and trading psychology, traders may lean towards one of these strategies. For this discussion, we will focus on the contrarian approach, which seeks mean-reverting oscillators that signal extremes in the market, guiding entry and exit points.
Example: EURCAD Hourly Chart
The chart illustrates a period of strong bullish momentum followed by a significant bearish trend. Our contrarian strategy aims to time market entries near the peaks and exits near the troughs. While it’s unrealistic to consistently pinpoint the exact tops and bottoms, we can create tools that signal approximate extremes, albeit with occasional false signals due to market randomness.
Consider exploring Medium, a platform filled with insightful articles. I found much inspiration there before I began writing. If you’re interested, you can join Medium using my referral link.
Chapter 3: Developing a Custom Momentum Indicator
Next, we will calculate momentum, which can be achieved either by comparing the current market price to a historical price or by taking the difference between them. For this illustration, we will utilize simple differencing—specifically, the difference between the current market price and a price from 13 periods prior. The mathematical formulation is as follows:
We will create an indicator that appears stationary, oscillating around zero. To enhance its readings, we can apply a moving average, such as a 3-period moving average.
When applied to the hourly values of EURUSD, this will yield a smoother indicator with defined barriers for back-testing at 0.005 and -0.005.
Trading Strategies with the Custom Indicator
The next phase involves trading this indicator using various strategies such as crossovers and extreme signals. A confirmation strategy might work as follows:
- Long (Buy): Execute a trade whenever the indicator rises above -0.005 after being below that threshold, indicating a bullish exit from the oversold zone.
- Short (Sell): Execute a trade whenever the indicator drops below 0.005 after being above it, signaling a bearish exit from the overbought zone.
Signal Chart on EURUSD
The chart below illustrates the signals generated using this approach on the EURUSD.
Code Implementation
To implement the strategy, the following functions can be defined:
def adder(Data, times):
for i in range(1, times + 1):
new = np.zeros((len(Data), 1), dtype=float)
Data = np.append(Data, new, axis=1)
return Data
def signal(Data, custom_indicator_col, buy, sell):
Data = adder(Data, 5)
for i in range(len(Data)):
if Data[i, custom_indicator_col] > lower_barrier and Data[i - 1, custom_indicator_col] < lower_barrier:
Data[i, buy] = 1elif Data[i, custom_indicator_col] < upper_barrier and Data[i - 1, custom_indicator_col] > upper_barrier:
Data[i, sell] = -1return Data
Now that we have our signals, we can evaluate the strategy's performance using the Signal Quality metric.
Chapter 4: Evaluating Signal Quality
After generating signals, we can simulate the trading strategy’s performance, allowing us to analyze returns and performance metrics. The Signal Quality metric resembles a fixed holding period strategy, measuring the market reaction after a certain time following a signal.
Choosing the Holding Period
We can choose a holding period and assess the signal quality with the following function:
def signal_quality(Data, closing, buy, sell, period, where):
Data = adder(Data, 1)
for i in range(len(Data)):
if Data[i, buy] == 1:
Data[i + period, where] = Data[i + period, closing] - Data[i, closing]if Data[i, sell] == -1:
Data[i + period, where] = Data[i, closing] - Data[i + period, closing]return Data
The output reveals the strategy’s effectiveness, showing a signal quality of approximately 48.83%.
Conclusion
As expected, this simplistic strategy does not significantly enhance predictive capabilities. The focus of this article was to foster an understanding of creating indicators. The Signal Quality metric alone cannot assess a strategy’s effectiveness; additional risk indicators should be included for a comprehensive view.
I often utilize Fibonacci sequences for holding periods, but personal preferences vary. Ultimately, the goal is to explore various periods and determine what resonates best for you.
For more insights into trading strategies, consider subscribing to my DAILY Newsletter. Subscribers receive my Medium articles, trading strategies, coding lessons, and a complimentary PDF of my first book.
Remember, always back-test your strategies. Trust your intuition and beliefs, as what works for one trader may not work for another.
Supporting Humanitarian Causes
I have recently launched an NFT collection aimed at supporting various humanitarian efforts. The Society of Light comprises limited collectibles, with a portion of each sale directed to associated charities.
Benefits of Purchasing NFTs:
- High potential for appreciation in the secondary market.
- A unique art collection that symbolizes positive contributions.
- Flexible donation options to preferred charities.
- A complimentary PDF copy of my latest book with each NFT purchase.
Click here to buy Nino and support humanitarian causes.
The first video titled "Code 10 Technical Trading Indicators with Python" provides an in-depth look at various technical indicators, demonstrating their implementation and significance in trading.
The second video, "Stock Technical Indicators Using Python," explores the application of technical indicators in stock trading, focusing on practical coding examples.