Jump to content

Welcome to the new Traders Laboratory! Please bear with us as we finish the migration over the next few days. If you find any issues, want to leave feedback, get in touch with us, or offer suggestions please post to the Support forum here.

  • Welcome Guests

    Welcome. You are currently viewing the forum as a guest which does not give you access to all the great features at Traders Laboratory such as interacting with members, access to all forums, downloading attachments, and eligibility to win free giveaways. Registration is fast, simple and absolutely free. Create a FREE Traders Laboratory account here.

Recommended Posts

XCAP_iPolyCycle

 

 

XCAP_iPolyCycle

 

Author: Paul A. Griffin

January 16, 2007

Extrema Capital, 2007

 

Introduction:

 

This is an example of what can be done by combining Legendre polynomials and

analytic signals. I get a way of determining a smooth period and

relative adaptive strength indicator without adding time lag.

 

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 HalfPeriod 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, is adaptive to the time series, and it can be smoothed by increasing the length of

decreasing the number of degrees of freedom.

 

Other adaptive indicators based upon the period and can be similarly constructed.

 

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

 

Part 1:

 

Any time series can be decomposed into a orthogonal set of polynomials [1,2,3].

This is just math and 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

 

I gave some thought to what should be done with ths and came to the conclusion that they can be used for basic smoothing

of time series. 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 the cycle. By construction, the cycle does not have a zero mode and more physically, I am defining the

"Trend" to be the zero mode.

 

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 fit of the last bar is in color.

 

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 too "smooth" will

not see the smaller cycles, and a fit that is too "choppy" will not see the longer ones. The idea is to use the fit

to try to suppress the smaller noise cycles while keeping larger signal cycles.

 

Part 2:

 

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 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'>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] http://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 imagary 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 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

 

explicitly, 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 what takes the analytic signal

at bar [1] to the analytic signal at bar [0]. T is the transfer matrix.

 

Of interest is the PhaseShift from the closest two bars to the present, given by the

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 pahse shifts.

On most charts, I have looked at, the indicator is mostly green, but occationally, the stock

"retrogrades" and red appears. This happens when the cycle is "broken" and the cycle length starts to

expand as a trend occurs.

 

Part 4:

 

The Period:

 

The Period is the number of bars required to generate a sum of

PhaseShifts equal to 360 degrees.

 

The halfperiod 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.

 

You can see the Period and Halfperiod by setting

 

ShowPeriod=TRUE

 

The code is very simple here:

 

Value1=0;

Value2=0;

while Value1 < barnumber and AbsValue(Value2) < 360 begin

Value2 = Value2 + PhaseShift[Value1];

Value1 = Value1 + 1;

end;

Period = Value1;

 

The period is sensitive to the input length and degree values but not overly so. Any insight

on this would be appreciated.

 

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, normalized between +1 and -1.

 

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

 

It therefore 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.

 

In code:

 

NewLength = floor(Period + HilbertWidth+1);

Max = highest(Series,NewLength);

Min = lowest(Series,NewLength);

if Max>Min then

 

Note that the variable NewLength includes the lag that comes from the hilbert transform,

(HilbertWidth=7 by default).

 

Conclusion:

 

This is an example of what can be done by combining Legendre polynomials and

analytic signals to determine a smooth period without adding time lag.

 

 

 

14672d1256761996-xcap-ipolyfitpredict-xcap.png

 

 

 

Note:

This indicator was written in EasyLanguage.

Please refer to your users manual for importation instructions.

 

Your comments and rating of this indicator is appreciated.

XCAP_iPolyCycle_(MultiCharts).pla

XCAP_iPolyCycle_(EasyLanguage).txt

Share this post


Link to post
Share on other sites

thx looks very interesting.....will test it shortly & then reply with feedback.......looks like it turns with Price, so can be a good addition/verifier for other indicators one uses....thx Tams

Share this post


Link to post
Share on other sites

tried to copy the easylanguage to make an "indicator".....made it via th top of the dialogue wordages... & it did make an indicator....but when loaded up unto a chart, showed the level, but nothing in it. So, not sure how to make an ELD for the graph you have. Any suggestions Tams? Do you have an ELD already made that you can post? Or am I copying the wrong wordage? Thx ahead of time....ajax358,,,,,,,,,,Here is what I copied:

 

Inputs:

Series((h+l)/2),

Length(17), // Length = 2*Width+1, the minimum is 17 bars

Degree(4), // 0 <= Degree <= 2*Width+1, default is 4, 4 DOF for 17 bars

ShowDataAndFit(FALSE), //Shows data and fit of the data last bar only

ShowAnalyticSignal(FALSE), //Shows the signal between the

ShowPhaseShift(FALSE), //Shows the PhaseShift for the last bar

ShowPeriod(FALSE), //Shows the number of bars required to Phase Shift a half and a full period

