TradeStation Securities
No New Private Messages
You are logged in to the forums as MisterFX
Brokerage Services Trading Platform Open an Account Support & Community  
| TradeStation Wiki | Most Recent Forum Posts | My Forum Subscriptions | Forum Help |
  | Advanced Forum Search

Home > Support > All Forums > EasyLanguage Library > Indicators (Charting, RadarScreen) >
 Cycles/Adaptive Indicators with Least Squares Fits
2 Pages    1 2  
  Next Page
Author
Topic  
eXcap
96 Posts
Posted - 01/17/2007 00:36:44    
XCAP_iPolyCycle

Author: Paul A. Griffin
January 16, 2007
Extrema Capital, 2007

Introduction

This indicator combines Legendre polynomials and analytic signal analysis. The result is a smooth definition of cycle period and an example relative strength indicator adapted to the cycle length. This analysis is performed without adding time lag by smoothing with moving averages.

This indicator displays the following:

a. The least squares fit of a polynomial to a DC subtracted time series - a best fit to a cycle.

b. The normalized Analytic Signal of the cycle (signal and quadrature).

c. The phase shift of the analytic signal per bar.

d. The period and half period lengths, in bars of the current cycle.

e. A relative strength indicator of the time series over the cycle length. That is, adaptive relative strength over the cycle length.

The relative strength indicator can be smoothed by increasing the length variable or decreasing the number of degrees of freedom used in the fit. Other adaptive indicators based upon the determined period and can be similarly constructed.

There is some new math here, so I have broken the story up into 5 Parts:

Part 1 The Polynomial Fit to a Cycle

Any time series can be decomposed into a orthogonal set of polynomials [1,2,3]. This decomposition lets you smooth the time series without adding extra lag associated with taking averages. I view this as the main reason to be using polynomial fits. You get an extra few bars of less lag.

Here are some good references:

[1] http://en.wikipedia.org/wiki/Legendre_polynomials

[2] https://www.tradestation.com/Discussions/Topic.aspx?Topic_ID=59250

[3] Peter Seffen, "On Digital Smoothing Filters: A Brief Review of Closed Form Solutions and Two New Filter Approaches", Circuits Systems Signal Process, Vol. 5, No 2, 1986

For the analysis below, I decompose a time series into a low number of degrees of freedom and discard the zero mode to introduce smoothing.

That is:

time series => c_1 t + c_2 t^2 ... c_Max t^Max

This is defined as the cycle. By construction, the cycle does not have a zero mode, as c_0 is removed from the re-expansion. The data for the cycle and the fit of the cycle can be viewed by setting

ShowDataAndFit = TRUE;



There, you will see the fit of the last bar as well as the time series of the leading edge of the fits. If you don't know what I mean by the "leading edge", please see some of the postings in [2]. The leading edges are in grayscale, and the data and fit of the last bar is in the blue colors. The data are the dots, the fits the lines.

I have choosen Length = 17 and Degree = 4 as the default. I am simply making sure by eye that the fit is reasonably good and degree 4 is the lowest polynomial that can represent a sine-like wave, and 17 is the smallest length that lets me calculate the Phase Shift (Part 3 below) using the Hilbert Transform of width = 7 (Part 2 below).

Depending upon the fit you make, you will capture different cycles in the data. A fit that is very "smooth" will not see smaller cycles, and a fit that is "choppy" will not see longer ones. The idea is to use the fit to try to suppress the smaller noise cycles while keeping larger signal cycles of interest to your trading.

Part 2 The Analytic Signal

Every time series has an Analytic Signal, defined by applying the Hilbert Transform to it. You can think of the original time series as amplitude * cosine(theta) and the transformed series, called the quadrature, can be thought of as amplitude * sine(theta). By taking the ratio, you can get the angle theta, and this is exactly what was done by John Ehlers in [4]. It lets you get a frequency out of the time series under consideration.

