Sharing investing and trading ideas. Helping traders get started.
Advertisement

Friday, May 4, 2012

Directional Movement - Backtest Results and Implementation Issues

Directional Movement - Backtest Results and Implementation Issues
Discusses basic issues and results when attempting to back-test the Directional Movement formula.

Data: S&P500 Emini Futures
Futures Contract Rollover: Arbitrarily set on second Friday of every Mar, Jun, Sep and Dec
Period: 28 Dec 2008 - 31 Mar 2012 (Hourly Chart)
VBA Code: Method B of Code
Excel Version: 2010

Note: 1) As with the Aroon Indicator, the Directional Movement can be used for other time frames and not necessarily daily data as is the context when I wrote the Directional Movement explanation page.

2) The directional movement indicator refers to an implementation of the directional movement formula. What this page attempts to do is to backtest the directional movement formula, not the directional movement index and also not the directional movement indicator. Return to the technical analysis page for links to the respective indicators, codes and backtest results. 

Click here for background information, formula, calculation steps and the entire VBA code.

There are multiple variations on how to apply an indicator. I seek your understanding that the work done below are experiments and are for information purposes only.

Results Summary
Divergence does not signify that a trend is forming in the hourly charts based on my dataset. I inverted this trading rule and arrived with a strategy that is profitable before transaction costs, as expected. Given the large number of trades generated, the naive trading rule applied will most likely not be profitable after costs. The interesting fact is that this is the second or third indicator I found where the  usual trading rule I read from other sources has to be inverted in order for the strategy to even show before transaction cost profitability.

Procedure in Brief
Pasted the code into Excel with changes made as per comments in code to direct application to ranges with input data (High, Low, Close columns). Screen Shot 1 shows the output (the last four columns).

Screen Shot 1
Detailed Findings and Results

Summary of Trading Rules -

1) Calculate Positive DM Minus Negative DM. Recall that Negative DM is a positive value. Negative refers to the fact that a new low was created in the current bar. 
2) If (Positive DM Minus Negative DM) is greater than 0, Long 
3) If (Positive DM Minus Negative DM) is lower than 0, Short
4) Else maintain long or short position

517 index points of profit (before transaction costs) were generated on a large set of 6,687 trades. Average return is very small at just 0.08 points per trade, which means that such an application will not cover trading costs for most people (I guess?). 59% of trades were profitable. Standard deviation of returns for each trade is 4.93 points. The profit trajectory of this indicator and trading rules is shown in Chart 1. 

Chart 1: Cumulative Profit of Strategy (Before Costs)
Conclusion
Although this application of the DM generated a lot of trades, just like my attempt with the Aroon Indicator, the trading rule in this case did not generate statistically significant profitability based on the student t statistic. The low per trade profitability of this approach negated the statistical effect of a large number of trades in reducing standard error. I end this post at this juncture as we will be using this Directional Movement formula in various forms when backtesting the directional movement index and the directional movement indicator. More can be elaborated then. 

Any suggestions or comments are welcome. 


Like what you have just read? Digg it or Tip'd it.
The objective of Finance4Traders is to help traders get started by bringing them unbiased research and ideas. Since late 2005, I have been developing trading strategies on a personal basis. Not all of these models are suitable for me, but other investors or traders might find them useful. After all, people have different investment/trading goals and habits. Thus, Finance4Traders becomes a convenient platform to disseminate my work...(Read more about Finance4Traders)

Tuesday, May 1, 2012

Aroon Indicator / Oscillator - Backtest Results and Implementation Issues

Aroon Indicator / Oscillator AI / AO - Backtest Results and Implementation Issues 
Discusses basic issues and results when attempting to back-test the AI and the AO indicators

Data: S&P500 Emini Futures
Futures Contract Rollover: Arbitrarily set on second Friday of every Mar, Jun, Sep and Dec
Period: 28 Dec 2008 - 31 Mar 2012 (Hourly Chart)
VBA Code: Method B of Code
Excel Version: 2010

Note: When I wrote the post for the Aroon Indicator VBA code, I wrote it in the context as though the Aroon Indicator and Oscillator can only be used on a daily basis. This is not necessarily always the case. In this case, I used the Aroon Indicator on the same hourly data as with all other backtests. 

Click here for background information, formula, calculation steps and the entire VBA code.

There are multiple variations on how to apply an indicator. I seek your understanding that the work done below are experiments and are for information purposes only.

Summary of Results 
While the Aroon Indicator has been described as a "trend" type indicator, I found that it behaves more as a price reversion indicator in the context of hourly data. Like the adaptive price zone (APZ) indicator, commonly known applications of the Aroon Indicator turned out to be loss making, requiring an inversion of the trading rule. While the Aroon Indicator (and the final trading rules used) is profitable before transaction costs, the key challenge lies with tweaking it to be profitable AFTER costs. Average profit per trade is only 0.2 index points per trade. 

Procedure in Brief
Pasted the code into Excel with changes made as per comments in code to direct application to ranges with input data (High, Low, Close columns). Screen Shot 1 shows the output (the last two columns).  

Screen Shot 1

Detailed Findings and Results
Period is set at 5 - This means that the formula looks at only the last five hours of data in the calculation of current hour Aroon Indicator value.

Summary of Trading Rules -

1) If Aroon Up is larger than Aroon Down at the end of each hour, SHORT in the next hour
2) If Aroon Down is larger than Aroon Up at the end of each hour, LONG in the next hour.
3) Otherwise, carry forward previous hour's position.

This set of trading rules generated 869.5 index points of profit (before transaction costs) on a large set of 4,146 trades. Average return per trade is 0.210 points on a standard deviation of 6.328 points. The success rate of this strategy is very high. 63.9% of the trades were profitable (before transaction costs and slippage). The profit trajectory of this indicator and trading rules is shown in Chart 1.

Chart 1: Aroon Indicator Cumulative Profit (Before Costs)

Conclusion
This set of trading rules and the indicator used generated a lot of trades. As a result, the standard error of the mean return is very small due to the formula used, which is standard deviation of returns of each trade divided by the number of trades. In turn, standard statistical distributions, such as the student t-statistic and normal z-statistic are significant when computed for this strategy. 

However, I have my doubts over the significance of these statistics. Due to the long tail nature of financial data, standard distributions may not correctly present the distribution of the returns of this strategy. Maybe this statistical significance will disappear when the correct statistic is used. 

Furthermore, I have repeatedly emphasized that the returns I calculated exclude commissions and slippage. I believe that this naive strategy on its own may not be profitable once I incorporate these costs.

The Aroon Oscillator measures the difference between the Aroon Up and Aroon Down indicator. As such, my trading rules are a form of the application of the Aroon Oscillator. 

Further research, in my opinion, can be in the application of these naive trading rules to larger time frames, e.g. daily, half-daily charts, which are more likely to generate less trades and lower trading costs. However, at larger time frames, the behaviour between price movements and the Aroon Indicator may change and may require the trading rules to be adjusted.