ShowRelativeStrength(TRUE); //Show the relative strengh of the current bar w.r.t. a full period (+ calculation lag).

 

Variables:

HilbertWidth(7), // Must be an odd number. 1,3,5,7,9, ... less than or equal to Width = floor(Length-1)/2)

pi(3.141592653589793), //close enough

Width(floor((Length-1)/2)); //

 

Variables:

DC(0),

EarliestWidth(0),

LeadingCycleEdge(0),

LeadingSignalEdge(0),

LeadingHilbertEdge(0),

p(0),j(0),k(0),

DataSize(2*Width+1),

T1(0),T2(0),//TransferMatrix

PhaseShift(0),

HalfPeriod(0),Period(0),

Max(0),Min(0),

RelativeStrength(0);

 

 

Arrays:

Polynomial[](0),

Coefficient[](0),

Cycle[](0),

Signal[](0),

Hilbert[](0),

HilbertTransform[](0),

SignalTransform[](0);

 

if barnumber = 1 then begin

 

//Allocate memory for the arrays. Polynomial is a 2D array

Array_SetMaxIndex(Polynomial, DataSize*(Degree+1)+1);

Array_SetMaxIndex(Coefficient, Degree+1);

Array_SetMaxIndex(Cycle, DataSize);

Array_SetMaxIndex(Signal, DataSize);

Array_SetMaxIndex(Hilbert, DataSize);

 

//We are going to make the analytic signal of the time series with the transforms below:

Array_SetMaxIndex(HilbertTransform, 2*HilbertWidth+1);

Array_SetMaxIndex(SignalTransform,2*HilbertWidth+1);

 

//Create the Dicrete Hilbert Transform Filter, normalized to a step function (the last being my idea)

for k = -HilbertWidth to HilbertWidth begin

if mod(k,2) = 0 then HilbertTransform[HilbertWidth+k] = 0 else HilbertTransform[HilbertWidth+k] = 2/(pi*k);

if k = 0 then SignalTransform[HilbertWidth+k] = 1 else SignalTransform[HilbertWidth+k] = 0;

end;

 

end;

Share this post


Link to post
Share on other sites

there were apparent breaks in the code with dialogue, so was not sure were to to copy & what not to copy.....still not sure, so am in limbo. Maybe someone smarter than me can then just post the string of dialogue so this non techie feeble mind can know. Just a thought & grateful for any help.... :)

thx......ajax358

Share this post


Link to post
Share on other sites
there were apparent breaks in the code with dialogue, so was not sure were to to copy & what not to copy.....still not sure, so am in limbo. Maybe someone smarter than me can then just post the string of dialogue so this non techie feeble mind can know. Just a thought & grateful for any help.... :)

thx......ajax358

 

Why do you try to pick what to copy and what not? Just copy and paste the text file Tams attached. It contains everything you need.

 

Open the attached Text file then:

Ctrl-A

Ctrl-C

Create a new indicator in TS then:

Ctrl-V

 

This is not so hard, is it?

Share this post


Link to post
Share on other sites

I did copy the whole thing & it did not work.....TS verified it on the close of the indicator creation, but when loaded to the window nothing loaded=it was blank. So I guess it is not so easy, as per the results of the above statement. As I asked, if someone could just copy & paste the entire one that works, then I will test it out & try it, then report back. If no one does, then I will pass on this....see is easy. Thx for someone to post it or the ELD.... :)

Share this post


Link to post
Share on other sites

"statsign".....cheers mate & thx for posting it.....me being puter geek language challenged, tho a geek wannabe.....thx ya allot. Will load & test it over this weekend....will report to this board later of my use & findings. Thx again. & thx to Tams for posting it.... :)

Share this post


Link to post
Share on other sites

"statsign"....(not sure if the other post got thru, as not see it, so try again).....thx allot for the post of the ELD....me being geek language/puter challengesd, but a geek wannabe, this will do the ticket. Will post a backtest & usgae response this weekend. Thx again. & thx Tams for posting this code .... :)

Share this post


Link to post
Share on other sites

is it possible to set array sizes to fixed sizes rather than dynamic allocation?

i'm talking about the part where Array_SetMaxIndex function called.

cause i use minor platform (not TS) which doesn't support dynamic allocating.

Share this post


Link to post
Share on other sites

Many thanks, this is currently my favorite oscillator, turned it into a scanner by adding the below code:

 

Value54=(UlcerIndex(RelativeStrength,40)/40-1);
	Plot88 (Value54,"ulcer");


If useradar = True then


{
if GetAppInfo( aiRealTimeCalc ) = 1 and OneAlert( Value15>.99 or Value15<-.99 ) then
RunCommand( ".NC" ) ; 
	RunCommand( Symbol ) ; }