[4] http://www.amazon.com/Rocket-Science-Traders-Processing-Applications/dp/0471405671

It also helps to have more references to understand this. There is a nice article in Wikipedia [5] on it. Read the part about the discrete Hilbert Transform:

[5] http://www.answers.com/topic/hilbert-transform

Also, Answers.com has good information on the Hilbert Transform and links to other concepts:

[6] http://www.answers.com/topic/hilbert-transform

If you really want to understand how to go from continuous to discrete, look up this article written by Richard Lyons:

[7] www.dspguru.com/info/tutor/QuadSignals.pdf

In the indicator below, I am calculating the normalized analytic signal, which can be written as:

s + i h where i is the imaginary number, and s^2 + h^2 = 1;

s= signal = cosine(theta)
h = hilbert transformed signal = quadrature = sine(theta)

The angle is therefore given by theta = arctan(h/s);

The analytic signal leading edge and the fit of the last bar of the cycle can be viewed by setting

ShowAnalyticSignal = TRUE;



The leading edges are in grayscale fit to the last bar is in color. Light (yellow) is the
s term, and Dark (orange) is the quadrature (hilbert transform). Note that for every bar,
s^2 + h^2 = 1 , by construction.

I am using a width = 7 Hilbert transform, just like Ehlers. (But you can adjust it if you want.) This transform has a 7 bar lag. I have put the lag into the plot statements, so the cycle info should be quite good at displaying minima and maxima (extrema).

Part 3 The Phase Shift

The Phase shift is the amount of phase change from bar to bar. It is a discrete unitary transformation that takes s[1] + i h[1] to s + i h so this means that:

T = (s+ih)*(s[1]-ih[1]) , since s[1]*s[1] + h[1]*h[1] = 1.

writing it out, we find that

T = T1 + iT2

where

T1 = s*s[1] + h*h[1] and T2 = s*h[1]-h*s[1]

and the phase shift is given by PhaseShift = arctan(T2/T1).

Alas, I have no reference for this, all I doing is finding the rotation that takes the analytic signal at bar 1 to the analytic signal at bar 0. T is a transfer matrix, by the way.

Of interest is the PhaseShift from the closest two bars to the present, given by bar 7 and bar 8 since I am using a width=7 Hilbert transform, bar 7 is the earliest bar with an
analytic signal.

I store the phase shift from bar 7 to bar 8 as a timeseries called PhaseShift. It basically gives you the (7-bar delayed) leading edge the amount of phase angle change in the series. You can see it by setting

ShowPhaseShift=TRUE



The green points are positve phase shifts and red points are negative phase shifts. On most charts I have looked at, the indicator is mostly green, but occasionally, the stock "retrogrades" and red appears. This happens when the cycle is "broken" and the cycle length starts to expand as a trend occurs. You might try setting the length to 31 with degree 4 to see this better.

Part 4 The Period and Half Period

The Period is the number of bars required to generate a sum of PhaseShifts equal to 360 degrees. The Half Period is the number of bars required to generate a sum of phase shifts equal to 180 degrees. It is usually not equal to 1/2 of the Period, by the way. The code to determine the period from the phase shifts is very simple:




You can see the Period and Half Period in the indicator by setting

ShowPeriod=TRUE

In the image below, you will also see for comparison the Rocket 7 period indicator from the Ehlers Rocket Science book [4].



The period is sensitive to the Length and Degree values but not overly so. Any clever insights on this would be appreciated of course.

Part 5 The Relative Stength Indicator

The Relative Strength is just the current value of the series minus the minimum over the last cycle
divided by the maximum - minimum over the last cycle length and the 7-bar lag, normalized between +1 and -1:

RelativeStrength = -1 + 2*(Series-Min)/(Max-Min);

Therefore it tells you where the current bar is relative to the cycle. If you want to smooth the indicator, then extend the period and/or reduce the polynomial degree. You can see the Relative Strength by setting