Any suggestions or comments are welcome.



Like what you have just read? Digg it or Tip'd it.
The objective of Finance4Traders is to help traders get started by bringing them unbiased research and ideas. Since late 2005, I have been developing trading strategies on a personal basis. Not all of these models are suitable for me, but other investors or traders might find them useful. After all, people have different investment/trading goals and habits. Thus, Finance4Traders becomes a convenient platform to disseminate my work...(Read more about Finance4Traders)

Sunday, April 29, 2012

Adaptive Price Zone APZ - Backtest Results and Implementation Issues

Adaptive Price Zone APZ - Backtest Results and Implementation Issues 

Discusses basic issues and results when attempting to back-test the APZ indicator

Data: S&P500 Emini Futures
Futures Contract Rollover: Arbitrarily set on second Friday of every Mar, Jun, Sep and Dec
Period: 28 Dec 2008 - 31 Mar 2012 (Hourly Chart)
VBA Code: Method B of Code
Excel Version: 2010

Click here for background information, formula, calculation steps and the entire VBA code.

There are multiple variations on how to apply an indicator. I seek your understanding that the work done below are experiments and are for information purposes only.

Summary of Results 
Conventional application of the APZ (i.e. long at the lower boundary and short at the upper boundary in anticipation of price reversal) is found to be not profitable. However, the reverse is somewhat profitable (long when price exceeds upper boundary of APZ and vice versa), suggesting that this technical indicator and the applied trading rules have potential for real-life implementation with further tweaking to the application method (e.g. chart indicator based on hourly data, but trades are generated as and when the trading rules are met subsequently). 

Procedure in Brief
Pasted the code into Excel with changes made as per comments in code to direct application to ranges with input data (High, Low, Close columns). Screen Shot 1 shows the output (the last seven columns). The first value of some columns are error values as their formulas include reference to cells on the first row which are actually text headings, not numbers. However, calculations in subsequent rows are unaffected. 

Screen Shot 1

Detailed Findings and Results
Inputs - Band factor is set at 2, EMA period is set at 5

Summary of Trading Rules -

1) If Close at this hour is higher than the APZ upper limit at the end of the last hour, enter long at the end of this hour
1) If Close at this hour is lower than the APZ lower limit at the end of the last hour, enter long at the end of this hour


223.25 index points of profit (before transaction costs) were generated out of this strategy on 344 trades. Average return per trade is 0.65 points on a standard deviation of 21.34 points. Therefore, this strategy does not look statistically profitable. The success rate of this strategy is 39%, i.e. only 135 trades were profitable. The profit trajectory of this indicator and strategy is shown in Chart 1. 

Chart 1: Cumulative Profit of APZ and Applied Trading Rules

Conclusion
Contemporary price behavior for the S&P500 suggests that the APZ is more suited for use as a "trend" type indicator, rather than a "price reversion" indicator as I have always thought. The key risk is that we cannot be certain that the behaviour of the APZ indicator versus the S&P500 will remain constant in the future. Under certain regimes, the APZ may behave as a price reversion indicator which would require the inversion of the above trading rules.

Further research can be in the application of this model in finer time granularity.

Any suggestions or comments are welcome.


Like what you have just read? Digg it or Tip'd it.
The objective of Finance4Traders is to help traders get started by bringing them unbiased research and ideas. Since late 2005, I have been developing trading strategies on a personal basis. Not all of these models are suitable for me, but other investors or traders might find them useful. After all, people have different investment/trading goals and habits. Thus, Finance4Traders becomes a convenient platform to disseminate my work...(Read more about Finance4Traders)

Saturday, April 28, 2012

Accumulation/Distribution Line ADL - Backtest Results and Implementation Issues

Accumulation/Distribution Line (ADL) - Backtest Results and Implementation Issues
Discusses basic issues and results when attempting to back-test the ADL line indicator

Data: S&P500 Emini Futures
Futures Contract Rollover: Arbitrarily set on second Friday of every Mar, Jun, Sep and Dec
Period: 28 Dec 2008 - 31 Mar 2012 (Hourly Chart)
VBA Code: Method B of Code
Excel Version: 2010

Click here for background information, formula, calculation steps and the entire VBA code.

There are multiple variations on how to apply an indicator. I seek your understanding that the work done below are experiments and are for information purposes only.

Summary of Results 
A naive strategy produced profitable results without accounting for transactions costs. Further research is necessary to create expected returns that remain positive after trading costs.

Procedure in Brief
Pasted the code into Excel with changes made as per comments in code to direct application to ranges with input data (High, Low, Close columns). Screen Shot 1 shows the output (the last three columns)

Screen Shot 1

Detailed Findings and Results
1) Conventional implementations of the ADL line suggests that divergence between ADL and prices are meaningful. However, it is difficult to judge divergence based on indicator and price levels alone. 

In my sample period, the ADL line, like price data, is non-stationary. Simply put, the ADL does not fluctuate around a constant mean. Otherwise, I simply did not use enough data to demonstrate the stationarity of the ADL line. Therefore, the ADL line in its raw form may not be easy to interpret. 

Chart 1: ADL line versus S&P 500

2) I tried rescaling the data using the formula -

Adjusted Close = (Close - Low of entire period) / (High of entire period - Low of entire period)
Adjusted ADL = (ADL - ADL Low of entire period) / (ADL High of entire period - ADL Low of entire period)
Chart 2 shows how the rescaled data looks like

Chart 2

Again, there is no meaningful interpretation at first glance. Furthermore, in real life implementation, there is no way of knowing the low and high of the entire period, including past, current and future moments in time.

3) Finally, I resorted to measuring the change in

I used the following simple trading rule

A) Calculate the percentage change in price at the end of each hour
B) Calculate the percentage change in ADL at the end of each hour
C) Calculate Percentage Change in ADL - Percentage Change in Price
D) If Percentage Change in ADL is higher than Percentage Change in Price, Long (in the next hour)
E) If Percentage Change in ADL is lower than Percentage Change in Price, Short (in the next hour)
F) If Percentage Change in ADL is equal to Percentage Change in Price, Maintain Position (in the next hour)

Conclusion
Unadjusted for slippage and transaction costs, my simple trading rule above generated 9,838 trades over a three year plus period and 601 index points per contract of profit. Chart 3 shows the cumulative profit of this strategy (without transaction costs).

Chart 3: Cumulative Gross Profit

However, the sure number of trades suggest that transaction costs will be high. As such, practical implementation will be a challenge. The breakeven level requires each trade to have a transaction cost of at most 0.061 index points (601 divided by 9838).

Further research can be in the modification of trading rules, such as enter into a long or short position only if the positive or negative divergences are sufficiently large.

Any suggestion or comments are welcome.