If usescreenerR	Then
		begin	
		{If  value14[4]< -.95 and RelativeStrength <-.75 and RelativeStrength >-.95 and  Value54< 0 then}
		 If  value14[4]< -.55 and RelativeStrength[4] <-.55 and RelativeStrength >-.65 and  Value54< 0 then
		FileAppend(fname,  Numtostr(date,0)+ ","+Numtostr(time,0)+ ", Xcap value14[4]< 5 and RelativeStrength <25 and RelativeStrength >5  ," +symbol + "," +  Numtostr(Value14*100,0)+ "," + Numtostr(RelativeStrength*100,0) + "," + Numtostr(Value54,2) +newline);	


		If  value14[4]>.55     and RelativeStrength[4] >.55 and RelativeStrength <.65 and  Value54< 0 then
		FileAppend(fname,  Numtostr(date,0)+ ","+Numtostr(time,0)+ ", Xcap value14[4]> 95 and RelativeStrength <75 and RelativeStrength <95  ," +symbol + "," +  Numtostr(Value14*100,0)+ "," + Numtostr(RelativeStrength*100,0) + "," + Numtostr(Value54,2) +newline);
	END;

 

Also using suri.CharShow.slideshow to cycle symbols. I'm scanning on 180 min.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Topics

  • Posts

    • there is no avoiding loses to be honest, its just how the market is. you win some and hopefully more, but u do lose some. 
    • Date: 11th July 2025.   Demand For Gold Rises As Trump Announces Tariffs!   Gold prices rose significantly throughout the week as investors took advantage of the 2.50% lower entry level. Investors also return to the safe-haven asset as the US trade policy continues to escalate. As a result, investors are taking a more dovish tone. The ‘risk-off’ appetite is also something which can be seen within the stock market. The NASDAQ on Thursday took a 0.90% dive within only 30 minutes.   Trade Tensions Escalate President Trump has been teasing with new tariffs throughout the week. However, the tariffs were confirmed on Thursday. A 35% tariff on Canadian imports starting August 1st, along with 50% tariffs on copper and goods from Brazil. Some experts are advising that Brazil has been specifically targeted due to its association with the BRICS.   However, the President has not directly associated the tariffs with BRICS yet. According to President Trump, Brazil is targeting US technology companies and carrying out a ‘witch hunt’against former Brazilian President Jair Bolsonaro, a close ally who is currently facing prosecution for allegedly attempting to overturn the 2022 Brazilian election.   Although Brazil is one of the largest and fastest-growing economies in the Americas, it is not the main concern for investors. Investors are more concerned about Tariffs on Canada. The White House said it will impose a 35% tariff on Canadian imports, effective August 1st, raised from the earlier 25% rate. This covers most goods, with exceptions under USMCA and exemptions for Canadian companies producing within the US.   It is also vital for investors to note that Canada is among the US;’s top 3 trading partners. The increase was justified by Trump citing issues like the trade deficit, Canada’s handling of fentanyl trafficking, and perceived unfair trade practices.   The President is also threatening new measures against the EU. These moves caused US and European stock futures to fall nearly 1%, while the Dollar rose and commodity prices saw small gains. However, the main benefactor was Silver and Gold, which are the two best-performing metals of the day.   How Will The Fed Impact Gold? The FOMC indicated that the number of members warming up to the idea of interest rate cuts is increasing. If the Fed takes a dovish tone, the price of Gold may further rise. In the meantime, the President pushing for a 3% rate cut sparked talk of a more dovish Fed nominee next year and raised worries about future inflation.   Meanwhile, jobless claims dropped for the fourth straight week, coming in better than expected and supporting the view that the labour market remains strong after last week’s solid payroll report. Markets still expect two rate cuts this year, but rate futures show most investors see no change at the next Fed meeting. Gold is expected to finish the week mostly flat.       Gold 15-Minute Chart     If the price of Gold increases above $3,337.50, buy signals are likely to materialise again. However, the price is currently retracing, meaning traders are likely to wait for regained momentum before entering further buy trades. According to HSBC, they expect an average price of $3,215 in 2025 (up from $3,015) and $3,125 in 2026, with projections showing a volatile range between $3,100 and $3,600   Key Takeaway Points: Gold Rises on Safe-Haven Demand. Gold gained as investors reacted to rising trade tensions and market volatility. Canada Tariffs Spark Concern. A 35% tariff on Canadian imports drew attention due to Canada’s key trade role. Fed Dovish Shift Supports Gold. Growing expectations of rate cuts and Trump’s push for a 3% cut boosted the gold outlook. Gold Eyes Breakout Above $3,337.5. Price is consolidating; a move above $3,337.50 could trigger new buy signals. Always trade with strict risk management. Your capital is the single most important aspect of your trading business.   Please note that times displayed based on local time zone and are from time of writing this report.   Click HERE to access the full HFM Economic calendar.   Want to learn to trade and analyse the markets? Join our webinars and get analysis and trading ideas combined with better understanding of how markets work. Click HERE to register for FREE!   Click HERE to READ more Market news.   Michalis Efthymiou HFMarkets   Disclaimer: This material is provided as a general marketing communication for information purposes only and does not constitute an independent investment research. Nothing in this communication contains, or should be considered as containing, an investment advice or an investment recommendation or a solicitation for the purpose of buying or selling of any financial instrument. All information provided is gathered from reputable sources and any information containing an indication of past performance is not a guarantee or reliable indicator of future performance. Users acknowledge that any investment in Leveraged Products is characterized by a certain degree of uncertainty and that any investment of this nature involves a high level of risk for which the users are solely responsible and liable. We assume no liability for any loss arising from any investment made based on the information provided in this communication. This communication must not be reproduced or further distributed without our prior written permission.
    • Back in the early 2000s, Netflix mailed DVDs to subscribers.   It wasn’t sexy—but it was smart. No late fees. No driving to Blockbuster.   People subscribed because they were lazy. Investors bought the stock because they realized everyone else is lazy too.   Those who saw the future in that red envelope? They could’ve caught a 10,000%+ move.   Another story…   Back in the mid-2000s, Amazon launched Prime.   It wasn’t flashy—but it was fast.   Free two-day shipping. No minimums. No hassle.   People subscribed because they were impatient. Investors bought the stock because they realized everyone hates waiting.   Those who saw the future in that speedy little yellow button? They could’ve caught another 10,000%+ move.   Finally…   Back in 2011, Bitcoin was trading under $10.   It wasn’t regulated—but it worked.   No bank. No middleman. Just wallet to wallet.   People used it to send money. Investors bought it because they saw the potential.   Those who saw something glimmering in that strange orange coin? They could’ve caught a 100,000%+ move.   The people who made those calls weren’t fortune tellers. They just noticed something simple before others did.   A better way. A quiet shift. A small edge. An asymmetric bet.   The red envelope fixed late fees. The yellow button fixed waiting. The orange coin gave billions a choice.   Of course, these types of gains are rare. And they happen only once in a blue moon. That’s exactly why it’s important to notice when the conditions start to look familiar.   Not after the move. Not once it's on CNBC. But in the quiet build-up— before the surface breaks.   Enter the Blue Button Please read more here: https://altucherconfidential.com/posts/netflix-amazon-bitcoin-blue  Profits from free accurate cryptos signals: https://www.predictmag.com/ 
    • What These Attacks Look Like There are several ways you could get hacked. And the threats compound by the day.   Here’s a quick rundown:   Phishing: Fake emails from your “bank.” Click the link, give your password—game over.   Ransomware: Malware that locks your files and demands crypto. Pay up, or it’s gone.   DDoS: Overwhelm a website with traffic until it crashes. Like 10,000 bots blocking the door. Often used by nations.   Man-in-the-Middle: Hackers intercept your messages on public WiFi and read or change them.   Social Engineering: Hackers pose as IT or drop infected USB drives labeled “Payroll.”   You don’t need to be “important” to be a target.   You just need to be online.   What You Can Do (Without Buying a Bunker) You don’t have to be tech-savvy.   You just need to stop being low-hanging fruit.   Here’s how:   Use a YubiKey (physical passkey device) or Authenticator app – Ditch text message 2FA. SIM swaps are real. Hackers often have people on the inside at telecom companies.   Use a password manager (with Yubikey) – One unique password per account. Stop using your dog’s name.   Update your devices – Those annoying updates patch real security holes. Use them.   Back up your files – If ransomware hits, you don’t want your important documents held hostage.   Avoid public WiFi for sensitive stuff – Or use a VPN.   Think before you click – Emails that feel “urgent” are often fake. Go to the websites manually for confirmation.   Consider Starlink in case the internet goes down – I think it’s time for me to make the leap. Don’t Panic. Prepare. (Then Invest.)   I spent an hour in that basement bar reading about cyberattacks—and watching real-world systems fall apart like dominos.   The internet going down used to be an inconvenience. Now, it’s a warning.   Cyberwar isn’t coming. It’s here.   And the next time your internet goes out, it might not just be your router.   Don’t panic. Prepare.   And maybe keep a backup plan in your back pocket. Like a local basement bar with good bourbon—and working WiFi.   As usual, we’re on the lookout for more opportunities in cybersecurity. Stay tuned.   Author: Chris Campbell (AltucherConfidential) Profits from free accurate cryptos signals: https://www.predictmag.com/   
    • DUMBSHELL:  re the automation of corruption ---  200,000 "Science Papers" in academic journal database PubMed may have been AI-generated with errors, hallucinations and false sourcing 
×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.