ShowRelativeStrength = TRUE



It tells you where you are on a bar defined by the maximum and minimum values over the previous cycle.

Discussion

This is my first crack at combining Legendre polynomials fits with analytic signal theory to determine a smooth period without adding additional time lag from moving averages. There are many more ideas I have with using polynomial fits, but this is the one that motivated me originally to think about the least squares fit problem.

I should mention again that you can use the Period variable to adapt any length-based indicators to cycle fluxuations.

Well, thats all for now. Feedback and insights on how to make the code better are also always welcome. Just trying to make some progress,

--Paul Griffin
"eXcap"

Attachment:DATA/20070116233527XCAP_POLYCYCLE.ELD 23004 bytes
Attachment:DATA/20070116233540XCAP_wPolyCycle.tsw 49152 bytes
Poll Description:
Choices:
Extremely Useful
Useful
Somewhat Useful
Not Useful
  View Results
JavLn
9023 Posts
Posted - 01/17/2007 01:44:34    
This looks very interesting! I think I can use this one.
kingsview127
101 Posts
Posted - 01/17/2007 03:14:36    
Once in a while, there is a "genius" appears in the Tradestation forum. Their ideas really save you thousand of dollars IMO. They are listed in chronological order:
1) TRO with hundred Radarscreen indicators."The fastest codes writer and the most controversial".
2) Antonio with Market Profile and Market Delta indicators."The mysterious".
3) eXcap with his Polynomial and XCAP_iPolyCycle indicators. "The math doctor".

Thank you.
eXcap
96 Posts
Posted - 01/17/2007 18:52:22    
Thanks kingsview127,

I think that is a nice compliment. I hope

Oh, I messed up on the references a little. The Wikipedia reference is:

http://en.wikipedia.org/wiki/Hilbert_transform

and also look at this:

http://en.wikipedia.org/wiki/Analytic_signal

I also forgot to mention, if you really want to do cycles right, and extract all the cycles, not just a dominant one, look into the Hilbert Huang Transform. I have not seen a better way of doing the analysis than this. Huang has a paper on its application to finance where he decomposes interest rates into multiple cycles

http://www.techbriefs.com/component/option,com_docman/task,doc_details/gid,2183/

Looks like you will have to type the above link by hand. The link below is an easier to understand version applied to the cycling of the length of a day over many years. Amazing.

www.worldscibooks.com/mathematics/ etextbook/5862/5862_chap1.pdf

That's it on cycles for now.

--Paul Griffin
"eXcap"





msb
1346 Posts
Posted - 01/17/2007 20:00:05    
eXcap,

I want to commend you and say thanks for your generous contribution. I have performed alot of studies on cycles, so it will be interesting to see how this approach compares with the others.

Mark
raydirks
8 Posts
Posted - 01/17/2007 22:19:38    
I want to add my congradulations on very impressive and professional work and add my sincere thanks for your generous contribution. I am doing alot of cycle work with various tools but getting the ideas or concepts into the code is a challenge - so you have helped at least me greatly!



quote:
Originally posted by eXcap
Thanks kingsview127,

I think that is a nice compliment. I hope

Oh, I messed up on the references a little. The Wikipedia reference is:

http://en.wikipedia.org/wiki/Hilbert_transform

and also look at this:

http://en.wikipedia.org/wiki/Analytic_signal

I also forgot to mention, if you really want to do cycles right, and extract all the cycles, not just a dominant one, look into the Hilbert Huang Transform. I have not seen a better way of doing the analysis than this. Huang has a paper on its application to finance where he decomposes interest rates into multiple cycles

http://www.techbriefs.com/component/option,com_docman/task,doc_details/gid,2183/

Looks like you will have to type the above link by hand. The link below is an easier to understand version applied to the cycling of the length of a day over many years. Amazing.

www.worldscibooks.com/mathematics/ etextbook/5862/5862_chap1.pdf

