SMART Trading Strategies http://smarttradingstrategies.com Statistical and Mathematical Approach to Retail Trading Sat, 30 Mar 2024 03:45:08 +0000 en-US hourly 1 https://wordpress.org/?v=6.5 http://smarttradingstrategies.com/wp-content/uploads/2021/08/logo-150x150.png SMART Trading Strategies http://smarttradingstrategies.com 32 32 Quantitative Trading Systems (2nd Edition) by Howard B. Bandy http://smarttradingstrategies.com/quantitative-trading-systems-2nd-edition-by-howard-b-bandy/ http://smarttradingstrategies.com/quantitative-trading-systems-2nd-edition-by-howard-b-bandy/#respond Thu, 29 Feb 2024 10:24:34 +0000 https://smarttradingstrategies.com/?p=1284 These are notes complied from Howard B. Bandy’s excellent book: Quantitative Trading Systems. The notes here focus on Chapters 9 to 17, which primarily discuss different trading systems and strategies.

The post is a work-in-progress and will be updated as I complete the different chapters.

Chapter 9: Trending Systems

Key Takeaways

  • Moving average crossover systems do not work for equities.

He gave an example of a backtest on LPX from 1991 to 2007, where the closing price of the stock at the end of the period did not differ much from the opening price at the start of the period. An optimization for a long only strategy found that the best result is obtained if we buy when the slow moving average crosses above the fast moving average (instead of the other way round). This means the system performs best as a mean reversion system.

  • For breakout systems, you should use a trailing stop instead of a profit target.

This is because breakout systems have a low percentage of winning trades (30% is not unusual). Hence, you need the big wins to offset the more frequent small losses. Setting profit targets that are often hit means giving up the big gains; setting profit targets that are seldom hit means creating a curve-fit system.

  • When breakout systems work, they work best to trade commodities but do not work well on common stocks.
  • When backtesting, we should separate the effects of a rising market on a profitable long only strategy.

The US markets had a long steady increase from 1982 through 2000. Essentially any technique that took long positions during that time was successful. To separate the effect of the rising market on a long-only strategy, we can test the strategy from early 1999 to 2011. Measured by the S&P 500 or NASDAQ 100, the markets as of May 2011 are at approximately the same price level as they were early 1999, giving a 12 year period with little overall price changes.

Code

Plotting the equity curve

https://smarttradingstrategies.com/afl-code-examples/#Plotting_the_Equity_Curve

Chapter 10: Mean Reversion

Key Takeaways

  • Mean reversion is based on the premise that prices tend to oscillate above and below some level of equilibrium (typically some form of the mean). When prices deviate too much from equilibrium, you can take a position that will profit from a return to equilibrium.
  • Almost any indicator that swings between high and low levels (such as the RSI) can be used to create a mean reversion trading system.
  • If a series does not oscillate, it can be transformed into one that does. There are two techniques to do this:
    • One technique is to subtract a moving average of the series from itself, resulting in a series that oscillates about zero and having a period (duration from one peak to another) about the length of the moving average.
    • Another technique is to compute a position-in-range statistic for the series. For instance, you can determine the highest-high value (HHV) and the lowest-low value (LLV) of the past 20-days and calculate the position of the current price in the HHV-LLV range. If the current price is midway within the range, the indicator has a value of 0.5. If the current price is the HHV, the indicator has a value of 1, and so on.
  • Oscillator systems get their signals from the following techniques:
    • Zero crossing: Buy when the oscillator crosses from below zero to above zero, sell when the reverse happens.
    • Crossing of the series with another series, where the second series is a delayed or smoothed copy of the original series.
    • Crossing of the oscillator with a level, such as the levels 0.2 and 0.8 for the stochastic oscillator (buy when it crosses above 0.2, sell when it crosses below 0.8).

Code

Other than the learning points above, this chapter includes the code for a number of oscillators and systems. Not much detail is given on the workings of these oscillators.

The oscillators (and related systems) provided are:

These systems provide examples of how you can

  • Use a smoothed version of an oscillator to trigger a signal
  • Compute a position-in-range series
  • Convert a data series into an oscillator

Chapter 11: Seasonality Systems

Key Takeaways

  • This chapter explores a few seasonality systems and provides the code for testing if a pattern exists
  • The few seasonality systems discussed are:
    • Day of Month (i.e. buying on Day 1 vs Day 2 vs Day 3 etc)
    • First trading day of the month and the 8 days before and after it
    • Options Expiration Day and the 8 days before and after it
    • Phase of the moon
  • The phase of the moon pattern did not do well using out-of-sample data in the first edition.
  • The other three patterns appear to do well when tested using out of sample data in the first edition of the book. However, they fail to do well when testing using data that occurred between the 1st and 2nd editions of the book. This could be because the model fell out of synchronization and may make a comeback in future.

Code

This code combines the first three seasonality systems listed above and allows us to test which day produces the best results.

Testing Seasonality Patterns

Chapter 12: Pattern Systems

Key Takeaways

This chapter explores how the price action of the past three days (including today) affects the price action for the next day.

Similar to the author’s findings, I tested the code and could not find a consistent pattern.

Code