Like what you have just read? Digg it or Tip'd it.
The objective of Finance4Traders is to help traders get started by bringing them unbiased research and ideas. Since late 2005, I have been developing trading strategies on a personal basis. Not all of these models are suitable for me, but other investors or traders might find them useful. After all, people have different investment/trading goals and habits. Thus, Finance4Traders becomes a convenient platform to disseminate my work...(Read more about Finance4Traders)

Tuesday, June 30, 2009

Continued Fractions and the Modified Lentz's Method

This articles explains how to evaluate continued fractions and offers VBA code for Excel implementation

Continued fractions are of the form below



Continued fractions can be used to express certain numbers, such as π. They are also used in calculating bessel functions of fractional orders. A general method to evaluate continued functions is known as the modified Lentz's method.

The algorithm is consists of the following steps adapted from Press et. al.
  1. f0=b0. If f0=0 then let f0=10-30 or an extremely small value ≈ 0.
  2. C0=f0
  3. D0=0
  4. For i=1 to a pre-determined number of iterations, e.g. 10000.
    Di=bi+aiDi-1. If Di=0, let Di=10-30 or an extremely small value ≈ 0.
    Ci=bi+ai/Ci-1. If Ci=0, let Ci=10-30 or an extremely small value ≈ 0.
    Di=1/Di
    Chgi=CiDi
    fi=fi-1Chgi
  5. Exit when |Chgi-1| is smaller than a specified threshold.
These steps assume that you should stop when the change in f(x) becomes sufficiently small. By iterating the above twice, it becomes obvious how the algorithm works
The VBA implementation of the algorithm is as follows

'Declare your variables
Dim anow As Double, bnow As Double
Dim achange As Double, bchange As Double
Dim Cnow As Double, Dnow As Double
Dim fnow As Double, n As Long, Chgnow As Double
Dim small1 As Double, stop1 As Double
Dim answer As Range

'Set your variables
anow = 1
bnow = 2
achange = 1
bchange = 1
n = 9999
small1 = 10 ^ -30
stop1 = 10 ^ -15
Set answer = Range("B3")

'Start iterating
If bnow = 0 Then
fnow = small1
Else
fnow = bnow
End If
Cnow = fnow
Dnow = 0

For i = 1 To n
anow = anow + achange
bnow = bnow + bchange
Dnow = anow * Dnow + bnow
If Dnow = 0 Then Dnow = small1
Cnow = anow / Cnow + bnow
If Cnow = 0 Then Cnow = small1
Dnow = 1 / Dnow
Chgnow = Cnow * Dnow
fnow = fnow * Chgnow
If Abs(Chgnow - 1) <>
answer.Value = fnow
End
End If
Next i
answer.Value = fnow
End Sub

The code above is also adpated from Press et. al. However, it assumes that ai and bi will increase by 1 for each iteration.

References
Numerical Recipes The Art of Scientific Computing 3ed
William H. Press, Saul, A. Teukolsky, William T. Vetterling and Brian P. Flannery 2007
Cambridge University Press


Like what you have just read? Digg it or Tip'd it.
The objective of Finance4Traders is to help traders get started by bringing them unbiased research and ideas. Since late 2005, I have been developing trading strategies on a personal basis. Not all of these models are suitable for me, but other investors or traders might find them useful. After all, people have different investment/trading goals and habits. Thus, Finance4Traders becomes a convenient platform to disseminate my work...(Read more about Finance4Traders)

Time Series Analysis: Univariate and Multivariate Distributions

Introductory Concepts in Time Series Analysis
A time series refers to a set of data that is ordered by time. Price, volume and return data are three examples of time series. Time series can be discrete or continuous. In a discrete series, the time interval between each observation is an integer value. Continuous series are ordered by real numbers, the entire set of numbers that form the number line and need not necessarily refer to integers.



In the example above, we let x refer to the entire time series of stock prices and x can have many different values for its subscript i to refer to each individual observation in the time series. In this case, x0 refers to the price today of $1.01. A single price is an observation. Strictly speaking, only xi before x0 are the realized observations, i.e. the historic prices.

Univariate and Multivariate Distributions and Time Series
When analyzing financial data, we often make comparisons involving more than one variable across time. When trading stocks, we may consider key information such as historical return, volume, dividend payout, profitability, sales growth etc. When a stock shows positive characteristics such as a low price-earnings ratio or strong historical price growth on high volume, we are more likely than not to expect positive future returns and buy into the stock.

Using terms borrowed from statistics and probability, we might be unknowningly making the assumption that the probability of a stock having a positive future return is greater than 50% given that its historical returns is more than 10% a year and its current profit growth is more than 20% annually. In mathematical notation, we may be assuming the following:

P[Future Return>0%|(Historical Return>10%, Current Profit Growth>20%)]>50%

If we are indeed making such assumptions, we must then believe that the future return of a stock given other information may take on multiple values with different probabilities. E.g.

P(Future Return = 5%|certain information=x) = 30%
P(Future Return = 10%|certain information=x)=15%
....

, where we let certain information and x be variables we use in our analysis such as profit growth =x% or volume =x lots traded etc.

The above are known as conditional probabilities. If we know the probability of observing certain information = x, P(certain information=x) = y%, we can convert these probabilities to joint probabilities using Bayes' rule.

P(A and B) = P (A|B) x P(B)

If we were to download 100 years of data for the Dow Jones Industrial Average and calculate the monthly return, we might observe the following univariate distribution.



On the other hand, we can calculate the returns in the past one month and in the next one month for every month of data we have to obtain the following possible distribution, which looks like a cone. Basically, it assigns a certain probability to every possible combination of current and future returns.



Thus it becomes apparent that by analyzing a set of variables to predict future return, we are inherently making probabilistic assumptions of future returns against available information. As such, we should shift our perspective of statistical distributions from a purely univariate case to a multivariate situation when studying related financial data.

The univarate case applies when the data we study has no relationship with each other. In the example above, the univariate distribution of monthly returns will be sufficient to tell us how much return we can expect in any month if we believe that historical returns do not affect future returns. If historical return share no relationship with future return, the probability of future return being a certain value x% will be the same regardless of historical return. If that is really the case, the multivariate distribution will be misleading. Hence, your chosen variables will determine your probability distribution which in turn affects your decision making process.

In reality, multivariate time series occur when we observe multiple related variables at the same point in time. An example will be price and volume. At time, t=0, you observe both the particular price and volume traded – 2 variables at the same time. If you assume that your series can go no more detailed than one day at a time, you can grudgingly argue that the open, high, low and closing prices are four variables observed at the same time. The crux of the issue is whether you correctly choose to include or exclude multiple variables in your analysis, to record an appropriate time series.

The distinction between these two time series is not trivial. Suppose you have been observing daily prices for a long time and you know that observing a price of $1.00 today gives you a 5% chance of observing a price of $1.20 tomorrow. Another person who observes both price and volume, might give only a 3% chance of observing a price of $1.20 tomorrow if today’s volume is 1000 shares traded.

Parametric Distributions
In practice, tabulating raw data might yield clumsy distributions that are not useful such as in the chart below.