That's it on cycles for now.

--Paul Griffin
"eXcap"






ForJL
55 Posts
Posted - 01/21/2007 19:42:55    


If it's at all possible, I would greatly appreciate it if someone could post the code for this indicator and it's functions for us 2000i users. I'm not sure if it will work in that environment but would like to give it a shot.
Thanks,
Joe
sunabeacho
4733 Posts
Posted - 01/21/2007 22:04:35    

Well here is the code. Give it a shot:


sunabeacho
4733 Posts
Posted - 01/21/2007 22:07:42    
I am not sure if there is any functions needed though?
ForJL
55 Posts
Posted - 01/22/2007 09:45:04    


Sunabeacho, thanks a lot! First glance at code makes me think I will have problems but we'll see. Thanks again, Joe.
magemic
11 Posts
Posted - 03/12/2007 18:59:04    
Hi, I am pretty new hear - if I wanted to turn this into a strategy that I could trade or at least play with a bit, what would I need to do?
Thanks!
tsxela
38 Posts
Posted - 01/26/2009 18:04:39    
it's possible have the code in ts 2000?
thank you
TradingDude
13852 Posts
Posted - 01/27/2009 07:47:18    
quote:
Originally posted by tsxela
it's possible have the code in ts 2000?
thank you


Read the posts above 1/21/2007 by sunabeacho

TradingDude



TheBoss
89 Posts
Posted - 01/27/2009 19:49:06    
eXcap,

Thank you for sharing! I simply don't understand why you would work so hard and let everyone else benefit from your work. We all know that large banks and institutions create their own indicators using different models of financial engineering, but they simply keep them from the hands of the public for obvious reasons. One model that I am personally getting involved with is the Heston Model. I have tons of research and information gather, if you are interested of acquiring it and working with me on an indicator please contact me. Once again I thank you for your generosity and hard work!

http://en.wikipedia.org/wiki/Heston_model



Best Regards,

TB
TheBoss
89 Posts
Posted - 01/27/2009 20:08:34    
One more thing I forgot to mention, the indicator is using 17 for length and 4 for degree. Is the indicator and formulas being used, work only with those values? Are those the optimal values? I am not very proficient with EL, but how can the code be modified to where optimization can be created for the length and degree period?

Best Regards,

TB
KnightsInRodanthe
839 Posts
Posted - 01/28/2009 13:50:27    
re: "17 for length and 4 for degree"
Not sure if these are the floor, but below certain thresholds for these parameters the mathematics for the cycles become 'illogical'. If I remember correctly, he discusses this in the code documentation...
xyzo
267 Posts
Posted - 02/01/2009 05:27:15    
[qoute]
Thank you for sharing! I simply don't understand why you would work so hard and let everyone else benefit from your work. We all know that large banks and institutions create their own indicators using different models of financial engineering, but they simply keep them from the hands of the public for obvious reasons.



The reason they kept secret is because they think they know everything, and they get selfish and don't want to share to public. See what they got for getting selfish? ALL FAILED!! Now, they ask the public to bail them out. Ouch! Can we say no? Ouch Ouch !!

Anyway, serve them right!!

Thank you eXcap for your generosity. It's people like you that is keeping our society up and running. Without giver's eXcap, our world is doomed; just like how those selfish bankers get doomed!

Thank you again!
alpha24
194 Posts
Posted - 02/04/2009 04:35:16    
Been watching the signals and its seems quiet interesting. Anyone made this into a strat yet ? I did but no orders were generated somehow .
optionswings
1935 Posts
Posted - 02/04/2009 13:52:28    
Do you have max bars set far back enough?

-OS

quote:
Originally posted by alpha24
Been watching the signals and its seems quiet interesting. Anyone made this into a strat yet ? I did but no orders were generated somehow .
ChaseLABS
15 Posts
Posted - 02/05/2009 18:25:46    
Can someone help me develop this indicator into a strategy? When it crosses over 0 Long, crosses below 0 short. I tried coding it, but i get no orders generated as well. It seems hard to define the value of the line crossing above and below 0. Any help is greatly appreciated!


