PureBytes Links
Trading Reference Links
|
Gordon, you are right ...
Below is the TS Cose ... previously posted by "run_for_your_life2003".
I do think this is very useful code ... I Almost got it translated... but
got hung up at one spot
The text below also includes commentary
Ara
>
> ----- Original Message -----
> From: "run_for_your_life2003" <run_for_your_life2003@xxxxxxxxx>
> To: <amibroker@xxxxxxxxxxxxxxx>
> Sent: Friday, September 19, 2003 5:13 PM
> Subject: [amibroker] AFL gurus-John Ehlers-Market Mode Strategies.
>
>
>
> I am trying to get this code converted to AFL are there any gurus
> who might be able to do the conversion???
>
> MARKET MODE STRATEGIES
>
> By
>
> John Ehlers
>
>
>
> INTRODUCTION
> Haven't you noticed that oscillators don't work in trending markets?
> Ever wonder why? Sometimes it is best to step back and take a
> philosophical look at why we do what we do. Some time back I
> discovered a general description of Random Walks1. As a result, I
> concluded that the market could be modeled as a combination of a
> Trend Mode and a Cycle Mode. This is not earth-shattering, nor at
> odds with some of the more modern observations of Chaos Theory. What
> is helpful is that the generalized partial differential equations
> that apply to these modes point directly to technical analysis
> indicators that can exploit them.
> I earlier promised you to show you what works. In this article I
> disclose two indicators you can program for each of the modes - and
> in fact help you identify the modes themselves. Just to save you
> time and disappointment, I thought it might be instructive to begin
> this article with a general discussion of momentum functions.
>
>
>
> MOMENTUM FUNCTIONS
> I can't begin to tell you how many hours I have wasted trying to get
> any indicator to give a signal just one bar sooner. Perhaps this
> brief description of momentum functions might spare you a similar
> fate.
>
> With reference to Figure 1, consider an input function as a ramp
> that starts at t=0. Momentum is the rate of change. So, in the
> second line, the rate of change of the ramp is shown as a step
> function. That is, to the left of t=0 the rate of change is zero. At
> t=0 the rate of change of the ramp jumps up to a constant value.
> Next, examining the momentum of the step function, we conclude that
> it is an impulse. An impulse can be pictured as a rectangle that is
> infinitely high and has zero width in such a way that the area
> within the rectangle is unity. The momentum of the step function
> initially is zero. At t=0 the step function jumps to a new value so
> that the rate of change is infinite. Also, at t=0 the step function
> has a zero rate of change at the new level to complete the back side
> of the rectangle, forming the impulse. The momentum of an impulse,
> seen in the bottom segment of Figure 1, is called a jerk. A jerk is
> a double impulse. The rate of change of the impulse consists of
> traversing up the front of the rectangle and then back down the back
> side of the rectangle. There are two truths about momentum functions
> that can be gleaned from the sequence shown in Figure 1.
>
> Momentum can never precede the driving function.
> Momentum is always more disjoint, or irregular, than the original
> function.
> The first of these truths is blindingly obvious when viewed at the
> theoretical level. However, the obvious gets subordinated when you
> are searching for an indicator that is just a little bit better. The
> second truth is visible in momentum indicators as noisy signals.
> Momentum indicators are almost always combined with smoothing
> functions to reduce the noise that has been created. The lag
> introduced by this smoothing tends to mitigate the advantages of
> getting an early signal from the momentum.
>
> Rather than accept the limitations of momentum functions or the lag
> of moving averages, there is perhaps a better way to apply signal
> analysis to the market activity. One such approach is to define
> modes of the market and then use a strategy of applying the best
> analysis technique for each mode after the mode has been identified.
> Let's take a philosophical look at what those modes might be.
>
>
>
> RANDOM WALK
>
> Randomness in the market results from a large number of traders
> exercising their prerogatives with different motivations of profit,
> loss, greed, fear, and entertainment; it is complicated by different
> perspectives of time. Market movement can therefore be analyzed in
> terms of random variables. One such analysis is the random walk.
> Imagine an atom of oxygen in a plastic box containing nothing but
> air. The path of this atom is erratic as it bounces from one
> molecule to another. Brownian motion is used to describe the way the
> atom moves. Its path is described as a three dimensional random
> walk. Following such a random walk, the position of that atom is
> just as likely to be at any one location in that box as at any
> other. If the market activity were purely random it would be
> perfectly efficient and any attempt at technical analysis would be
> futile. While some hold this to be true, it is easy to refute on the
> basis of the obvious success of some technical analysts.
>
> Another form of the random walk is more appropriate for describing
> the motion of the market. This form is a two dimensional random
> walk, called the "drunkard's walk." The two dimensional structure is
> appropriate for the market because the prices can only go up or down
> in one dimension. The other dimension, time, can only move forward.
> These are similar to the way a drunkard's walk is described.
>
>
>
> DIFFUSION EQUATION
>
> The drunkard's walk is formulated by allowing the "drunk" to step to
> either the right or left randomly with each step forward. The ensure
> randomness, the decision to step right or left is made on the
> outcome of a coin toss from a fair coin. If the coin turns up heads,
> the drunk steps to the right. If the coin turns up tails, the drunk
> steps to the left. Viewed from above, we see the random path the
> drunk has followed. We can write a differential equation for this
> path because the rate change of time is related to the rate change
> of position in two dimensions. The result is a relatively famous
> differential equation (among mathematicians, at least) called the
> diffusion equation. The equation describes many physical phenomena
> such as heat traveling up a silver spoon when it is placed in a hot
> cup of coffee or the shape of the plume of smoke as it leaves a
> smokestack.
>
> Picture this plume of smoke in a gentle breeze. The plume is roughly
> conical, widening with greater distance from the smokestack. The
> plume is bent in the direction of the breeze. The widening of the
> plume is, more or less, the description of the probability of the
> location of a single particle of smoke. There are clearly no cycles
> involved. I think the plume of smoke is generally descriptive of
> predicting the market action in a trend.
>
>
>
> TELEGRAPHERS EQUATION
>
> If we reformulate the drunkard's walk problem so that the outcome of
> the coin flip determines whether the drunk should change his
> direction or keep going the same direction of the previous step, the
> random variable become momentum rather than position. In this case,
> the solution to the random walk problem is an equally famous
> differential equation called the telegrapher's equation. In addition
> to describing waves on a telegraph wire, the equation also describes
> the meandering of a river. The significance is that short term
> coherence often exists in the drunkard's path.
>
> This makes sense. If we are in a short meander of a river we can
> pretty well predict how that meander is going to behave. On the
> other hand, if we were to overlay all the meanders of a given river
> as in a multiple exposure photograph, they would all be different.
>
> Just as the river has a short term coherency but is random over the
> longer span, I feel that the market has short term cycles but is
> generally efficient over the longer time span. By measuring the
> short term market cycles we can use their predictive nature to our
> advantage. However, we must realize they come and go in the longer
> term.
>
>
>
> Market Modes
>
> Arguments that cycles exist in the market arise not only from
> fundamental considerations or direct measurement but also on
> philosophical grounds related to physical phenomena. The natural
> response to any physical disturbance is harmonic motion. If you
> pluck a guitar string, the string vibrates with cycles you can hear.
> By analogy, we have every right to expect that the market will
> respond to disturbances with cyclic motion. This expectation is
> reinforced with random walk theory that suggests there are times the
> market prices can be described by the diffusion equation and other
> times when the market prices can be described by the telegrapher's
> equations.
>
> From this philosophical background it is a small jump to conclude
> that the market can be modeled as a trend mode plus a cycle mode. We
> can measure the cycles in the market. Therefore, if we subtract the
> cycle from the composite waveform the residual must be the
> instantaneous Trendline. Having a mechanism to separate the trend
> from the cycle we can establish trading indicators for each mode.
>
>
>
> Instantaneous Trendline
> The Instantaneous Trendline is created by removing the dominant
> cycle from the price information. We must first ascertain the period
> of the dominant cycle. We demonstrated a way to do this in the first
> article of this series2. Knowing the dominant cycle period, it is
> surprisingly easy to completely remove it by filtering. A simple
> average taken over the period of the dominant cycle has as many
> sample points above the average as below it, with the result that
> the dominant cycle component is removed at the output of the filter.
> The filtered residual is the Instantaneous Trendline. The period of
> the dominant cycle often changes as we move across the chart, so the
> period of the simple average must change accordingly. The output of
> this dynamically adjusted simple average is similar to a simple
> moving average. However, in this case, the lag of this Instantaneous
> Trendline will always be half the period of the dominant cycle.
>
> The EasyLanguage code to compute the Instantaneous Trendline is
> given in SideBar 1. You can save a lot of keystrokes if you cut and
> paste the dominant cycle period calculation from our first article
> of this series and simply add the code to compute and plot the
> simple average over the dominant cycle period.
>
> Trading strategy using the Instantaneous Trendline is easy to
> establish. In a cycle mode the price will alternate back and forth
> across the Instantaneous Trendline every half cycle. However, in a
> Trend Mode the price will be on one side of the Instantaneous
> Trendline for an extended period. Don't trade the trend until the
> price has crossed the Instantaneous Trendline more than the half
> dominant cycle (which you have measured) in history. Stop trading
> the Trend when the price again crosses the Instantaneous Trendline.
> In future articles we will develop filters to engage these rules
> with greater precision.
>
>
>
> ************************************ SideBar 1
> **************************************************
>
> EasyLanguage Code to Plot Instantaneous Trendline
>
>
>
> Inputs: Price((H+L)/2);
>
>
>
> Vars: Imult (.635),
>
> Qmult (.338),
>
> InPhase(0),
>
> Quadrature(0),
>
> Phase(0),
>
> DeltaPhase(0),
>
> count(0),
>
> InstPeriod(0),
>
> Period(0),
>
> Trendline(0);
>
>
>
> If CurrentBar > 5 then begin
>
>
>
> {Detrend Price}
>
> Value3 = Price - Price[7];
>
>
>
> {Compute InPhase and Quadrature components}
>
> Inphase = 1.25*(Value3[4] - Imult*Value3[2]) + Imult*InPhase[3];
>
> Quadrature = Value3[2] - Qmult*Value3 + Qmult*Quadrature[2];
>
>
>
> {Use ArcTangent to compute the current phase}
>
> If AbsValue(InPhase +InPhase[1]) > 0 then Phase = ArcTangent(AbsValue
> ((Quadrature+Quadrature[1]) / (InPhase+InPhase[1])));
>
>
>
> {Resolve the ArcTangent ambiguity}
>
> If InPhase < 0 and Quadrature > 0 then Phase = 180 - Phase;
>
> If InPhase < 0 and Quadrature < 0 then Phase = 180 + Phase;
>
> If InPhase > 0 and Quadrature < 0 then Phase = 360 - Phase;
>
>
>
> {Compute a differential phase, resolve phase wraparound, and limit
> delta phase errors}
>
> DeltaPhase = Phase[1] - Phase;
>
> If Phase[1] < 90 and Phase > 270 then DeltaPhase = 360 + Phase[1] -
> Phase;
>
> If DeltaPhase < 1 then DeltaPhase = 1;
>
> If DeltaPhase > 60 then Deltaphase = 60;
>
>
>
> {Sum DeltaPhases to reach 360 degrees. The sum is the instantaneous
> period.}
>
> InstPeriod = 0;
>
> Value4 = 0;
>
> For count = 0 to 40 begin
>
> Value4 = Value4 + DeltaPhase[count];
>
> If Value4 > 360 and InstPeriod = 0 then begin
>
> InstPeriod = count;
>
> end;
>
> end;
>
>
>
> {Resolve Instantaneous Period errors and smooth}
>
> If InstPeriod = 0 then InstPeriod = InstPeriod[1];
>
> Value5 = .25*(InstPeriod) + .75*Period[1];
>
>
>
> {Compute Trendline as simple average over the measured dominant
> cycle period}
>
> Period = IntPortion(Value5);
>
> Trendline = 0;
>
> For count = 0 to Period - 1 begin
>
> Trendline = Trendline + Price[count];
>
> end;
>
> If Period > 0 then Trendline = Trendline / Period;
>
>
>
> Plot1(Trendline, "TR");
>
> end;
>
>
>
> *********************************************************************
> ******************************
>
>
>
> Cycle Mode Trading
> Since Moving Averages, including the Instantaneous Trendline, lag
> the price action, a different technique is required to effectively
> trade the cycle mode. The usual approach is to use an oscillator
> such as a RSI or Stochastic in such trading conditions. Since we
> know the period of the dominant cycle3 there is a superior approach -
> the Sinewave Indicator. The Sinewave Indicator was first described
> in 19964, and now we have a means to dynamically adjust it to the
> measured dominant cycle. The Sinewave Indicator is obtained by
> taking the Sine of the measured phase of the dominant cycle.
>
>
>
> We measure the phase of the dominant cycle by establishing the
> average lengths of the two orthogonal components. This is done by
> correlating the data over one fully cycle period against the sine
> and cosine functions. Once the two orthogonal components are
> measured, the phase angle is established by taking the tangent of
> their ratio. A simple test is to assume the price function is a
> perfect sinewave, or Sin(q). The vertical component would be Sin2(q)
> = .5*(1-Cos(2q)) taken over the full cycle. The Cos(2q) term
> averages to zero, with the result that the correlation has an
> amplitude of Pi. The horizontal component is Sin(q)*Cos(q) = .5*Sin
> (2q). This term averages to zero over the full cycle, with the
> result that there is no horizontal component. The ratio of the two
> components goes to infinity because we are dividing by zero, and the
> arctangent is therefore 90 degrees. This means the arrow is pointing
> straight up, right at the peak of the sinewave.
>
> One additional step in our calculations is required to clear the
> ambiguity of the tangent function. In the first quadrant both the
> sine and cosine have positive polarity. In the second quadrant the
> sine is positive and the cosine is negative. In the third quadrant
> both are negative. Finally, in the fourth quadrant the sine is
> negative and the cosine is positive. The phase angle is obtained
> regardless of the amplitude of the cycle. Given that we know the
> dominant cycle, the BASIC program in the sidebar shows how we can
> compute he phase angle.
>
> When the market is in a Cycle Mode the Sine of the measure phase
> looks very much like a sinewave. On the other hand, when the market
> is in a Trend Mode there is only an incidental rate change of phase
> of the phasor. A clear, unequivocal cycle mode indicator can be
> generated by plotting the Sine of the measured phase angle advanced
> by 45 degrees. This leading signal crosses the sinewave 1/8th of a
> cycle BEFORE the peaks and valleys of the cyclic turning points,
> enabling you to make your trading decision in time to profit from
> the entire amplitude swing of the cycle. A significant additional
> advantage is that the two indicator lines don't cross except at
> cyclic turning points, avoiding the false whipsaw signals of
> most "oscillators" when the market is in a Trend Mode. The two lines
> don't cross because the phase rate of change is nearly zero in a
> trend mode. Since the phase is not changing, the two lines separated
> by 45 degrees in phase never get the opportunity to cross.
>
> The EasyLanguage code for the dynamically adjusted Sinewave
> Indicator is given in SideBar 2. Again, to save yourself some
> keystrokes, you can cut and paste from the code to calculate the
> dominant cycle from the first article of this series and then add in
> the code to compute the phase of the dominant cycle and the Sine and
> LeadSine values using that phase.
>
>
>
> ********************************* SideBar 2
> ***************************************************
>
> EasyLanguage Code to Compute the Sinewave Indicator
>
>
>
> Inputs: Price((H+L)/2);
>
>
>
> Vars: Imult (.635),
>
> Qmult (.338),
>
> InPhase(0),
>
> Quadrature(0),
>
> Phase(0),
>
> DeltaPhase(0),
>
> count(0),
>
> InstPeriod(0),
>
> Period(0),
>
> DCPhase(0),
>
> RealPart(0),
>
> ImagPart(0);
>
>
>
> If CurrentBar > 5 then begin
>
>
>
> {Detrend Price}
>
> Value3 = Price - Price[7];
>
>
>
> {Compute InPhase and Quadrature components}
>
> Inphase = 1.25*(Value3[4] - Imult*Value3[2]) + Imult*InPhase[3];
>
> Quadrature = Value3[2] - Qmult*Value3 + Qmult*Quadrature[2];
>
>
>
> {Use ArcTangent to compute the current phase}
>
> If AbsValue(InPhase +InPhase[1]) > 0 then Phase = ArcTangent(AbsValue
> ((Quadrature+Quadrature[1]) / (InPhase+InPhase[1])));
>
>
>
> {Resolve the ArcTangent ambiguity}
>
> If InPhase < 0 and Quadrature > 0 then Phase = 180 - Phase;
>
> If InPhase < 0 and Quadrature < 0 then Phase = 180 + Phase;
>
> If InPhase > 0 and Quadrature < 0 then Phase = 360 - Phase;
>
>
>
> {Compute a differential phase, resolve phase wraparound, and limit
> delta phase errors}
>
> DeltaPhase = Phase[1] - Phase;
>
> If Phase[1] < 90 and Phase > 270 then DeltaPhase = 360 + Phase[1] -
> Phase;
>
> If DeltaPhase < 1 then DeltaPhase = 1;
>
> If DeltaPhase > 60 then Deltaphase = 60;
>
>
>
> {Sum DeltaPhases to reach 360 degrees. The sum is the instantaneous
> period.}
>
> InstPeriod = 0;
>
> Value4 = 0;
>
> For count = 0 to 40 begin
>
> Value4 = Value4 + DeltaPhase[count];
>
> If Value4 > 360 and InstPeriod = 0 then begin
>
> InstPeriod = count;
>
> end;
>
> end;
>
>
>
> {Resolve Instantaneous Period errors and smooth}
>
> If InstPeriod = 0 then InstPeriod = InstPeriod[1];
>
> Value5 = .25*InstPeriod + .75*Period[1];
>
>
>
> {Compute Dominant Cycle Phase, Sine of the Phase Angle, and Leadsine}
>
> Period = IntPortion(Value5);
>
> RealPart = 0;
>
> ImagPart = 0;
>
> For count = 0 To Period - 1 begin
>
> RealPart = RealPart + Sine(360 * count / Period) * (Price[count]);
>
> ImagPart = ImagPart + Cosine(360 * count / Period) * (Price
> [count]);
>
> end;
>
> If AbsValue(ImagPart) > 0.001 then DCPhase = Arctangent(RealPart /
> ImagPart);
>
> If AbsValue(ImagPart) <= 0.001 then DCPhase = 90 * Sign(RealPart);
>
> DCPhase = DCPhase + 90;
>
> If ImagPart < 0 then DCPhase = DCPhase + 180;
>
>
>
> Plot1(Sine(DCPhase), "Sine");
>
> Plot2(Sine(DCPhase + 45), "LeadSine");
>
>
>
> end;
>
> *********************************************************************
> ****************************
>
>
>
> REAL WORLD EXAMPLES
>
> This is where things really get interesting. We have plotted the
> Instantaneous Trendline over the price bars and the Sinewave
> Indicator in subgraph 2 in Figure 2. Note that the price (actually
> the average price for each day) stays above the Instantaneous
> Trendline from the latter part of August until mid December. The
> market is clearly in a Trend Mode during this period, and the
> correct strategy would be to buy and hold. Then, in mid December the
> market switched to a Cycle Mode, and stayed in a cycle mode almost
> to the end of the chart. During this period the best strategy would
> be to use a cycle mode technique - the Sinewave Indicator. The
> Sinewave Indicator correctly anticipated EVERY turning point.
>
> It is important to note that the Leadsine Indicator did not cross
> the Sinewave signal during the Trend Mode period, although the two
> lines were wandering around. There were no distracting cycle mode
> signals from this oscillator when the market is in the trend mode.
>
> I can point out the features of these two indicators ad nauseum.
> However, it is far better for you to program these indicators and
> test them for yourself. This way, you will build confidence that
> they can work for you.
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> Figure 1. Momentum can never precede the driving function and
> momentum is always more disjoint (noisy) than the driving function.
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> Figure 2. Trade the Instantaneous Trendline from the latter part of
> August to mid December. Trade the Sinewave Indicator almost all the
> rest of the chart. The Sinewave Indicator lines do not cross during
> the Trend Mode.
>
>
>
>
> 1 George H. Weiss, "Random Walks and Their Applications", American
> Scientist, Jan/Feb 1983, p65-71
>
>
>
>
> 2 John Ehlers, "Signal Analysis Concepts"
>
>
>
>
> 3 John Ehlers, "Signal Analysis Concepts", Ibid
>
>
>
>
> 4 John Ehlers, "Stay In Phase", Stocks & Commodities, Vol 14, #11,
> 1996, p 483-
>
>
>
>
> Send BUG REPORTS to bugs@xxxxxxxxxxxxx
> Send SUGGESTIONS to suggest@xxxxxxxxxxxxx
> -----------------------------------------
> Post AmiQuote-related messages ONLY to: amiquote@xxxxxxxxxxxxxxx
> (Web page: http://groups.yahoo.com/group/amiquote/messages/)
> --------------------------------------------
> Check group FAQ at:
> http://groups.yahoo.com/group/amibroker/files/groupfaq.html
>
> Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
>
>
------------------------ Yahoo! Groups Sponsor ---------------------~-->
Buy Ink Cartridges or Refill Kits for your HP, Epson, Canon or Lexmark
Printer at MyInks.com. Free s/h on orders $50 or more to the US & Canada.
http://www.c1tracking.com/l.asp?cid=5511
http://us.click.yahoo.com/mOAaAA/3exGAA/qnsNAA/GHeqlB/TM
---------------------------------------------------------------------~->
Send BUG REPORTS to bugs@xxxxxxxxxxxxx
Send SUGGESTIONS to suggest@xxxxxxxxxxxxx
-----------------------------------------
Post AmiQuote-related messages ONLY to: amiquote@xxxxxxxxxxxxxxx
(Web page: http://groups.yahoo.com/group/amiquote/messages/)
--------------------------------------------
Check group FAQ at: http://groups.yahoo.com/group/amibroker/files/groupfaq.html
Yahoo! Groups Links
<*> To visit your group on the web, go to:
http://groups.yahoo.com/group/amibroker/
<*> To unsubscribe from this group, send an email to:
amibroker-unsubscribe@xxxxxxxxxxxxxxx
<*> Your use of Yahoo! Groups is subject to:
http://docs.yahoo.com/info/terms/
|