In the case above, you will have dififculty inferring the probability of having a return of less than -10% or 14% or more than 15%. This happens when you have insufficient data or data that is not representative of what you believe to be the true distribution. To handle such situations, practitioners either apply smoothing techniques to their data or assume a parametic distribution such as the normal distribution or the student t distribution in their analysis.


Like what you have just read? Digg it or Tip'd it.
The objective of Finance4Traders is to help traders get started by bringing them unbiased research and ideas. Since late 2005, I have been developing trading strategies on a personal basis. Not all of these models are suitable for me, but other investors or traders might find them useful. After all, people have different investment/trading goals and habits. Thus, Finance4Traders becomes a convenient platform to disseminate my work...(Read more about Finance4Traders)

Site Updates

Hi (to whoever is reading this),

A big welcome for finding my site. This post is a running list of updates and work done on this site, inclusive of any on-going projects so that visitors including you can have a better understanding of the things I am doing.

11 July 09
Have not updated this journal for some time. Basically, I spent the last 2 weeks revamping the site layout. I tore the built-in template apart and redid everything from scratch. The benefit of literally reinventing the wheel is that I now know exactly how my template works and have done quite a few customisations to make it for pleasing to the eye.

I also wrote VBA functions and routines for each of the technical indicators featured here. Now all technical indicators here come with VBA code for your convenient implementation.

Two NEW articles have also been added for those who are more interesting in quant stuff. One of the articles is about multivariate distributions and why we should use them. Another is about analyzing technical indicators in the frequency domain.

26 June 09
Spent close to half a day trying to figure out a way to do web queries better in VBA. Turns out that it is much easier and simpler than I expected.

25 June 09
Did up an article on filtering. Interesting view on how you can test the how responsive or volatile some indicators are. Also did a less intensive article on recommended Excel programming practices. Hopefully someone finds it useful in increasing his productivity.

24 June 09.

I did some more posts on technical indicators and got to this indicator that went into signal processing. As stuffing everything about signals, filtering and hilbert transformation into a single post seems too ambitious, I opened up the quant section and did a few introductory stubs, while I tidy up my materials on filtering. The good thing about writing posts as you do your work is that it keeps you organized.

Sent a spreadsheet on VAR to a visitor earlier today.

23 June 09.

I have been writing about nothing but technical indicators for the last three days now. Why? I am currently on a mini-project to back test as many indicators as I can from a list of about 70 to 80 indicators. Once I am done with the back-tests, I will release them on this site.

Before I can do any actual backtesting, it came to me that I should spend time reading about technical indicators. Hence, I am posting them up as I read. The pace is slow because not all websites or books out there provide the exact formulas. Instead of explaining the steps involved in calculation, most websites give a brief explain what the indicator attempts to do and either continue with an example of using it to trade or recommend you to buy a trading tool or software. Over here, I do the reverse, I am brief about what the indicator does, but I go heavy into the formulas so that readers can implement these indicators themselves.

If you are serious about backtesting, you have know what drives a particular indicator. Hence, this is my addition to existing internet literature, a depository of 'how-to-calculate's - Anyone who wishes to know how an indicator is computed can come here. Some of them like the Fisher Transform or the Darvas Box are quite complex and a few websites do too brief a job explaining them.

The reason why I borther to do backtesting of technical indicators is because I intend to incorporate technical indicators in a genetic programming strategy that I will work on some time in the future.

22 June 09

I tried to do some marketing of my site on the 22nd by signing up to several forums and giving my 2 cents worth as a forum participant. Hey, I was not spamming ok! I diligently read the posts that other people write, respond to their comments with some of my own thoughts. Only if there are related topics will I send them to Finance4Traders. I only started one thread on possible unfavorable practices out there in the industry, after reading about all those angry customers who were disappointed with their brokers.

Yours sincerely,

Finance4Traders


Like what you have just read? Digg it or Tip'd it.
The objective of Finance4Traders is to help traders get started by bringing them unbiased research and ideas. Since late 2005, I have been developing trading strategies on a personal basis. Not all of these models are suitable for me, but other investors or traders might find them useful. After all, people have different investment/trading goals and habits. Thus, Finance4Traders becomes a convenient platform to disseminate my work...(Read more about Finance4Traders)

Signal Processing in Trading

Financial time series such as price data are in general digital signals. They can only take on a set range of values and can only be measured at discrete time intervals. Even tick data is digital. It is merely sampled at very small time intervals, i.e. the machine records the prevailing quote every millisecond and only shows you those that have changed.

Visit HERE for introductory information on signal processing and the terminology used here.

In fact any time series can be viewed as the summation of an infinite number of sine and cosine waves of varying amplitudes, phases and frequencies even if it is not periodic. A technique to break down a time series to its component sinusoidal waves is known as the Fourier transform. From this perspective, I assert that any particular financial time series may be characterised by waves of certain dominant frequencies. Understanding how a particular technical indicator and its parameters interact with these dominant frequencies can help the trader understand if his chosen indicator is extracting the information he or she wants.

Suppose the market goes through a mini cycle every 2 weeks, a 200 week moving average will never be able to identify the peaks and troughs of this mini cycle. The design of indicators may limit its ability to capture frequency dynamics within a certain bandwidth only. For example, a n period simple moving average will not be able to capture the cyclicity of a n period cycle as well as that of integer multiples of n period cycles.

An article HERE explains fitlers in trading and how they are classified within the time domain. The current article that you are reading elaborates on filters in the frequency domain. Filters and signals can be analyzed within the frequency or time/temproral domain.

In the frequency domain, filters are typically classified into low-band pass and high-band pass filters. A low-band pass filter tends to capture the low frequency dynamics of a signal, while a high-band pass filter captures the high frequency components of a signal. The following sections will help you understand what I mean.

Frequency Domain
The process of classifying filters in the frequency domain begins by feeding a signal xt of a known frequency into the filter.

xt=ei2πft

Using the Euler's identity, ei2πft actually equals cos(2πft)+isin(2πft) which produces signals like below, depending on the frequency of the signal. [This article here explains more about the role of the Euler's identity in signal processing.]



Using the 3 period simple moving average indicator in our previous article on filters and technical indicators, we obtain the following.


The function H(f) is the frequency response function or the transfer function of the signal and has the general form.

H(f) can be further broken into two parts - the gain function G(f) and phase angle θ as shown below.


In the case of the 3 period simple moving average, the gain function G(f) and phase angle of the filter θ are as follows,

The G(f) and θ that I work out above might not be accurate. While, I have retained the meaning behind these functions, I have not had them proof-read and they are for illustrative purpose only. If we fit H(f) and its component G(f) and θ back into the original filter


Recall that the original signal xt=ei2πft or xt=cos(2πft)+isin(2πft). Hence, we now know that the three period simple moving average changes the the original signal by G(f) and introduces a phase shift of θf.