Best Regards,

ChaseLABS
KnightsInRodanthe
839 Posts
Posted - 02/06/2009 13:43:57    
ChaseLABS, Post your code or eld and your chances of getting solid help go up geometrically...
TheBoss
89 Posts
Posted - 02/09/2009 15:32:33    
KnightsInRodanthe,

The eld file is posted on top of this thread for the indicator!
Mark43
23 Posts
Posted - 02/22/2009 13:37:35    
Would it be possible for the "function" ELD(s) to be posted for this indicator please? It looks like a very useful indicator but the code is so long and complex I'm having trouble figuring out how to convert it to function(s). Thanks to anybody who is willing to share this.
TradingDude
13852 Posts
Posted - 02/22/2009 21:35:03    
quote:
Originally posted by Mark43
Would it be possible for the "function" ELD(s) to be posted for this indicator please? It looks like a very useful indicator but the code is so long and complex I'm having trouble figuring out how to convert it to function(s). Thanks to anybody who is willing to share this.


At the end of the first post by excap, there are 2 attachments: the ELD and the workspace, TSW.

Double click on the ELD to import to platform. Copy the workspace in mywork folder. Then open the workspace.

TradingDude

tbbwtrader
4 Posts
Posted - 02/23/2009 22:16:24    
I have been using the XCAP_iPolyCycle in my strategy. I simply cut out the plotting routines from this indicator and pasted it into my strategy. I'm only using the Relative Strength part and was wondering if there was more that can be removed to improve code efficiency if I just want the Relative Strength. Preliminary results from my strategy for day trading look awesome. I am combing the Relative Strength with the Moving Average Adaptive, a 200 period MA, a 50 period MA, and the difference between 9 and 18 period MAs. The difference between the shorter two MAs is a nice convergence/divergence indicator. Look for turning points in the convergence/divergence and then wait for +1 or -1 in the Relative Strength to be pegged.
marcpc1
11 Posts
Posted - 02/26/2009 17:54:31    
Pardon my naivity about lagged indicators but is there a way to use the analytic signal cross overs in real-time. I am having some success using the Cycle's turns in real-time combined with a momentum oscillator reversing.

The relative strength at 1 or -1 seems difficult to use in strongly trended markets.
  Next Page
2 Pages    1 2  
Quick Reply
Message:

 
       




Copyright © 2001-2009 TradeStation Securities, Inc. All rights reserved.
Member NYSE, FINRA, NFA & SIPC. A subsidiary of TradeStation Group, Inc. (Nasdaq Symbol: TRAD)


| Important Information | Notice to Online Traders | Online Identity Theft and Security Reminders | TradeStation Securities Account Agreement for Securities Accounts | TradeStation Securities Account Agreement for Futures Accounts | TradeStation Technologies Subscription Agreement | Risks of Active Trading | Extended Hours Trading Risk Disclosure | Margin Disclosure Statement | Risk Disclosure Statement For Security Futures Contracts | Characteristics and Risks of Standardized Options | Description and Certain Risks of Forex Trading | Risk Disclosure Statement for Futures and Futures Options | Exercise and Assignment Policy for Futures Options | New York Board of Trade Electronic Order Routing Systems Disclosure Statement | Trading and Order Routing Disclosure Statement for Futures Trades | Special Statement for Uncovered Options Writers | Anti-Money Laundering Requirements | Business Continuity Plan Disclosure | Truth-in-Lending Disclosure Statement | Web Site User Agreement, Disclaimers and Certain Legal Notices | Privacy Policy | Forum Guidelines and User Agreement |

TradeStation.com Discussion
This page was generated in 0.30 seconds. 2003-2010 TradeStation.com.