The code works as follows:

  • Calculate the percentage return for each day
  • Define a cutoff point to be used for splitting the percentage returns into three categories.
    • Suppose the cutoff point is x. Daily returns in the top x% of the returns for the past 60 days belong to the top group, daily returns in the bottom x% belong to the bottom group, the rest belong in the middle group.
  • Label each day as 1, 2, or 3.
    • 1 for bottom group, 2 for middle group and 3 for top group.
  • Combine the labels for three consecutive days such that
    • 111 means the returns for the three days are all in the bottom group,
    • 112 means the returns for today is in the middle group, while the returns for yesterday and the day before are both in the bottom group and so on.
  • Optimize to see which sequence produces the best result

Pattern Systems

Chapter 13: Anticipating Signals

Key Takeaways

If your trading systems are designed to trade at the closing price on the day the signal is generated, you must either:

  • be able to monitor the market near the close, estimate the closing price, and act very near the close, or
  • precalculate the price that will trigger a signal and place a limit-on-close order before the close.

The code below shows how you can estimate the price that will trigger a signal using a binary search.

Code

This example uses a binary search to determine the closing price that causes two moving averages to be equal to each other. Once you know this value, you can then infer that there will be a crossover when the closing price rises above or falls below this value.

You can modify the code for other types of crossover by editing the ZeroToFind() function.

Generic Binary Search

Chapter 14: Sector Analysis

Key Takeaways

  • You can export a data series from the Amibroker database to a CSV formatted file in a directory of your choice. The code labelled “Export Data Series” below shows how it can be done. To use the code, do the following:
    • Open the AFL file in “Automatic Analysis”.
    • Next, open the AFL file in the AFL Formula Editor and click the Verify Syntax icon.
    • A file named exported.csv will be written to the directory specified as argument to the fopen() function.
  • The Foreign() and SetForeign() functions in Amibroker allow us to access data from a foreign data series (i.e. a data series whose chart is not currently displayed in the chart window)
    • Foreign() loads a single component – one of OHLCVI – into a single component.
    • SetForeign() loads all six variables into the default variables Open, High, Low, Close, Volume and OpenInt.
    • RestorePriceArrays() informs Amibroker that data from the current symbol is to be used from that point on.

Code

Export Data Series

Using Foreign

Using SetForeign

Chapter 15: Rotation

Key Takeaways

  • The book uses the EnableRotationalTrading() function to inform the backtester to rotate between different stocks.
  • This function is now obsolete. Use SetBacktestMode(backtestRotational) in new formulas. (https://www.amibroker.com/guide/afl/enablerotationaltrading.html)
  • How rotation works in Amibroker
    • All scores are sorted according to the absolute value of PositionScore. Higher positive score means better candidate foe entering long trade; lower negative score means better candidate for entering short trade.
    • Backtester successively enters the trades starting from highest ranked security until the number of positions open reaches max open positions or there are no more funds available.
    • Exits are generated automatically when security’s rank drops below WorstRankHeld

Code

Rotation

Chapter 16: Portfolios

Key Takeaways

  • To perform portfolio backtest, select “Backtest > Portfolio Backtest” in the Analysis Window (refer to the screenshot above).
  • Use SetOption(“MaxOpenPositions”, n) to set the maximum number of open positions, where n is the desired number of open positions.
  • Use PositionScore (similar to the one used in rotational trading) to break ties when there are more signals than entry places.

Chapter 17: Filters and Timing

Key Takeaways

Can use interest rate as a filter system.

  • Yahoo Finance maintains several interest rate-related data series, including ^IRX (90 day interest rate), ^FVX (yield on the Five Year Note), ^TXN (yield on the Ten Year Note).
  • One example of using interest rate as a filter system is given by the “Interest Rate Filter” code below
  • Another example is the Heine Interest Rate Filter
    • This filter is based on weekly data of five indices: Dow Jones 20 Bond Index, Long Term Bond Yields, 13 Week T Bill Yield, Dow Jones Utility Index, and CRB Index.
    • It is designed to time the Dow Jones 20 Bond Index (or the Dow Jones Corporate Bond Index).
    • Score +1 when any of the below occurs
      • DJ20 > its 24 week SMA
      • Long Term Bond Yield < its 6 week SMA
      • 13 Week Yield < its 6 week SMA
      • DJ Utility Index > its 10 week SMA
      • CRB Index < its 20 week SMA
    • Add up the five scores. Allow Long positions when total score >= 3, allow Short positions when total score <= 2.
    • This filter works well for long term interest rates and related securities.

Other relationships that can be used a filters include:

  • Volatility as measured by VXO (or VXN) and broad indices
  • Dollar and equities
  • Dollar and gold
  • Dollar and oil
  • Oil and transportation
  • Cattle feed and cattle
  • Crops and weather

Many trading systems are built on the principle that action at one time interval must be confirmed by action at a longer time interval.

  • Amibroker allows time frame manipulation calculations using functions such as TimeFrameSet, TimeFrameExpand, and TimeFrameRestore.
  • One example of using different time frames is given by the “Timeframe Manipulation” code below
]]>
http://smarttradingstrategies.com/quantitative-trading-systems-2nd-edition-by-howard-b-bandy/feed/ 0