A high-band pass filter will have a G(f) whose magnitude is close to 1 at higher frequencies and a G(f) of magnitude approximately 0 at lower frequencies. The reverse applies to low-band pass filters. The magnitude of G(f) is calculated as √[(real coefficient)2+(imaginery coefficient)2]. The real and imaginery coefficients refer to the respective components of the G(f) function.

Intuitively, the product of 2 complex numbers (a+bi) and (c+di) is equal to (ac-bd)+(bc+ad)i. The magnitude of (ac-bd)+(bc+ad)i is equal to the product of the magnitudes of (a+bi) and (c+di). Recall that a time series can be viewed as a combination of signals with different frequencies. Hence, the outputs of a filter whose gain function G(f) has a magnitude of 1 at frequency f best reflect the component signal of that frequency. If θf is not zero, this means that the indicator shifts the phase of the input signal and and lags the input signal by θf/2π of a cycle.

The chart below is called a gain diagram and it shows the magnitude of the gain function of a 3 period simple moving average aginst the signal xt=ei2πft at varying frequencies. As can be observed, the gain function is approximately 0 at frequencies of 0.333 and 0.666, meaning that this indicator is unable to sufficiently reflect the dynamics of a 3 period and 6 period cycle.



Conclusion
While it seems like overkill to go through such complicated mathematics just to show that there is little utility in using a 3 period moving average in a 3 period cycle, the method described here can be applied to test other indicators for their ability to capture market cycles. An example is the exponential moving average whose gain diagram looks like the below. The exponential moving average due to its design is able to capture at least some of the dynamics of a wide range of frequencies and is less limited by its averaging period.



References

An Introduction to Wavelets and Other Filtering Methods in Finance and Economics by Ramazan Gencay, Faruk Selcuk and Brandon Whitcher


Like what you have just read? Digg it or Tip'd it.
The objective of Finance4Traders is to help traders get started by bringing them unbiased research and ideas. Since late 2005, I have been developing trading strategies on a personal basis. Not all of these models are suitable for me, but other investors or traders might find them useful. After all, people have different investment/trading goals and habits. Thus, Finance4Traders becomes a convenient platform to disseminate my work...(Read more about Finance4Traders)

Understanding Technical Indicators: Filters in Finance

One of the first few questions that I ask myself is what are technical indicators? Are they just a jumble of equations? In fact, most technical indicators are filters. A filter can be viewed as an equation that transforms a time series to another form, such as how moving averages are supposed to smooth a time series. The objective of a filter is to identify and extract certain features, such as the trend and cycles, from a time series. Filters are commonly used in most forms of analysis, such as in engineering, signals processing, image recognition, economics and finance. Hence, I cannot do justice without doing an article on filters. Even some of the more sophisticated models rely on effective filtering to work.

What a Filter does

In simple terms, a filter changes x to a different series y because you think that y makes it easier for you to analyze x, e.g. observe the trend in x. You can visualize this operation using the diagram below.



Filters can be classified into linear and non-linear types. There are other classifications such as infinite/finite impulse response and causal/non-causal filters which will be elaborated later. Whether an equation is linear or nonlinear is a mathematical construct. You can view the more rigorous explanations at the references below. Intuitively, a linear equation must obey the following rules

[Equations are typically represented by functions. For instance, f(x)=1 can refer to the equationx+2=1 or g(xy)=20 can refer to xy-9=20.]


Nonlinear equations do not obey the two rules above. The intuitive explanation of a nonlinear equation is one where changes in its input do not lead to a proportionate change in its output. An example of a nonlinear equation will be x2+x=2. A 50% change in x to 1.5 will cause x2+x=3.75, a 87.5% change.

Hence, it becomes obvious that x can be changed or mapped to y via functions that are either linear or nonlinear. The simple moving average, such as SMA3 below is an example of a linear filter, using n to denote the filter period or the number of historical periods this indicator averages.



The SMA3 of 1,2 and 3 is 2. If we increase 1, 2 and 3 respectively by 50% to 1.5, 3 and 4.5, SMA3 becomes 3, an equivalent increase of 50%. An example of a nonlinear function is a neural network whose explanation requires a separate post in itself.

Causal filters utilize the past and current values in mapping inputs to their outputs, like most technical indicators. Non-causal filters utilize both past and future values. An example will be a centered moving average.



As future values are unobservable in real life, non-causal filters are more for analyzing and understanding current data than for predicting future values.

Types of Filter outputs

Filters are also classified based on their outputs into finite and infinite impulse response filters. An impulse response is a filter’s output to an unit impulse signal. Consider a “magical” option that costs $1 only on today and nothing on all other days, both future and current. Such a price sequence is called an unit impulse signal. Once the only non-zero input of 1 is entered into an infinite impulse response filter, this filter’s response or output will remain greater than 0 infinitely. An example of such a linear filter is the exponential moving average, EMA.

For a 3 period filter equivalent, or n=3, the EMA alpha = 2/(n+1) = 0.5



Suppose xo=1 and xi=0 for all other values of i. EMA will be 0 before x0. The EMA at x0 will be 0.5 x 0.50 x 1=0.5. For the next 10 days, x1 to x10 will be 0. However, EMA at x10 will be 0.5 x 0.510 x 1 = 0.000488. EMA after x0 will never be 0. The past filter outputs will always feedback to the current output. The simple moving average on the other hand is a finite impulse response filter. If filter period is 3, the SMA at x3 will be 0. Hence, the SMA will change abruptly when an older, but large observation is removed from the filter period, while the EMA phases out the older inputs gradually. Furthermore, the EMA is more responsive to the newer observations than the SMA. (See Chart below).


Conclusion

The key learning point of this article is to show that technical indicators are filters that extract features from a time series. It introduces different types of filters and illustrates how an unit impulse signal can be used to show the responsiveness and volatility of different technical studies.

However, a time series can also be represented as the sum of multiple oscillations with different frequencies and amplitudes. As the older values are never entirely excluded from the EMA, it is able to capture the effects of price patterns or cycle peaks and troughs that occur at higher frequencies or at intervals longer than the specified filter period. More will be elaborated on analyzing time series and filters as waves and signals in a separate article.

References

Gencay, Selcuk and Whitcher, 2002, An Introduction to Wavelets and Other Filtering Methods in Finance and Economics, Academic Press
An excellent book on wavelets analysis and filtering

A much more rigorous treatment of linear transformation


Like what you have just read? Digg it or Tip'd it.
The objective of Finance4Traders is to help traders get started by bringing them unbiased research and ideas. Since late 2005, I have been developing trading strategies on a personal basis. Not all of these models are suitable for me, but other investors or traders might find them useful. After all, people have different investment/trading goals and habits. Thus, Finance4Traders becomes a convenient platform to disseminate my work...(Read more about Finance4Traders)

Quick Basic Info on Math and Physics

This post is where all basic information is stored so that you can easily understand what I am talking about.

Introduction to Signals

1. A signal is a sequence of numbers

2. A signal consists is measured along two dimensions – displacement and time.

3. An analogue signal is a continuous signal varying in continuous time. Its displacement (from 0) and time can take on real values*. At each infinitely small interval in time, there is a displacement that can take on a value of infinite number of decimal places. Chart 1 on the right is an example of an analogue signal. Sound is an example of an analogue signal.

4. A digital signal has discrete displacements at discrete time intervals. Its values are limited to a given set and are observed at fixed intervals in time.

5. A signal can be discrete in amplitude, but continuous in time, or continuous in amplitude but discrete in time.

References

Digital Signal Processing: DSP & Applications
by Day Stranneby, 2001

Introduction to Oscillations

1. A cycle is a complete oscillation about an equilibrium position, 0. In chart 1, the signal completes one cycle somewhere between time 5 and 6.

2. The period of an oscillator is the amount of time needed to complete one cycle.

3. The frequency of an oscillator is the number of complete cycles per time interval. It is the inverse of period or (1/period).

4. The amplitude of an oscillator is the maximum displacement about the equilibrium position, 0.

*Intuitively, real values or numbers are not discrete and can exist in infinitely small intervals.

Introduction to Complex Numbers

1. A complex number has the form x+yi, where x is the real coefficient and y is the imaginery coefficient of the complex number. i is defined as the square root of -1 or √-1. Thus all real numbers have an imaginery coefficient of 0.

2. Complex numbers were originally created to solve certain polynomial functions. Consider the equation x2+1=0, whose solution is √-1 - a complex number.

3. Complex numbers are always plotted on the complex plane or in an argand diagram with the y axis being the imaginary coefficient and the x axis being the real coefficient.

3. In signal processing, complex numbers allow signals to be represented in a coordinate system, where the signal at any one point in time is represented by a real and imaginery component. Such representation allows for easy manipulation of 'complex frequencies' as we shall see later.

Suppose you have a sine function as a signal, y=sin(2πft), where f is the frequency of your signal. You will observe the following signal if frequency = 1, or 1 cycle is completed within 1 time interval.



As the signal is repetitive, the same signal can be represented via the argand diagram below. The radius of the circle represents the signal amplitude, while the angle θ theta = 2πft.

4. Upon closer study of the diagram above, we will realize that the Euler's identity, eiθ=cosθ+isinθ, is another representation of complex numbers. Note that cosθ=sin(θ+π/2).

5. Suppose we have a complex frequency f=a+ib so that we have a signal represented by est.

est=e(a+ib)t
=eateibt
=eat[cos(bt)+isin(bt)]

We know from previously that cos(bt)+isin(bt) creates a signal of constant frequency on the real plane like for instance, either of the two signals below.


However, multiplying [cos(bt)+isin(bt)] by eat creates a signal with varying frequency over time depending on the value of a such as the example below.



References

Digital Signal Processing Fundamentals by Ashfaq A Khan


Like what you have just read? Digg it or Tip'd it.
The objective of Finance4Traders is to help traders get started by bringing them unbiased research and ideas. Since late 2005, I have been developing trading strategies on a personal basis. Not all of these models are suitable for me, but other investors or traders might find them useful. After all, people have different investment/trading goals and habits. Thus, Finance4Traders becomes a convenient platform to disseminate my work...(Read more about Finance4Traders)

Fisher Transform (VBA Code)

The code below provides a convenient sub routine to perform the Fisher transform. The FT_1 sub routine uses the high and low prices of your dataset as its inputs. You will also need to specify a number n representing the length of the normalising period in the transformation process. The sub routine produces 5 columns of outputs - the median price, normalised median price, smoothed normalised median price, Fisher transform and smoothed Fisher transform.

The exact steps of the Fisher transform and the meaning of the outputs can be obtained from here, where a more detailed explanation of the Fisher transform is provided. This article focuses on the VBA code for this indicator.

Sub Runthis()
Dim high As Range, low As Range
Dim output As Range, n As Long

Set high = Range("C2:C11955")
Set low = Range("D2:D11955")
Set output = Range("H2:H11955")

n = 5 'number of historical periods to look at
'needed for certain indicators
FT_1 high, low, output, n
End Sub

Sub FT_1(high As Range, low As Range, output As Range, n As Long)
output(0, 1).Value = "Median Price"
high0 = high(1, 1).Address(False, False)
low0 = low(1, 1).Address(False, False)
output(1, 1).Value = "=(" & high0 & "+" & low0 & ")/2"
output(1, 1).Copy output
output(0, 2).Value = "Normalized Price"
rangen = Range(output(1, 1), output(n, 1)).Address(False, False)
TP = output(n, 1).Address(False, False)
output(n, 2).Value = "=(((" & TP & "-min(" & rangen & "))/(max(" & rangen & ")-min(" & rangen & ")))-0.5)*2"
output(n, 2).Copy output.Offset(0, 1)
output(0, 3).Value = "Smoothed Normalized Price"
SNPtoday = output(n + 1, 2).Address(False, False)
SNPyesterday = output(n, 3).Address(False, False)
output(n + 1, 3).Value = "=max(-0.9999,min(0.9999,(0.5*" & SNPtoday & "+0.5*" & SNPyesterday & ")))"
output(n + 1, 3).Copy output.Offset(0, 2)
SNPyesterday = output(n, 2).Address(False, False)
output(n + 1, 3).Value = "=max(-0.9999,min(0.9999,(0.5*" & SNPtoday & "+0.5*" & SNPyesterday & ")))"
output(0, 4).Value = "Fisher Transform"
SNP = output(n + 1, 3).Address(False, False)
output(n + 1, 4).Value = "=0.5*ln((1+" & SNP & ")/(1-" & SNP & "))"
output(n + 1, 4).Copy output.Offset(0, 3)
output(0, 5).Value = "Smoothed Fisher Transform"
FTtoday = output(n + 2, 4).Address(False, False)
FTyesterday = output(n + 1, 5).Address(False, False)
output(n + 2, 5).Value = "=0.5*" & FTtoday & "+0.5*" & FTyesterday
output(n + 2, 5).Copy output.Offset(0, 4)
FTyesterday = output(n + 1, 4).Address(False, False)
output(n + 2, 5).Value = "=0.5*" & FTtoday & "+0.5*" & FTyesterday
Range(output(1, 2), output(n - 1, 5)).Clear
Range(output(n, 3), output(n, 5)).Clear
output(n + 1, 5).Clear
End Sub

The code provided above is definitely not efficient and will be updated over time. If you have any suggestions, do drop a comment below.


Like what you have just read? Digg it or Tip'd it.
The objective of Finance4Traders is to help traders get started by bringing them unbiased research and ideas. Since late 2005, I have been developing trading strategies on a personal basis. Not all of these models are suitable for me, but other investors or traders might find them useful. After all, people have different investment/trading goals and habits. Thus, Finance4Traders becomes a convenient platform to disseminate my work...(Read more about Finance4Traders)

Average Directional Movement Rating

Average Directional Movement Rating ADR
Comes with formula, calculation steps and VBA code

Introduction
The average directional movement rating ADR is based on the average directional index ADX. You might want to read about the average directional index before proceeding further. The ADR is calculated as follows:

ADR=(current ADX + ADX k periods ago)/2

As such, ADR can be seen as an approximate of the average ADX over n periods. The crossover of ADR and ADX can be seen as a signal confirming the existing of the trend. ADX is a measure of the strength of a trend, not direction. In an up or down market, the ADR and ADX values are always positive. Therefore, these indicators should be used with other trend indicators to infer the direction of the market.

VBA Code
Method A uses functions, while Method B uses sub procedures to calculate ADR. Method B is faster and more flexible.

Method A
To calculate average directional movement rating, ADR, you will need the ADX custom function in your code, which in turn needs the following custom functions from the respective pages

DM function from directional movement
TR function from average true range
DMX function from directional movement index

In addition, you will need to have calculated ADX using Method A based on the steps provided in the page on average directional index. Below is the code for the custom function ADR.

'Insert the following into the AddUDF sub which you can obtain from any of the 'other pages listed above.
Application.MacroOptions macro:="ADR", _
Description:="Returns Average Directional Movement Rating" & Chr(10) & Chr(10) & _
"Select current ADX and ADX n periods ago", _
Category:="Technical Indicators"

'Insert below into the module
Public Function ADR(ADX, ADXn)
ADR = (ADX + ADXn) / 2
End Function

Once done, you can calculate ADR by entering "=ADR([current ADX], [ADX k periods ago])" into any cell.

Method B
Method B is much more convenient, with the intermediate steps calculated for you. To run Method B, you have to copy the Runthis sub of Method B from the page on Accumulation/Distribution line. You will run the ADR_1 sub from the Runthis sub.

However, you will still need the DM_1, WWMA_1, ATR_1, DMI_1, DMX_1, ADX_1 subs of Method B from the directional movement, Welles Wilder's moving average, average true range, directional movement indicator, directional movement index and average directional index pages respectively.

'Copy the following line into the Runthis sub
'Just before the line End Sub
'Disable all other macros that Runthis will call e.g. CLV, ADL, by
'marking them out as comments with single quotes
ADR_1 high, low, close1, output, n, k

'Insert this as a new sub
Sub ADR_1(high As Range, low As Range, close1 As Range, output As Range, n As Long, k As Long)
ADX_1 high, low, close1, output, n
ADX0 = output(4 + k, 10).Address(False, False)
ADX1 = output(4, 10).Address(False, False)
output(0, 11).Value = "ADR"
output(4 + k, 11).Value = "=(" & ADX0 & "+" & ADX1 & ")/2"
output(4 + k, 11).Copy output.Offset(0, 10)
Range(output(1, 11), output(3 + k, 11)).Clear
End Sub

Other References

http://www.marketvolume.com/technicalanalysis/adxr.asp


Like what you have just read? Digg it or Tip'd it.
The objective of Finance4Traders is to help traders get started by bringing them unbiased research and ideas. Since late 2005, I have been developing trading strategies on a personal basis. Not all of these models are suitable for me, but other investors or traders might find them useful. After all, people have different investment/trading goals and habits. Thus, Finance4Traders becomes a convenient platform to disseminate my work...(Read more about Finance4Traders)

Weighted Moving Average

Weighted Moving Average WMA
Comes with formula, calculation steps and VBA code

The weighted moving average is calculated by giving each lagging price a smaller weight. The weight decreases at a constant rate from n to 0.

WMA = [n x Pricet + (n-1) x Pricet-1 + … + 2 x Pricet-n+2 + Pricet-n+1] / (n + (n-1) + …+ 2 + 1)

The divisor (n + (n-1) + …+ 2 + 1) can be calculated using the formula [n x (n+1)] / 2.

VBA Code
Two seperate methods are presented below.

Method A
To compute the weighted moving average of a series, enter into any cell "=WMA([n periods of your series])" after you have pasted the code below. The AddUDF sub routine adds your functions to a custom category called "Technical Indicators".

Sub AddUDF()
Application.MacroOptions macro:="WMA", _
Description:="Returns the Weighted Moving Average" & Chr(10) & Chr(10) & _
"Select n periods of prices", _
Category:="Technical Indicators"
End Sub

Public Function WMA(close_)
total1 = 0
n = WorksheetFunction.Count(close_)
divisor = (n * (n + 1)) / 2
For a = 1 To n
total1 = total1 + close_(a, 1) * a
Next a
WMA = total1 / divisor
End Function

Method B
In general, Method B is preferred over Method Afor large datasets. It is much more faster.

Sub Runthis()
Dim close1 As Range, output as Range, n As Long

Set close1 = Range("E2:E11955")
Set output = Range("H2:H11955")

n = 5 'number of historical periods to look at
'needed for certain indicators
WMA_1 close1, output, n
End Sub

Sub WMA_1(close1 As Range, output As Range, n As Long)
For a = 1 To n
output(a, 1).Value = a
Next a
numrange = Range(output(1, 1), output(n, 1)).Address
pricerange = Range(close1(1, 1), close1(n, 1)).Address(False, False)
output(n, 2).Value = "=sumproduct(" & numrange & "," & pricerange & ")/(" & n & "*(" & n & "+1)/2)"
output(n, 2).Copy output.Offset(0, 1)
Range(output(1, 2), output(n - 1, 2)).Clear
End Sub


Like what you have just read? Digg it or Tip'd it.
The objective of Finance4Traders is to help traders get started by bringing them unbiased research and ideas. Since late 2005, I have been developing trading strategies on a personal basis. Not all of these models are suitable for me, but other investors or traders might find them useful. After all, people have different investment/trading goals and habits. Thus, Finance4Traders becomes a convenient platform to disseminate my work...(Read more about Finance4Traders)

Directional Movement Index

Directional Movement Index DMX
Comes with formula, calculation steps and VBA code

Introduction
The directional movement index, DMX is derived from the positive and negative directional movement indicators, +DMI and -DMI. It is calculated as follows.

DMX = Absolute of [+DMI - (-DMI)] / [+DMI + (-DMI)]

The +DMI is the Welles Wilder's moving average of +DM over n days divided by the average true range for n days. -DMI is calculated in the same way. +DM refers to positive directional movement. Intuitively, it can be thought of as the change in the day's high. On the other hand, -DM or negative directional movement refers to the change in the day's low.

The directional movement index or DMX normalizes the absolute difference in DMI against the sum of +DMI and -DMI. It shows the strength in the current trend net of both upwards and downwards movement. If + DMI is similar in value to the -DMI, the value of DX will be small reflecting a weak trend. However, DX strictly tells nothing about the direction, only the strength of the trend because it is always an absolute value.

VBA Code
Method A uses functions, while Method B uses sub procedures to calculate DMI. Method B is faster and more flexible.

Method A
To calculate +/-DMX, you need the following custom functions from the respective pages

DM function from directional movement
TR function from average true range

Calculate the following.
  1. +DM and -DM, "=DM([current high], [current low], [previous high], [previous low])". Select the cell and the neigbouring cell right next to it, press F2 and Crtl+Shift+Enter. DM is an array function, returning both +DM and -DM
  2. WWMA for +/- DM by entering in another cell "=WWMA([previous WWMA],[current +/-DM],[n])".
  3. True range, "=TR([high],[low],[previous close])"
  4. Average true range, "=WWMA([previous WWMA],[current TR],[n])"
  5. +/-DMI=output from step 2 /output from step 4
  6. DMX, "=DMX([+DMI],[-DMI])
'Paste this code into your ThisWorkBook code window in VBA. Right Click This WorkBook in Project Explorer and click View Code.
Private Sub Workbook_Open()
AddUDF
End Sub

'The rest belong to any module
Sub AddUDF()
'Tells Excel to includes these in list of functions, add descriptions to them and create a new category called Technical Indicators.
Application.MacroOptions macro:="DMX", _
Description:="Returns Directional Movement Index" & Chr(10) & Chr(10) & _
"Select positive and negative directional movement indicators", _
Category:="Technical Indicators"
End Sub

Public Function DMX(PosDMI, NegDMI)
DMX = Abs(PosDMI - NegDMI) / (PosDMI + NegDMI)
End Function

Method B
Method B offers the benefit of not having to the intermediate outputs, such as DMI yourself. It does everything for you. To run Method B, you have to copy the Runthis sub of Method B from the page on Accumulation/Distribution line. You will run the DMX_1 sub from the Runthis sub.

You will also need the DMI_1, DM_1, WWMA_1, ATR_1 subs of Method B from the directional movement indicator, directional movement, Welles Wilder's moving average and the average true range pages respectively.

'Copy the following line into the Runthis sub
'Just before the line End Sub
'Disable all other macros that Runthis will call e.g. CLV, ADL, by
'marking them out as comments with single quotes
DMX_1 high, low, close1, output, n

'Insert this as a new sub
Sub DMX_1(high As Range, low As Range, close1 As Range, output As Range, n As Long)
DMI_1 high, low, close1, output, n
output(0, 9).Value = "DMX"
PosDMI = output(3, 7).Address(False, False)
NegDMI = output(3, 8).Address(False, False)
output(3, 9).Value = "=abs(" & PosDMI & "-" & NegDMI & ")/(" & PosDMI & "+" & NegDMI & ")"
output(3, 9).Copy output.Offset(0, 8)
Range(output(1, 9), output(2, 9)).Clear
End Sub

Other References

http://fxtrade.oanda.com/learn/graphs/indicators/adx.shtml


Like what you have just read? Digg it or Tip'd it.
The objective of Finance4Traders is to help traders get started by bringing them unbiased research and ideas. Since late 2005, I have been developing trading strategies on a personal basis. Not all of these models are suitable for me, but other investors or traders might find them useful. After all, people have different investment/trading goals and habits. Thus, Finance4Traders becomes a convenient platform to disseminate my work...(Read more about Finance4Traders)

Directional Movement Indicator

Directional Movement Indicator DMI
Comes with formula, calculation steps and VBA code

Introduction
The directional movement indicator DMI is the directional movement smoothed by the Welles Wilder's moving average normalized by the average true range. Like directional movement, the DMI is made of two studies - Positive DMI and Negative DMI or +DMI and -DMI respectively. Both +DMI and -DMI are behave like indices and are positive numbers. The +DMI and -DMI measures the strength of the up and the down trends respectively.

+DMI=WWMA(+DM,n) / ATR(n)
-DMI=WWMA(-DM,n) / ATR(n)

, where WWMA(DM,n) refers to a n period Welles Wilder's moving average of the DM and ATR(n) refers to a n day average true range.

Smoothing the DM and dividing the result by average range allows the DMI to be compared across different trading ranges and hence, across time. On the other hand, an upward sloping WWMA of the DMI alone may be inflated by a spike in trading ranges.

VBA Code
Method A uses functions, while Method B uses sub procedures to calculate DMI. Method B is faster and more flexible.

Method A
To calculate +/-DMI, insert into a module the DM function from the page on directional movement, WWMA function from the page on Welles Wilder's moving average and TR function from the page on average true range.
  1. Calculate +DM and -DM, by entering into any cell "=DM([current high], [current low], [previous high], [previous low])". Select the cell and the neigbouring cell right next to it, press F2 and Crtl+Shift+Enter.
  2. Calculate WWMA for +/- DM by entering in another cell "=WWMA([previous WWMA],[current +/-DM],[n])".
  3. Calculate true range, "=TR([high],[low],[previous close])".
  4. Calculate average true range "=WWMA([previous WWMA],[current TR],[n])".
  5. +/-DMI = ouput from step 2 / output from step 4
Method B
Method B is more convenient as it does not require you to remember the computation steps. To run Method B, you have to copy the Runthis sub of Method B from the page on Accumulation/Distribution line. You will run the DMI_1 sub from the Runthis sub.

You will need the DM_1, WWMA_1, ATR_1 subs of Method B from the directional movement, Welles Wilder's moving average and the average true range pages respectively.

'Copy the following line into the Runthis sub
'Just before the line End Sub
'Disable all other macros that Runthis will call e.g. CLV, ADL, by
'marking them out as comments with single quotes
DMI_1 high, low, close1, output, n

'Insert this as a new sub
Sub DMI_1(high As Range, low As Range, close1 As Range, output As Range, n As Long)
DM_1 high, low, output
WWMA_1 output, output.Offset(0, 2), n
WWMA_1 output.Offset(0, 1), output.Offset(0, 3), n
Range(output(2, 3), output(2, 4)).Copy output(3, 3)
Range(output(2, 3), output(2, 4)).Clear
ATR_1 high, low, close1, output.Offset(0, 4), n
output0 = output(3, 3).Address(False, False)
output1 = output(3, 4).Address(False, False)
output2 = output(3, 6).Address(False, False)
output(0, 7).Value = "Positive DMI"
output(3, 7).Value = "=" & output0 & "/" & output2
output(3, 7).Copy output.Offset(0, 6)
output(0, 8).Value = "Negative DMI"
output(3, 8).Value = "=" & output1 & "/" & output2
output(3, 8).Copy output.Offset(0, 7)
Range(output(1, 7), output(2, 8)).Clear
End Sub

Other References

http://fxtrade.oanda.com/learn/graphs/indicators/adx.shtml


Like what you have just read? Digg it or Tip'd it.
The objective of Finance4Traders is to help traders get started by bringing them unbiased research and ideas. Since late 2005, I have been developing trading strategies on a personal basis. Not all of these models are suitable for me, but other investors or traders might find them useful. After all, people have different investment/trading goals and habits. Thus, Finance4Traders becomes a convenient platform to disseminate my work...(Read more about Finance4Traders)