1108

CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

  • Upload
    vuthuan

  • View
    215

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 2: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CYCLEANALYTICS

FORTRADERS

Page 3: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CYCLEANALYTICSFORTRADERS

AdvancedTechnical

Page 4: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

TradingConcepts

JohnF.Ehlers

Page 5: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 6: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Coverimage:Chart©iStockphoto.com/AndreyProkhorovCoverdesign:WileyCopyright©2013byJohnF.Ehlers.Allrightsreserved.PublishedbyJohnWiley&Sons,Inc.,Hoboken,NewJersey.PublishedsimultaneouslyinCanada.Nopartofthispublicationmaybereproduced,storedin

Page 7: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

aretrievalsystem,ortransmittedinanyformorbyanymeans,electronic,mechanical,photocopying,recording,scanning,orotherwise,exceptaspermittedunderSection107or108ofthe1976UnitedStatesCopyrightAct,withouteitherthepriorwrittenpermissionofthePublisher,orauthorizationthroughpaymentoftheappropriateper-copyfeetotheCopyright

Page 8: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ClearanceCenter,Inc.,222RosewoodDrive,Danvers,MA01923,(978)750-8400,fax(978)646-8600,orontheWebatwww.copyright.com.RequeststothePublisherforpermissionshouldbeaddressedtothePermissionsDepartment,JohnWiley&Sons,Inc.,111RiverStreet,Hoboken,NJ07030,(201)748-6011,fax(201)748-6008,oronlineatwww.wiley.com/go/permissions

Page 9: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

LimitofLiability/DisclaimerofWarranty:Whilethepublisherandauthorhaveusedtheirbesteffortsinpreparingthisbook,theymakenorepresentationsorwarrantieswithrespecttotheaccuracyorcompletenessofthecontentsofthisbookandspecificallydisclaimanyimpliedwarrantiesofmerchantabilityorfitnessforaparticularpurpose.Nowarrantymaybecreatedor

Page 10: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

extendedbysalesrepresentativesorwrittensalesmaterials.Theadviceandstrategiescontainedhereinmaynotbesuitableforyoursituation.Youshouldconsultwithaprofessionalwhereappropriate.Neitherthepublishernorauthorshallbeliableforanylossofprofitoranyothercommercialdamages,includingbutnotlimitedtospecial,incidental,consequential,orother

Page 11: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

damages.Forgeneralinformationonourotherproductsandservicesorfortechnicalsupport,pleasecontactourCustomerCareDepartmentwithintheUnitedStatesat(800)762-2974,outsidetheUnitedStatesat(317)572-3993orfax(317)572-4002.Wileypublishesinavarietyofprintandelectronicformatsandbyprint-on-

Page 12: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

demand.Somematerialincludedwithstandardprintversionsofthisbookmaynotbeincludedine-booksorinprint-on-demand.IfthisbookreferstomediasuchasaCDorDVDthatisnotincludedintheversionyoupurchased,youmaydownloadthismaterialathttp://booksupport.wiley.com.FormoreinformationaboutWileyproducts,visitwww.wiley.com.

Page 13: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

LibraryofCongressCataloging-in-PublicationData:Ehlers,JohnF.,1933-Cycleanalyticsfortraders:advancedtechnicaltradingconcepts/JohnF.Ehlers.pagescmISBN978-1-118-72851-2(cloth)—ISBN978-1-118-72841-3(ebk)—ISBN978-1-118-72860-4(ebk)1.Technicalanalysis

Page 14: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

(Investmentanalysis)2.Investmentanalysis.I.Title.HG4529.E3882014332.63′2042—dc23

2013034306

Page 15: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CONTENTS

Cover

HalfTitle

TitlePage

CopyrightPage

Page 16: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Preface

AbouttheAuthor

Chapter1:UnifiedFilterTheory

TransferResponseNonrecursiveFilters

Page 17: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

RecursiveFiltersGeneralizedFiltersProgrammingtheFiltersWaveAmplitude,Power,andDecibels(dB)

Page 18: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

KeyPointstoRemember

Chapter2:SMAs,EMAs,orOther?

SimpleMovingAverages(SMAs)Exponential

Page 19: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

MovingAverages(EMAs)WeightedMovingAverages(WMAs)MedianFilterKeyPointstoRemember

Page 20: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Chapter3:SmoothingFiltersonSteroids

NonrecursiveFiltersModifiedSimpleMovingAveragesModifiedLeast-Squares

Page 21: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

QuadraticsSuperSmootherSuperSmootherFilterApplicationsKeyPointstoRemember

Chapter4:DecyclersDecycler

Page 22: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ConstructionDecyclerApplicationDecyclerOscillatorKeyPointstoRemember

Chapter5:Band-PassFilters

Page 23: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Band-PassFilterBand-PassFilterQAutomaticGainControl(AGC)SpectralDilationRemoval

Page 24: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Band-PassFilterMeasuringtheCyclePeriodKeyPointstoRemember

Chapter6:MarketStructureandtheHurstCoefficient

Page 25: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

FractalDimensionComputingtheHurstCoefficientTheHurstCoefficientinActionDrunkard'sWalk

Page 26: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

HypothesisforMarketStructureKeyPointstoRemember

Chapter7:SpectralDilation

FrequencyContentof

Page 27: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

IndicatorOutputsRoofingFilterasanIndicatorImpactofSpectralDilationonConventionalIndicatorsKeyPointsto

Page 28: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Remember

Chapter8:Autocorrelation

BackgroundAutocorrelationAutocorrelationPeriodogramAutocorrelationReversals

Page 29: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

KeyPointstoRemember

Chapter9:FourierTransforms

SpectralDilationDiscreteFourierTransform

Page 30: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

(DFT)KeyPointstoRemember

Chapter10:CombFilterSpectralEstimates

SpectralDilationComputinga

Page 31: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CombFilterSpectralEstimateKeyPointstoRemember

Chapter11:AdaptiveFilters

AdaptiveRelative

Page 32: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

StrengthIndex(RSI)AdaptiveStochasticIndicatorAdaptiveCCI(CommodityChannelIndex)AdaptiveBand-Pass

Page 33: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

FilterAdaptiveIndicatorComparisonKeyPointstoRemember

Chapter12:TheEvenBetterSinewaveIndicator

Page 34: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

EvenBetterSinewaveApproachEvenBetterSinewaveDescriptionUsingtheEvenBetterSinewaveIndicator

Page 35: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

KeyPointstoRemember

Chapter13:Convolution

TheoreticalFoundationHeatMapDisplayComputing

Page 36: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ConvolutionKeyPointstoRemember

Chapter14:TheHilbertTransformer

AnalyticSignalsHilbertTransformer

Page 37: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

MathematicsComputingtheHilbertTransformerTheHilbertTransformerIndicatorUsingtheHilbertTransformerto

Page 38: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ComputetheDominantCycleDualDifferentiatorPhaseAccumulationHomodyneKeyPointstoRemember

Page 39: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Chapter15:IndicatorTransforms

FisherTransformInverseFisherTransformCubeTransformKeyPointstoRemember

Page 40: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Chapter16:SwamiCharts

SwamiChartsOverviewSwamiChartsRSISwamiChartsStochasticRollYourOwnSwamiCharts

Page 41: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

KeyPointstoRemember

Chapter17:Swing-TradingStrategies

ConventionalWisdomAnticipatingtheTurningPoint

Page 42: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

SineWaveUniquenessSafetyValveExitingaTradeStopLossEvaluatingaTradingStrategyMonteCarloEvaluation

Page 43: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

StockSpotter.comKeyPointstoRemember

AbouttheWebsite

Index

BookCard

Page 44: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

PREFACE

It has been over 10 yearssince Rocket Science forTraders was published. Inthosedays, technicalanalysiswasprimarilytheprovinceoffutures traders, whileportfolio theory andfundamental analysis

Page 45: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

comprised the conventionalwisdom for equity traders.However, there have beenprofound changes in themarketplace since that time.Futures trading has lostpopularity because ofscandalsinvolvingsegregatedcustomer accounts, the stockmarket's relentless trendupwardhasbeenbrokenwiththeresultthatbuy-and-holdisno longer a valid investmentstrategy, and new trading

Page 46: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

vehicles such as exchange-traded funds (ETFs) haveevolved. In addition,commission rates havedecreased, and the Internethas made electronic tradingavailabletoeveryone.Allthishas caused investors to bemore involved in the tradingprocessandinterestedinself-directed trading. Majorbrokerage houses haveresponded by includingtechnical analysis tools in

Page 47: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

theirtradingplatforms.Thisisatechnicalresource

bookwritten for self-directedtraders who want tounderstand the scientificunderpinnings of the filtersand indicators they use intheir trading decisions ratherthan to use the trading toolsonblindfaith.Thereisplentyof theory and years ofresearch behind the uniquesolutions provided in this

Page 48: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

book, but the emphasis is onsimplicity rather thanmathematical purity. Inparticular, thesolutionsuseapragmatic approach to attaineffective trading results. Theconcepts are presented sothey can be understood withonlyabackgroundinalgebra.Thewritingstyle in thebookis intentionally terse so thereader doesn't need to wadethroughamountainofwordsto find the ideas being

Page 49: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

presented. EasyLanguagecomputer code is used tocalculate and display theindicators. From myviewpoint, EasyLanguage isjust a dialect of Pascal withkey words for trading.Therefore,thecodeshouldbenearlyasreadableasEnglish.Cycles are unique because

they are one of the fewcharacteristicsofmarketdatathat can be scientifically

Page 50: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

measured. However, cyclemeasurement is extremelycomplex. In themostgeneralsense,thereisatripleinfinityof parameters–period, phase,and amplitude–that must beidentified simultaneously tocompletely describe thecycles. Additionally, marketcycles are ephemeral and areoftenburiedinpurenoise.Sothe compromises begin. Oneof the first realizations that atrader must make is that

Page 51: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

cycles cannot be the basis oftradesallthetime.Sometimesthe cycle swings areswamped by trends, and it isfolly to try to fight the trend.However, the cyclic swingscanbehelpful toknowwhento buy on a dip in thedirection of the trend.Traditional indicatorssuchasStochastics, relative strengthindex (RSI),moving averageconvergence/divergence(MACD), and commodity

Page 52: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

channel index (CCI) aresubject to the sameconstraints,andthereforethisbook will lead to a greaterunderstandingofalltechnicalindicators.Most important, Cycle

Analytics for Traders willallowtraderstothinkoftheirindicators and tradingstrategies in the frequencydomain as well as theirmotions in the time domain.

Page 53: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

This new viewpoint willenablethemtoselectthemostefficient filter lengths for thejob at hand.Thedescriptionsarewritten for understandingat several different levels.Traders with littlemathematical backgroundwillbeable toassessgeneralmarket conditions to theiradvantage. More technicallyadvanced traderswillbeableto create indicators andstrategies that automatically

Page 54: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

adapt to measured marketconditions by usingcombinations of computercodethataredescribed.So what should a trader

take away from this book?These are a few of the newconceptsthatIhaverankedinpriority:

An awareness ofSpectral Dilation, andhowtoeliminateitor to

Page 55: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

useittoyouradvantage.How to use automaticgain control (AGC) tonormalize indicatoramplitudeswings.Thinkingofpricesinthefrequency domain aswell as in the timedomain.An awareness that allindicators are statisticalrather than absolute, asimplied by their single-linedisplays.

Page 56: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Several advancedcookbook filters. Theseinclude theSuperSmoother, roofingfilter, even bettersinewave, decycler, andHilbert TransformIndicator.Several differentmethods of estimatingmarket spectra andsifting out the dominantcycle, with theautocorrelation

Page 57: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

periodogram being thepreferredmethod.How to use transformsto improve the displayand interpretation ofindicators.

The concepts I havedeveloped and derived fromscientific principles are newand useful aids to short-termtrading. Ultimately, tradingcomes down to buying andselling decisions. These

Page 58: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

decisionsarenevereasy, andinthefinalchapterIunitetheconceptswith a few tips andtricks that I have acquired inmy years of trading. Aboveall, trading should beapproached as a statisticalprocess. Even with a goodperformance of 60 percentwinning trades, 60 percent isalotcloserto50–50thanitisto 100 percent regarding asingle event. Therefore, theperformancejudgedbyafew

Page 59: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

tradesis invalid,andIwouldencourage readers to stickwith a trading strategy theyhave developed with aprofitable history, albeithypothetical, and let thestatistics be the light tosuccessinthelongrun.Asevidenceofmywarped

senseofhumor, eachchapterstarts with a “Tom Swifty”pun that encapsulates theentire content of the chapter

Page 60: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

and I hope serves as ananchor for the reader'smemory.Ithinkthecomputercode is often the mostsuccinctandefficientmethodof describing a concept.Accordingly,mystyleistobebrief, with plenty of poeticlicense with mathematicalnotation in an effort toconvey the concepts to mosttraders. Each chapterconcludeswiththesignificantpointstorememberfromthat

Page 61: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

chapter.Iwishyouallgoodtrading.

JohnF.EhlersAugust2013

Page 62: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ABOUTTHEAUTHOR

John Ehlers is an electricalengineer, receivinghisBSEEand MSEE from theUniversity of Missouri. Hedid his doctoral work at TheGeorge Washington

Page 63: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

University, specializing inFields & Waves andInformation Theory. He hasretiredasaseniorengineeringfellowfromRaytheon.Hehasbeen a private trader since1976.John is a pioneer in

introducing the MESAcycles-measuring algorithmand the use of digital signalprocessing in technicalanalysis. He developed

Page 64: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

maximum entropy spectrumanalysis (MESA) over threedecades ago. The programhas evolved with theincreasedcapacityofmoderncomputers.John has written

extensivelyaboutquantitativealgorithmic trading usingadvancedDSP (digital signalprocessing) and has spokeninternationallyonthesubject.HisbooksincludeMESAand

Page 65: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Trading Market Cycles,Rocket Science for Traders,and Cybernetic Analysis forStocks and Futures. Hisapproach is unique. Anytechniquemust firstwork ontheoretical waveforms beforetestingagainstreal-worlddataisattempted.John is a cofounder of

StockSpotter.com.

Page 66: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CHAPTER1

UnifiedFilterTheory

“It is toocomplex,”saidTomsimply.

Page 67: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Simplicity is at the heart oftheconceptoflinearsystems.Inputdataaresuppliedtothesystem, and the systemprovides the resultant as anoutput. There is only oneinput and only one output.However,thesystembetweentheinputandoutputcanbeascomplex as desired. Theoutputdividedbytheinputisthe transfer response of thesystem. It is this transfer

Page 68: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

response that describes theactionofthesystem.In this chapter you will

find the difference betweennonrecursive filters andrecursive filters, andcombinations of the two,enablingyoutoselectthebestfilter for each application. Inaddition, you will find thatthe responses in the timedomain and in the frequencydomain are intimately

Page 69: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

connected. When designingfilters for trading, it isbeneficial to consider theresponse in both of thesedomains. It is important toremember that no filter ispredictive—filter responsesare computedon thebasisofhistoricaldatasamples.Bythinkingintermsofthe

transfer responses, you willeasily make the transitionbetween filter theory and

Page 70: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

programming the filters inyourtradingplatform.

Page 71: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ TransferResponseConsider a four-bar simplemoving average. The inputdataarethelastfoursamplesof price. The filter output isone-fourthof themost recentprice data plus one-fourth ofthe data sample delayed byonebarplusone-fourthofthedata sample delayed by two

Page 72: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

bars plus one-fourth of thedata sampledelayedby threebars. Ifwe allow the symbolZ −1 to represent one unit ofdelay, then we can write anequation for the transferresponse of a simplemovingaverage(SMA)as:

(1-1)

Thevaluesof¼arecalledthe coefficients of the filter.In general, the filter

Page 73: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

coefficients sum to 1, so theratiooftheinputtotheoutputis1if theinputisaconstant.Ifwechoosetogeneralizethefilter to be other than anSMA, the values of thecoefficients canbearbitrarilyassigned. Further, we canextend the filter to have anyarbitrary length. In this case,the filter transfer responsecanbewrittenas:

(1-2)

Page 74: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The interesting thingaboutthis equation is thatwe havenow written the transferresponse as a generalizedalgebraic polynomial. Thepolynomial can have as highanorderasdesired.Thefiltergeneralitycanbe

extended by writing thetransfer response as the ratiooftwopolynomialsas:

(1-3)

Page 75: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

This equation completelydescribes the transferresponse of any filter. Theonly thing that differentiatesone filter fromanother is theselection of the coefficientsof the polynomials. It isimmediatelyapparentthatthemore fancy and complex thefilterbecomes,themoreinputdataisrequired.Thisisreally

Page 76: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

badforfiltersusedintradingbecause using more datameans the filter necessarilyhasmorelag.Minimizinglagin trading filters is almostmore important than thesmoothing that is realized byusing the filter. Therefore,filters used for trading bestusearelativelysmallamountof input data and should benotbecomplex.Although mathematicians

Page 77: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

will cringe at the notation,filter computations canperhaps be better understoodby simplifying Equation 1-3as:

Clearing fractionsbycrossmultiplying, we get anequation useful forprogramming:

(1-4)

Page 78: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Equation 1-4 says that thefilter output is comprised oftwo parts. The first part, thenumerator term, uses onlyinputdatavalues.Ifthatistheonly term used in the filter,the filter is said to benonrecursive. The secondpart, the denominator term,consists of previously

Page 79: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

computed values of theoutput. Filters using anypreviously computed valuesof the output are said to berecursive. The distinction isimportant because it isdifficult to create recursivefilters in some computerlanguages used for trading.Parenthetically, thecoefficienta0 isusuallyunitytokeepthingssimple.

Page 80: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■NonrecursiveFiltersA nonrecursive filter is onewhere the output responsedepends only on the inputdata and does not use aprevious calculation of theoutput to partially determinethe current value of the

Page 81: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

output. Nonrecursive filtershave wide applications andthereforehaveacquiredmanydifferent names. Among thealiasesare:

MovingaveragefiltersFinite impulse response(FIR)filtersTappeddelaylinefiltersTransversalfilters

SMA filters are a specialcaseofmovingaveragefilters

Page 82: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

where all the filtercoefficients have the samevalue.One of themost important

filter characteristics to atrader is how much lag thefilter introducesat theoutputrelative to the input. Anonrecursive filter whosecoefficients are symmetricalabout the center of the filteralwayshasa lagequal to thedegreeofthefilterdividedby

Page 83: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

two. For example, anonrecursive filter of degreesix will have a three-bardelay. This delay is constantforallfrequencycomponents.Since lag is very important,and since lag is directlyrelated to filterdegree, filtersused for trading mostgenerally are simple and areoflowdegree.If the a0 coefficient equals

one and all the other “a”

Page 84: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

coefficientsarezero,themostgeneral transfer response isjust thesimplepolynomial inthe numerator. From thefundamental theorem ofalgebra, the polynomial canbe factored into as manycomplex roots as it hasdegrees. In other words, thetransfer response can bewrittenas:

(1-5)

Page 85: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The coefficients may becomplex numbers rather thanrealnumbers.Inthiscase,theroots of the polynomial arecalledthezerosofthetransferresponse. For example, thefour-bar SMA transferresponse is a polynomial ofdegreethreeandthereforehasthreerootsfactoredas:

(1-6)

This transfer response has

Page 86: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

one real root and twocomplementary imaginaryroots. If we substitute anexponential as exp(−j2π f) =Z −1, in the real root portionofEquation1-5,wegetusingDeMoivre'stheorem:

(1-7)

Page 87: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

This equation can be trueonly when the frequency ishalf the sampling frequency.Half the sampling frequencyis the highest frequency thatis allowable in sampled datasystemswithoutaliasing,andis called the Nyquistfrequency. In our case, thesamplingisdoneuniformlyatonce per bar, so the highestpossible frequency we canfilter is0.5cyclesperbar,ora period of two bars.

Page 88: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Equation 1-7 shows that thezero in the transfer responseoccursexactlyat theNyquistfrequency. We havesucceeded in completelycanceling out the highestpossible frequency in thefour-barSMA.We can see the frequency

characteristic of the transferresponse by starting with afive-element SMA and thengeneralizing.

Page 89: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Multiplying both sides ofthis equation by Z −1 andsubtracting that multiplicandfrom both sides of theequation,weobtain

Page 90: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

We get the frequencyresponse of this five-elementSMA by making thesubstitutionZ−1=exp(−j2πf), where f is the samplingfrequency.Then,

Page 91: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The equality of theexponential expressions andthe sine equivalent will berecognized by readersfamiliar with complexvariables as DeMoivre'stheorem. For readerswithoutthismath background, pleaseacceptitonfaith.

Page 92: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Generalizing this result foran N-length SMA, we havethe transfer response of anSMA in the frequencydomainexpressedas:

But since the Nyquistfrequency is half thesampling frequency, thetransfer response in thefrequencydomainis

Page 93: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

(1-8)where f = frequency relativetothesamplingfrequencyThe important conclusion

from this discussion is thatwe can think of the transferresponse with equal validityin the time domain or in thefrequencydomain.Whenweplottheresponse

ofthefour-elementSMAasafunction of frequency in

Page 94: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure1.1,weseethatwenotonly have a zero at theNyquistfrequency,butalsoatafrequencyof0.25.

Figure1.1FrequencyResponseofaFour-BarSimpleMovingAverage

Page 95: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 96: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The horizontal axis isplotted in termsof frequencyrather than the cycle periodthat is most familiar totraders.Frequencyandperiodhaveareciprocalrelationship,soafrequencyof0.25cyclesperbarcorrespondstoafour-bar period. The vertical axisistheamplitudeoftheoutputrelative to the amplitude ofthe input data in decibels. Adecibel (dB) is a logarithmic

Page 97: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

measure of the power in theoutput.Figure1.1shows thatthere are zeros in the filtertransfer response in thefrequency domain as well asinthetimedomain.Theconceptof thinkingof

how a filter works in thefrequency domain as well ashow it works in the timedomain is central to theunderstanding of theindicators that will be

Page 98: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

developed. Low frequenciesnear zero are passed frominput to output with little orno attenuation. Since higherfrequencies are blocked frombeing passed to the output,the SMA is a type of low-pass filter—passing lowfrequencies and blockinghigher frequencies. Low-passfiltersaredatasmoothersthatremove the higher-frequencyjitter in the input data thatoftenmakes the data hard to

Page 99: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

interpret. The penalty traderspay for this smoothing is thelag introduced in the transferresponse.Low-passfiltersarenotthe

only filters that can begenerated with thegeneralized transfer responseofEquation1-3.Supposewearrange to have thecoefficientstobeas:

Page 100: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

All other coefficients areequaltozero.Then the frequency

responseofthefilterisshowninFigure1.2.

Figure1.2FrequencyResponseofaTwo-BarDifferenceFilter

Page 101: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 102: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

In this case, the higherfrequencies are passed, andthe lower frequencies areseverely attenuated by thefilter.Thisisanexampleofahigh-pass filter. Since trendscanbeviewed as pieces of avery long cycle, a high-passfilter is basically a detrenderbecause the low-trendfrequenciesarerejectedinitstransferresponse.Since the coefficients of a

Page 103: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

simple high-pass filter areequivalent to just taking thedifferenceoftwoconsecutivesamples of input data, thedifference operation can beviewed as analogous to aderivative function in thecalculus. This conceptenables a high-pass filter tobe used in several differentways in trading to attempt tocreateapredictivewaveform.If the inputdataareassumedto be in a trend, then the

Page 104: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

difference between any twodata samples is constant. Inthis case, adding thedifference to the current bardatapredicts thevalueof theinput data for the nextsample. Alternatively, if theinputdataareassumedtobeaquiescent sinewave, a tradercanuse the relationship fromcalculusas:

(1-9)

Page 105: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Ifthefrequencyofthesinewaveisknown,thehigh-passfilter not only provides awaveformthatleadstheinputdatawaveformby90degrees,but also provides the meansto normalize the outputamplitudetotheamplitudeoftheinputdata.Returning to Equation 1-2

for a generalizednonrecursive filter, and

Page 106: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

factoring out a Z −N/2 term,weobtain:

(1-10)

SinceZ−N/2isapuredelayterm, and since exp(−j2π f )can be substituted for Z −1,Equation 1-10 is proof thatnonrecursive filters havingcoefficients symmetricalabout the center of the filterwill have a constant delay at

Page 107: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

all frequencies. Further, thatdelaywillbeexactlyhalf thedegree of the transferresponsepolynomial.

Page 108: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ RecursiveFiltersA recursive filter is onewhere the output responsedependsnotonlyontheinputdata but also on previousvalues of the output. Strictlyrecursive filters arecharacterizedbyusingonlyaconstantinthenumeratorandmultiple terms in the

Page 109: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

denominatorofEquation1-3.Recursive filters also havewide applications andthereforehaveacquiredmanydifferent names. Among thealiasesare:

Exponential movingaveragefiltersInfinite impulseresponse(IIR)filtersLadderfiltersAutoregressivefilters

Page 110: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

If the b0 coefficient is aconstantandalltheother“b”coefficientsarezero,themostgeneral transfer response isjust thesimplepolynomial inthe denominator. Thispolynomial can be factoredinto as many complex rootsas it has degrees. In otherwords, the transfer responsecanbewrittenas:

(1-11)

Page 111: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The coefficients may becomplex, rather than real,numbers. In this case, theroots of the polynomial arecalledthepolesofthetransferresponsebecauseazerointhedenominator of the transferresponse causes the transferresponse to go to infinity atthat point. One can visualizethe transfer response as thecanvasof a circus tent in thecontext of complex numbers,and the poles in the transfer

Page 112: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

responseareanalogoustothetentpoles.Whileitispossibleto choose coefficients thatcause the transfer function to“blow up,” frequencies areconstrained to be realnumbers, and therefore it isrelatively easy to avoid thecomplexpolelocations.Consider the special case

ofarecursivefilterwhere

Page 113: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Then, Equation 1-3becomes

Then, using theconventional notation thatOutput[1] equals the output

Page 114: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

onebarago:(1-12)

Equation 1-12 is exactlythe equation for anexponential moving average(EMA).Note that the sumofall of the coefficients on theright-handsideofEquation1-11 sum to1 so that the filterhasnonoisegain.Figure 1.3 shows the

frequency response of theEMAwhen alpha= 0.2.The

Page 115: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

EMA is a type of low-passfilter, passing the lower-frequency components of theinput data and attenuating itshigher-frequencycomponents.Ifalphaismadeto be smaller, fewer of thelower-frequency componentsare allowed to pass, and thehigh-frequency componentsare attenuated to a greaterdegree. Conversely, if alphaismade to be larger, there islesssmoothing,and therefore

Page 116: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

more higher-frequencycomponents of the input areallowedtopasstotheoutput.Therearenozeros (orpoles)inthetransferresponse.

Figure1.3ExponentialMovingAverageFrequencyResponseforα=0.2

Page 117: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 118: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ThelagofEMAfilterswillbederivedinChapter2.

Page 119: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ GeneralizedFiltersAgeneralizedfilterusesboththe numerator anddenominator of Equation 1-3to achieve a wider range ofresponsesotherthanlow-passfilteringandhigh-passfilters.Some familiar aliases forthesegeneralizedfiltersare:

Page 120: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Autoregressive movingaverage(ARMA)filtersAutoregressiveintegrated movingaverage(ARIMA)filters

A band-pass filter can becreated by connecting a low-pass filter in tandem with ahigh-pass filter so that boththe low-frequency and high-frequency components areattenuated and componentsnear a selected frequency are

Page 121: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

passed to the output.However, it is much moreefficient to create the band-passfilterresponsesimplybyselecting the propercoefficientsinEquation1-3.

Page 122: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ProgrammingtheFiltersIt is most convenient toconsiderfiltersas“stonewall”filters that have only a passbandandastopbandwiththeboundary between themlocated at a critical cycleperiod. For example, a

Page 123: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

smoothing low-pass filter onstock data might have acritical cycle period of 20bars because many stockshave monthly cycle periodsofapproximately20barsandthe smoothing wouldattenuate only those cycliccomponents shorter than 20bars.Band-pass filterswouldpass only cycle componentscentered at the critical cycleperiod. Band-stop filterswould reject only cycle

Page 124: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

components also centered atthecriticalcycleperiod.With the exception of

nonrecursive filters, onlyfiltersofdegreetwoareuseddue to lag considerations. Inthis case, Equation 1-3reducestoEquation1-13:

(1-13)

UsingthenotationthatZ−1* Input = Input[1], etc., and

Page 125: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

algebraically rearrangingEquation1-13,theexpressionthat can be used forprogramming becomesEquation1-14:

(1-14)

Beforeweassignthevalueofthe coefficients, it is mostconvenient to compute someconstants in terms of thecritical period. In thefollowing equations, the

Page 126: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

arguments of thetrigonometricfunctionsareindegrees.1

(1-15)

WhereK = 1 for single-polefilters

K = 0.707 for two-polehigh-passfiltersK = 1.414 for two-polelow-passfilters

Page 127: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

(1-16)Whereγ=Cos(360*/Period)

and δ = bandwith as afractionofPeriod(1-17)

Using these unifiedcalculations, the filtercoefficients for the varioustypes of filters can be foundinTable1.1.Table1.1FilterCoefficientsforVariousTypesofFilters

Page 128: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Simple two-pole filters arejust two single-pole filtersthat are serially connected.Filteringapreviously filteredoutputmeans thecoefficientsmustbeadjustedtoobtainthe

Page 129: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

same−3-dBattenuationatthedesired critical period.Equation 1-15 accomplishesthisbycomputingalphatermat a period where theattenuation is approximately−1.5 dB for each of the twocomponent filters. Thus, thetotal attenuation of theserially connect set is −3decibelsatthecriticalperiod.A trader may also serially

connect any of the conical

Page 130: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

filter types in Table 1.1 toobtain a more complexsystem to achieve an overalldesiredresult.Forexample,aband-pass filter output couldbetheinputtoanEMAfilterwithadifferentcriticalperiodtofurthersmooththedata.Asanother example, a low-passfiltercanbecombinedwithahigh-pass filter to create avery wide bandwidth band-passfilter.

Page 131: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

All the filters inTable 1.1have application to tradingwith the exception of theband-stop filter. Using theparameters in Table 1.1 theband-stop filter would moreappropriately be called anotch filter. That is, itattenuates a very narrowrangeoffrequencies.Itcouldbe used to remove 60-hertzpower line frequency fromaudio equipment, forexample. Market cycles tend

Page 132: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

to be ephemeris and havevery fuzzy bandwidths,making them difficult torejectbyfiltering.Evenmoresophisticatedband-stopfilterswith relatively wide stopbands do not seem to beeffective in removing cycliccomponents from the data.This is indeed unfortunatebecause removing cycliccomponents to isolate thetrends is a philosophicallyinteresting digital signal

Page 133: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

processingapproach.

Page 134: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ WaveAmplitude,Power, andDecibels(dB)The transfer response of afilter is expressed as theoutputrelativetotheinput.Inthe time domain, we canexamine the two waveforms

Page 135: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

tomakeacomparison.Waveshave three components:frequency, amplitude, andphase. It is generally moreconvenient for trading todescribe only the relativeamplitudes and delays. Wecan eliminate phase byexamining power rather thanwave amplitude. Thedifferencebetweenpowerandwave amplitude is analogousto describing a lightbulb asusing 60 watts rather than

Page 136: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

using 115 volts. Power isproportional to the square ofthe wave amplitude, and tobetter examine a wide rangeof power levels, relativepower isusuallymeasured ina logarithmic ratio calleddecibels.2Using V to represent

relative wave amplitude, thetransferresponseamplitudeisexpressedmathematicallyas

Page 137: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Some relative amplitudesusefultorememberare:

Page 138: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Key PointstoRemember

1.Allthecommonfiltersuseful for tradershaveatransfer response thatcanbewrittenasa ratiooftwopolynomials.2.Lag isvery importantto traders. Morecomplex filters can becreatedusingmoreinput

Page 139: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

data,butmoreinputdataincreases lag.Sophisticated filters arenot very useful fortrading because theyincurtoomuchlag.3. Filter transferresponse can be viewedin the time domain andthe frequency domainwithequalvalidity.4. Nonrecursive filterscan have zeros in the

Page 140: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

transfer response,enabling the completecancellation of someselected frequencycomponents.5. Nonrecursive filtershaving coefficientssymmetrical about thecenter of the filter willhave a delay of half thedegree of the transferresponse polynomial atallfrequencies.

Page 141: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

6. Low-pass filters aresmoothers because theyattenuate the high-frequency componentsoftheinputdata.7. High-pass filters aredetrenders because theyattenuate the low-frequency componentsoftrends.8. Band-pass filters areboth detrenders andsmoothers because they

Page 142: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

attenuate all but thedesired frequencycomponents.9. Filters provide anoutputonlythroughtheirtransfer response. Thetransfer response isstrictly a mathematicalfunction, andinterpretations such asoverbought, oversold,convergence,divergence, and so on

Page 143: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

are not implied. Thevalidity of suchinterpretations must bemade on the basis ofstatistics apart from thefilter.

Page 144: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Notes1. Sanjit K. Mitra,Digital SignalProcessing, 2nd ed.(New York: McGraw-Hill, 2000), Section4.5.2.

2.Adecibelisone-tenthof a bel, named afterAlexanderGrahamBell.Abeloriginalmeanttheapproximate power lost

Page 145: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

in one mile of standardtelephone cable, and isabout the least amountof change in audiodetectablebyahuman.

Page 146: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CHAPTER2

SMAs,EMAs,orOther?

“Everyone's children areabove average,” said

Page 147: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Tommeanly.

Moving averages arediscussed in this chaptersimply because they areubiquitous in technicalanalysis. There are manybetter filters for variousapplications that aredescribed in the followingchapters. Moving averageshave the advantage that theyare dirt-simple to compute.Theirdisadvantageisthatthe

Page 148: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

produceonlya small amountof smoothing for the cost oflagintheircomputation.One little-known fact is

thatasimplemovingaverageconstitutesabestfittodataintheleast-squaressense.

Page 149: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ SimpleMovingAverages(SMAs)SMAs are a special case ofnonrecursive filterswhere allthe coefficients are equal tounity divided by the numberof elements in the filter. At

Page 150: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

any given point in the datastream,theoutputofthefilteris just the average of dataover the span of the filter.When time is advanced byonebar inonealgorithm, thefractional part of the oldestdata sample is discarded andthe fractional newest datasampleisadded.Thus, it isa“moving” average. It justdoesn't getmore simple thanthat,andsoitisdeemedtobeasimplemovingaverage.

Page 151: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Viewed from anotherperspective, it canbeviewedas a “window” that is passedacross a fixed data stream.Only those data sampleswithin the window areaveraged and provided as anoutput of the filter. Sincemodern computers are veryfast, I recommend this latterapproach because if thelengthoftheaverageisvariedacross the data set, thecomputations will fail. We

Page 152: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

maywant tomake the lengthof the average vary whenadaptingthefiltertovolatilityorameasuredcycleperiod.Animpulseisatheoretical

data object that has zerowidthandinfiniteheight.Itisused to assess the filtertransfer response. Forexample, you can think of itas a clapper striking abell—the bell provides the transferresponse, and the ringing is

Page 153: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

theoutput.Inotherwords,theringing is the impulseresponseofabell.Insampleddata systems, we canapproximate an impulse as adata stream that has a valueonly at one point and haszeros at all other datasamples.If we slide the SMA

window across the impulsedata stream, the filter willhaveanoutputonlywhenthe

Page 154: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

impulse falls within thewindow of the filter. Thus,the impulse response of anSMA is finite, and thereforeanSMAisaspecialcaseofafinite impulse response (FIR)filter.Suppose we start a filter

design by trying to make itstransfer response be the bestfit to a straight line. If wehave more than two datapoints, this would be

Page 155: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

impossible in the generalcase.However,wecandefinea best fit, where the sum ofthesquaresofthedifferencesbetween the data and ourstraight line is minimum. Inthe case of five data points,designatedasux,wecanwritethedesiredfunctionas

We can minimize thisfunction by taking the

Page 156: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

derivatives of this functionwith respect to m and b andsetting those derivatives tozero. When we do this, wefind that the correct value ofb is just the average of thefive data points. This is trueregardless ofwhich five datapoints we select, so that anSMA is synonymous withfinding a best-fitting straightlinetothedata,atleastwhenthe lag of the filter isdisregarded.Ifindthistobea

Page 157: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

fascinating little-known factaboutSMAs.In Chapter 1, we showed

that thelagofanonrecursivefilter having coefficientssymmetrical about its centerpoint and of length N isexactly (N−1) / 2.SinceanSMA is a special case of anonrecursive filter, it is alsotruethatanSMAlagisalso

Equation 1-8 is repeated

Page 158: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

here as the amplitude of thetransferresponseofanSMA.

(2-1)At zero frequency,

Equation2-1evaluatesto1inthe limit.This starts the passbandoftheSMA.Thecriticalperiodofafilteroutputisthefrequencyatwhichtheoutputpowerof the filter ishalf thepower of the input wave atthat frequency. Since power

Page 159: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

is proportional to the squareofthewaveamplitude,weareinterested in finding thefrequencyatwhichtheoutputwave has an amplitude of0.707(thesquarerootof0.5).Knowing this, we can selectan SMA that gives us theapproximate critical periodweseek.Figure2.1showstherelationship between thecriticalperiodandthenumberofelementsintheSMA.

Page 160: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure2.1SMACritical

Page 161: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

PeriodasaFunctionofFilterLengthIt is a reasonable

approximation and easy toremember that the criticalperiodofanSMAistwiceitslength.The first zero in the

transfer response occurs thewhen the argument in thenumerator has a value of π.This occurswhen f = 1 / N.Subsequent zeros in the

Page 162: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

transfer response occurwhenthe argument in thenumerator are integermultiples of π. The firstmaximum in the stop bandoccurswhen the argument inthenumeratorcausesthesinefunctiontobeatamaximum,or f = 3π / 2. At thisfrequency the value of thetransfer response isapproximately 2 / (3π), or−13.3 decibels (dB). For thesame reason, the next

Page 163: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

maximum in the stop bandoccurs at f = 5π / 2, and theattenuation is 2 / (5π), or−17.8 dB. This amount ofattenuation is not substantial,and you will see methods tomodify an SMA to improveitsfilteringcapability.

Page 164: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ ExponentialMovingAverages(EMAs)An EMA is computed bytaking a fraction of thecurrent price added to thecomplementary fraction oftheEMAcalculation one bar

Page 165: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ago. The first fraction isusually called alpha, and canhave a value between zeroand one. The two fractionsmust sum to unity, so thesecondfractionmusthavethevalue of one minus alpha.The equation to compute anEMAis:

(2-2)

The EMA becomes amoving average by movingfrom bar to bar, from left to

Page 166: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

right,acrossthepricedata.Imagine a case where the

input data set has only onesampleatanamplitudeof1/α.When theEMA is appliedto these data, the first outputfrom the filter is unitybecause there was noprevious value for the EMA.On subsequent calculations,thepricevalueiszero,andsothe sequence of calculationsis:

Page 167: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Since the quantity (1 − α)must be less than one, theamplitude decays as theexponent of each succeedingcalculation from an impulseinput, hence the name

Page 168: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

exponential moving average.Inprinciple,apartofanydatainput remains in subsequentcalculations, although thecontribution becomesvanishingly small. ThisattributemakesanEMApartof a general class of filterscalled infinite impulseresponse(IIR)filters.It is instructive toexamine

the EMA response to a stepfunction.A step functionhas

Page 169: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

a series of constant valuesand then jumps to anotherseries of constant values.Assume the price has beenzerofora longtimeandthensuddenlyjumpsuptoavalueof1andmaintains thatvaluethereafter. On the first bar,theEMAwillhaveavalueofα. On the second bar, thevaluewillbeα+α*(1−α).On the third bar, the valuewillbeα+α*(1−α)+α*

Page 170: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

(1−α)2,andsoon.TheEMAwill gradually approach thevalue of 1. A common errorinprogramming is to insertavalue for α, such as .2, andinserting another number for(1 − α), such as .9. The twoterms must sum to unity orthe recursive algorithm willleadtoerraticresultsormighteven cause your computer tocrash. You should alwayscheckyourcomputercode to

Page 171: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ensurethatthetwotermssumtounity. I amsocautiousonthis point that I assign thevalue α as a global variableand write out the EMAequation in terms of α. Byletting the computer do thework, I know the two termsmustsumcorrectly.Wecanassertthattheprice

onday“d”isd.Ifweassumethe lag of the EMA is “L,”then the current value of the

Page 172: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

EMAis (d−L).Further, theprevious EMAwould have avalue of (d − L − 1), sinceprice is rising one unit perbar.Putting thesevalues intotheequationfortheEMA,weobtain

This equation shows that

Page 173: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

we can select an acceptablelag and, from that lag,computethealphatermoftheEMA.Forexample,ifwecanaccept a three-bar lagresulting from the EMA, wewoulduseα=0.25.WecanalsorelateanEMA

to an SMA on the basis oftheir equivalent static lags.Recalling that the lag of anSMAis(N−1)/2foranN-bar SMA, we can substitute

Page 174: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

this value of lag into thealphacalculationoftheEMAas

(2-3)

This is the relationshipbetween an N-bar SMA andthe alpha of an EMA that isquoted in most technicalanalysis books. Thefrequencyresponsesofafive-

Page 175: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

bar SMA and its EMAequivalent are compared inFigure 2.2. Figure 2.3 showsthat the lagsof theSMAandEMA are equal only at zerofrequency.

Figure2.2FrequencyResponseComparisonofaFive-BarSMAandSimilarEMA

Page 176: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 177: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure2.3LagResponseofEMAComparedtoaConstantTwo-BarLagofaFive-BarSMA

Page 178: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 179: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Although the lags at staticfrequencies align, note thatthecriticalperiodoftheEMAisnotalignedwiththatoftheSMA.Wecanobtainabettercalculation for the fraction αby examining the transferresponseoftheEMA.

Page 180: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ WeightedMovingAverages(WMAs)ItappearsthattheWMAwasinventedby a traderwhodidnothaveafirmgraspoffiltertheory in hopes of reducinglag.

Page 181: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

A WMA is an FIR filterhaving coefficientsasymmetrically weightedabout the center point of thefilter. The most recent datasample is weighted mostheavily, the second mostrecent data sample weightedsomewhat less, and so on.The weighting does notnecessarily have to be linearwiththedatasample,butthatis the most common usage.For our graphical example, I

Page 182: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

willuseafive-elementWMAwhosecoefficientsare [5432 1] / 15. Figure 2.4 showsthefrequencyresponseofthisfilter, and Figure 2.5 showsitslagresponse.

Figure2.4AWMAHasPoorRejectioninItsTransferResponse

Page 183: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 184: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure2.5LagofaFive-ElementWMAHasNoOutstandingCharacteristics

Page 185: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 186: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure 2.4 shows that aWMAhas poorer attenuationthan the equivalent SMAshown inFigure2.2 and thataWMA hasmore lag in thepassbandthantheequivalentEMAshowninFigure2.3.Inshort, a WMA has little torecommend itself comparedto theothercommonmovingaverages.

Page 187: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ MedianFilterThere are times when amedian filter is the mostappropriate filter to use. It isbest applied when the datacontains impulsive noise orwhen there are widevariationsinthedata,suchasvolumedata.Itspurposeistoattempttodiscardoutlierdata

Page 188: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

samplestoavoidhavingthemexertaninordinateimpactontheaverage.A median filter simply

picks the middle value of asample set of data after thesamples have been ranked.Thisselectioniseasiestwhenan odd number of datasamples is used. Todemonstrate the effect of amedian filter, consideradataset consisting of four

Page 189: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

samples, eachhavingavalueof1andonesamplethathasavalue of 6.The data samplescanappearinanyorder.Afterranking, the center value isjust 1. Therefore the medianvalue is 1,which happens tobe the value of most of thedata samples. However, theaveragevalueis(4+6)/5=2. That one outlier datasample has severely skewedthe average, and the medianfilter best recovers the

Page 190: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

“average” value of the dataset.

Page 191: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Key PointstoRemember

1. The critical perioddefiningthepassbandofan SMA isapproximately twice thelengthofthefilter.2. An N-length SMAwill have a lag of (N −1) / 2 bars at allfrequencies.

Page 192: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

3. An EMA shouldalways be written asEMA=α*Input+(1−α) * EMA[1] to avoidcomputational errors inevaluating the fractionalcoefficient.4. The fractionalcoefficient of an EMAequivalent to an N-length SMA iscalculated asα=2 / (N−1).

Page 193: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

5. AWMA has little ornoredeemingvirtue.6.Amedianfilterisbestused when the datacontain impulsive noiseor when there are wildvariations in the data.Smoothing volume dataisoneexampleofagoodapplication for amedianfilter.

Page 194: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CHAPTER3

SmoothingFiltersonSteroids

“Steroids are for guys

Page 195: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

who want to cheat theiropponents,” said Tomcombatively.

The objective of smoothingfilters in trading is to get thehighest degree of smoothingpossiblewithin the constraintof inducing the least amountof lag. The purpose of thischapter is to develop thosekinds of filters for traders.Then, it isup to the trader tointerpret the results of the

Page 196: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

filtering.Noneofthesefiltersare predictive.None of thesefiltersexplainmarketactivity.

Page 197: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■NonrecursiveFiltersAny nonrecursive filterhaving coefficientssymmetrical about the centerpointof the filter andhavinga polynomial of odd degreewillalwayshavearootofthepolynomial at the Nyquist

Page 198: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

frequency. This is importantbecause completely rejectingthe highest possiblefrequency component in thefilteroutputgoes a longwaytowardnoisereduction.Noisereduction is the principalpurposeofasmoothingfilter.Since the degree of the

polynomial is one less thanthenumberofelementsinthefilter, nonrecursive filtershaving the number of

Page 199: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

elementsas2,4,6,8,10,andso on will have thischaracteristic.Sincethelagofnonrecursivefiltersishalfthedegree of the filter, thesefilters will have lags of 0.5,1.5, 2.5, 3.5, and 4.5 bars,respectively.Filterdesignnotonly depends on the amountofsmoothingdesired,butalsoontheamountoflagthatcanbetolerated.As a shorthand notation,

Page 200: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

[b0 b1 b2 b3 . . . bN] / S isintroduced to describe thecoefficients of nonrecursivefilters.Forexample,[1111]/ 4 describes the coefficientsof a four-element simplemoving average (SMA). Infact,afour-elementSMAfitsthecriterionofhavingazeroat the Nyquist frequency. Itsfrequency response is shownin Figure 3.1. This figureshows that a four-bar cycle

Page 201: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

period (frequency = 0.25) isalso rejected. The criticalfrequency is the−3 dBpointin the response. The −3 dBpoint along the frequencyaxis is where the output isattenuatedtobehalftheinputpower.Inthiscasethecriticalfrequency is approximately0.1 cycles per bar,corresponding to a 10-barcycle period.The attenuationcharacteristic between a two-bar cycle period and a four-

Page 202: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

barcycleperiodrisestoabout−12 decibels (dB), whichmeans thewaveamplitudeattheoutputisabout25percentoftheamplitudeattheinput.

Figure3.1FrequencyResponseofa[1111]/4NonrecursiveFilter

Page 203: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 204: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The expectation ofobtainingmoresmoothingbyincreasing the length of theSMA leads us to examine asix-element nonrecursivefilterwhoseelementsare[111 1 1 1] / 6. The frequencyresponse of this filter isshown in Figure 3.2.Increasing the degree of thepolynomial introducedanother zero in the transferresponse polynomial so that

Page 205: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

two-, three-, and five-barcycle periods are completelyeliminated at the output.However, attenuationbetween the rejection pointsisnotchangedwithrespecttothe lobe number, and is onlyslightly increased from lobetolobe.Thecriticalperiodofthis filter is increasedcomparedtothefour-elementSMAtobeata13.7-barcycleperiod.

Page 206: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure3.2FrequencyResponseofa[111111]/6NonrecursiveFilter

Page 207: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 208: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Nonrecursivefiltersarenotrestricted to be SMAs. Thecoefficients can be weightedsymmetrically about thecenter of the filter. Amongthemost simpleof these is afilter whose coefficients are[1 2 2 1] / 6. The frequencyresponse of this filter isshown in Figure 3.3.Comparing this nonrecursivefiltertotheSMAoflikeorder(in Figure 3.1), we see that

Page 209: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

not only have the cycleperiods that are completelyrejected are two- and three-bar cycle periods as opposedto two- and four-cycleperiods. In addition, theattenuation between therejection frequencies rises toa minimum of −25 dB,meaningtheoutputwaveformamplitude is less than 5.6percentoftheinputamplitudein this rejection band. Theincreased attenuation comes

Page 210: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

at the expense of a decreasein the critical cycleperiod toa 7.4-bar cycle. The filterdelayremainsthesameat2.5bars.

Figure3.3FrequencyResponseofa[1221]/6NonrecursiveFilter

Page 211: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 212: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

From our experience withSMAs,we can improve boththe smoothing and therejection band attenuation byincreasing the degree of thefilter (at the expense ofincreasedlag).Thefrequencyresponseof a [123321] /12 nonrecursive filter isshown in Figure 3.4. In thiscase, two-, three-, and four-bar cycle periods arecompletely eliminated from

Page 213: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

theoutputofthefilterandtherejection in the stop bands isstill greater than −25 dB.Filteringisimprovedbecausethe critical period has beenincreased to be at a 10.9-barcycleperiod.All this is doneat the expense of a delay of3.5bars.Whilethisisaprettynicefilter,wecandobetter.

Figure3.4FrequencyResponseofa[123321]/12NonrecursiveFilter

Page 214: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 215: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ ModifiedSimpleMovingAveragesAn interesting fact is that ifthevaluesofthefirstandlastelements of an SMA havinganevendegreearecutinhalf,then one is guaranteed adouble zero in the transferresponse at the Nyquist

Page 216: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

frequency. For example, afive-element (four-degree)SMAwouldhavecoefficientsas [0.5 1 1 1 0.5] / 4. Thetransfer response of a five-element modified SMA isshown in Figure 3.5 forcomparisontotheresponseofa four-element SMA showninFigure3.1.Notonlydowehave the double zero at theNyquist frequency and thesamezeroata four-barcycleperiod, but we also have

Page 217: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

increased the minimumattenuation between the twozeros to be −20 dB, whichmeanstheoutputamplitudeisonly 10 percent of the inputdata amplitude. Thisimproved filteringperformance comes at theexpenseofonlyahalfbarofdelaybecausewewentfromafour-element filter to a five-elementfilter.

Figure3.5Frequency

Page 218: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ResponseofaFive-ElementModifiedSimpleMovingAverage

Page 219: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 220: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Thefrequencyresponsesofthree-,five-,seven-,andnine-element modified SMAs areshowninFigure3.6.

Figure3.6ModifiedSimpleMovingAverageFrequencyResponses

Page 221: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 222: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ ModifiedLeast-SquaresQuadraticsInstead of transfer response'shavingaleast-squaresbestfit,aswiththeSMA,wecanalsoarrange to obtain a least-squaresbestfittoaquadraticequation.Thismeanswe canaccommodate some bowing

Page 223: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

in the data while getting ourleast-squares best fit. Then,wecanhalvethefirstandlastcoefficients to realize thedouble zero in the transferresponse at the Nyquistfrequency. Hamming1 givesthecoefficientsofsuchfiltersas:

Thefrequencyresponsesof

Page 224: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

these filters are shown inFigure 3.7. The frequencyresponses inFigure3.7 showthattheseareclearlysuperiorsmoothing filters for trading.Thesefiltersincurtwo,three,four, and five bars of lag,respectively.

Figure3.7ModifiedLeast-SquaresQuadraticsFilterFrequencyResponses

Page 225: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 226: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■SuperSmootherOne of the advantages ofrecursive filters is that thetransition between the passbandandthestopbandcanbemuch sharper compared tothat of the nonrecursivefilters. As a matter ofcomputational simplicity, thecriticalperiodofthefiltercan

Page 227: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

be established independentlyfrom the degree of the filter.On the downside, recursivefilters don't have the samedelay at all frequencies. Thisvariable delay across thespectrum leads to dispersiondistortion of the outputwaveform. Most of thedispersion occurs at thosefrequency components thathave been attenuated, so theeffect of the distortion is arelativelyminorone.

Page 228: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

A Butterworth filter is afavorite analog filter becauseits frequency response ismaximally flat, near zerofrequency. Years ago, ItranslatedanalogButterworthfilters to their digitalapproximations having likedegrees in thenumeratoranddenominator of the transferresponse. The transferresponseischaracterizedbyasingle variable: the criticalperiod. The critical period is

Page 229: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

that where the output isattenuatedby3dBrelativetotheinputdata.The digital Butterworth

filter approximationsincluded numerators whosecoefficientswere [121] and[1 3 3 1] for two- and three-pole configurations,respectively. However, forapplications to trading, Inoted that the primarycontributionof thenumerator

Page 230: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

terms was to increase thefilter lag. So I createdmodified versions simply bydeleting all but the constantterm in the numerator of theButterworth transferresponse.Theequations for the two-

pole modified Butterworthfilterare:

(3-1)

Page 231: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The equations for thethree-pole modifiedButterworthfilterare:

(3-2)

Page 232: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The frequency responsesfor two- and three-polemodified Butterworth filters

Page 233: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

whose critical periodwas setata10-barcycleareshowninFigure 3.8. The three-poleversion gives about 6 dBmore attenuation at theNyquist frequency than thetwo-poleversion.Thatmeanstheoutputwaveamplitudeofthe three-pole version wouldbehalfthewaveamplitudeatthe Nyquist frequency. Insome applications, thisdifference in filteredamplitudecouldbeimportant.

Page 234: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure3.8FrequencyResponseofTwo-andThree-PoleModifiedButterworthFiltersWherePeriod=10

Page 235: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 236: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The delay of the two- andthree-pole modifiedButterworth filters whosecriticalperiodwassetata10-bar cycle is shown in Figure3.9. The price to be paid forthe additional rejection bandattenuation is an increase ofalmost twobarsofadditionaldelaynear thecriticalperiod.In addition, there is greaterpercentage dispersiondistortion across the pass

Page 237: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

band.

Figure3.9LagsofTwo-andThree-PoleModifiedButterworthFiltersWherePeriod=10

Page 238: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 239: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Having obtained goodfilteringwithminimumdelayand minimum delaydistortion,itisrelativelyeasytoobtainazerointhetransferresponse at the Nyquistfrequency by adding a two-element moving average inthenumerator.Thedelaycostis only half a bar, and thatcostseemsworthit.Bydoingthis, a filter I call theSuperSmoother is created.

Page 240: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The equations for theSuperSmootherfilterare:

(3-3)

The frequency response ofthe SuperSmoother filter

Page 241: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

wherethecriticalperiodissetto10isshowninFigure3.10.

Figure3.10FrequencyResponseofaSuperSmootherFilterWherePeriod=10

Page 242: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 243: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■SuperSmootherFilterApplicationsA SuperSmoother filter isused anytime a movingaverage of any type wouldotherwise be used, with theresultthattheSuperSmoother

Page 244: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

filter output would havesubstantially less lag for anequivalent amount ofsmoothing produced by themoving average. Forexample,afive-barSMAhasa cutoff period ofapproximately 10 bars andhas two bars of lag. ASuperSmoother filter with acutoffperiodof10barshasalag a half bar larger than thetwo-pole modifiedButterworth filter shown in

Page 245: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure3.9.Therefore, such aSuperSmoother filter has amaximum lag ofapproximately 1.5 bars andeven less lag into theattenuationbandof the filter.The differential in lagbetweenmoving average andSuperSmoother filter outputsbecomes even larger whenthecutoffperiodsarelarger.Market data contain noise,

and removal of noise is the

Page 246: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

reason for using smoothingfilters. In fact, market datacontain several kinds ofnoise. I'll group one kind ofnoise as systemic, caused bythe random events of tradesbeing exercised. A secondkind of noise is aliasingnoise, caused by the use ofsampled data. Aliasing noiseis the dominant term in thedataforshortercycleperiods.Itiseasytothinkofmarket

Page 247: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

data as being a continuouswaveform,butitisnot.Usingthe closing price asrepresentative for that barconstitutes one sample point.It doesn't matter if you areusing an average of the highand low instead of the close,you are still getting onesample per bar. Sincesampled data is being used,there are some DSP aspectsthat must be considered. Forexample,theshortestanalysis

Page 248: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

period that is possible(without aliasing)2 is a two-bar cycle. This is called theNyquistfrequency,0.5cyclespersample.Aperfecttwo-barsine wave cycle sampled atthe peaks becomes a squarewave due to sampling.However, sampling at thecycle peaks cannot beguaranteed, and theinterference between thesampling frequency and the

Page 249: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

data frequency creates thealiasing noise. The noise isreduced as the data period islonger. For example, a four-barcyclemeanstherearefoursamples per cycle. Becausethere are more samples, thesampled data are a betterreplica of the sine wavecomponent. The replica isbetter yet for an eight-bardata component. Theimproved fidelity of thesampled data means the

Page 250: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

aliasing noise is reduced atlonger and longer cycleperiods.Therateofreductionis 6 dB per octave. Myexperience is that thesystemicnoise rarely ismorethan10dBbelowthelevelofcyclicinformation,sothatwecreate two conditions foreffective smoothing ofaliasingnoise:

1. It is difficult to usecycleperiodsshorterthat

Page 251: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

two octaves below theNyquist frequency. Thatis, an eight-bar cyclecomponent has aquantization noise level12 dB below the noiselevel at the Nyquistfrequency. Longer cyclecomponents thereforehave a systemic noiselevel that exceeds thealiasingnoiselevel.2. A smoothing filter

Page 252: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

should have sufficientselectivity to reducealiasing noise below thesystemic noise level.Since aliasing noiseincreasesattherateof6dB per octave above aselected filter cutofffrequency and since theSuperSmootherattenuationrateis12dBper octave, theSuperSmoother filter isan effective tool to

Page 253: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

virtually eliminatealiasing noise in theoutputsignal.

I urge readers to universallyadapt the SuperSmootherfilterset toacutoffperiodof10 bars or so on all data toattenuate aliasing noise. Theoutput of the SuperSmootherfilter can be used directly asanindicatororasthesampleddata fed to any otherindicator.

Page 254: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Key PointstoRemember

1. The lag of allnonrecursive filtershaving coefficientssymmetrical about thecenter point of the filteris half the degree of thetransfer responsepolynomial. In otherwords, for a

Page 255: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

nonrecursive filterhaving N elements, thelag of that filter will be(N−1)/2.2. Nonrecursive filterswith coefficientssymmetrical about thecenter point of the filterand having an evennumberof elementswillalwayshaveazerointhetransfer response at theNyquistfrequency.

Page 256: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

3. An SMA having anodd number of elementsandwhose first and lastelements havecoefficients cut in halfareguaranteedofhavinga double zero in thetransfer response at theNyquistfrequency.4.Whereas SMAs are aleast-squaresbestfittoastraight line,nonrecursive filters can

Page 257: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

also have coefficientsthat are a least-squaresbest fit to a quartic.Halving their endcoefficients alsoguaranteesadoublezerointheirtransferresponseat the Nyquistfrequency.5. Probably the bestfilterformostsmoothingapplications is a two-poleSuperSmoother.

Page 258: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

6. A SuperSmootherfilter is recommendedfor universal use toremovealiasingnoise.

Page 259: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Notes1. R. W. Hamming,Digital Filters, 3rd ed.(Upper Saddle River,NJ:PrenticeHall,1997),49.

2. Aliasing is the falsesignals that result fromundersampling. Forexample, wagon wheelsoften appeared to turnbackwards in the early

Page 260: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

cowboy motion picturesbecauseof the relativelyslowmovieframerate.

Page 261: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CHAPTER4

Decyclers“Thewiggles have beencanceled,” said Tomflatly.

Page 262: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

If technical analysistechniques include adetrender,thencertainlythereis room for its corollary, adecycler.Adecyclerremovesthe cycle components andretains only the trendcomponents.

Page 263: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ DecyclerConstructionThe concept of a decycler isreally pretty simple. Thecyclic components areremoved by the process ofcancellation. Figure 4.1showstheamplituderesponseofahigh-passfilter.Notethatthe amplitude of the filteroutput is almost the same as

Page 264: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

thefilterinputamplitude(i.e.,0 dB).Thus, if the high-passfilter output is subtractedfrom the input data, theresidual only contains thelow-frequencycomponents.

Figure4.1FrequencyResponseofaHigh-PassFilterHavinga30-BarCutoffPeriod

Page 265: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 266: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The transfer response of adecycler is written as thedifference between input andtheoutputofahigh-passfilteras

Byputtingtheright-handsideof this equation over acommon denominator, weobtain

Page 267: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

This transfer responseequation shows the decyclertobeaone-polefilterbecausethe denominator containsonlyafirst-orderpolynomial.Byexamination, thedecyclermustcloselyfollowthe inputdata because there is nodifference term in thenumerator of the transferresponse. The EasyLanguage

Page 268: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

codetocomputethedecycleris written almost directlyfrom the transfer responseequationinCodeListing4-1.

CodeListing4-1.EasyLanguage

CodetoComputeaDecycler

{Decycler©2013JohnF.Ehlers}Inputs:Cutoff(60);

Page 269: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Vars:alpha1(0),HP(0),Decycle(0);

//Highpassfiltercycliccomponentswhoseperiodsareshorterthan“cutoff”barsalpha1=(Cosine(360/Cutoff)+Sine(360/Cutoff)-1)/Cosine(360/Cutoff);Decycle = (alpha1 / 2)*(Close+Close[1])+(1-alpha1)*Decycle[1];Plot1(Decycle);

Page 270: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ DecyclerApplicationThe decycler removes theshorter cycle energy bycancellation, leaving thedecycler output to bebasicallyaone-pole low-passfilter.Adecyclerhavinga30-barcutoffperiodisusedasanexample. The amplituderesponse is shown in Figure

Page 271: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

4.2, and the lag is shown inFigure 4.3. The amplituderesponse confirms the 6-dB-per-octaveattenuationroll-offrateofasingle-polefilter.Forexample, the response at afrequency of 0.1 bars percycle is approximately −10dB, and the response oneoctave higher at a frequencyof 0.2 bars per cycle isapproximately−16dB.

Figure4.2Amplitude

Page 272: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ResponseofaDecyclerHavinga30-BarCutoffPeriod

Page 273: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 274: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure4.3LagofaDecyclerHavinga30-BarCutoffPeriod

Page 275: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 276: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The really importantcharacteristic of the decycleris its exceptionally low lag.The very longest cyclecomponents are delayed lessthan five bars, and at afrequency of 0.05 cycles perbar (a 20-bar cycle period),the lag ison theorderof1.5bars. Higher-frequencycomponentsaredelayedevenless. The end result is thehigher-frequencywigglesthat

Page 277: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

make it through the filterattenuation are roughlycoincidentwiththewigglesinthe price itself. This featuremakes the decycler an ideal“instantaneous trend line”that accurately portrays thetrendofthedata.A similar smoothed filter

outputcanbeproducedusinga SuperSmoother filter.However,whentheresultsofthe decycler are compared to

Page 278: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

those of the SuperSmoother,thedecyclerwillalwayshavelesslag.However,adecycleris only a one-pole filter andthereforehasinferiorfilteringcapabilities. Therefore, adecycler should not be usedas a smoothing filter toremove aliasing noise.Rather, its role should berelegated to producing aninstantaneous trend linewhere the selected cutoffperiodisrelativelylarge.The

Page 279: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

large cutoff period enablesthe decycler to attenuate thealiasing noise because it ismany octaves away from theNyquistfrequency.It is certainly possible to

create a decycler bysubtracting a two-pole high-pass filter output from theinput data. In fact, such adecyclerhassome interestingproperties because the longcycle components have

Page 280: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

substantial lag, while theshort cycle componentscontinuetohaveminimallag.However, interpretation oftheindicatorismoredifficultbecause the larger spread inlag across the spectrum.Therefore, only the single-pole decycler isrecommended for use asinstantaneoustrendlines.

Page 281: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ DecyclerOscillatorA decycler oscillator iscreated by subtracting theoutput of a high-pass filterhavingashortercutoffperiodfrom the output of anotherhigh-pass filter having alonger cutoff period. Thisway, both elements have azero in their transfer

Page 282: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

responses at zero frequency.Thus, the very, very longcycle components (and thestatic term) are removed.There is a finite differencebetweentheoutputofthetwofilters in the frequency rangebetween their cutoff periods,but shorter cycle componentsare still removed bycancellation. As a result, thetrend line is displayed as anoscillator.TheEasyLanguagecodetocomputethedecycler

Page 283: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

oscillator is shown in CodeListing4-2.

CodeListing4-2.EasyLanguage

CodeforDecyclerOscillator

{DecyclerOscillator©2013JohnF.Ehlers}

Inputs:HPPeriod1(30),HPPeriod2(60);

Vars:alpha1(0),

Page 284: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

alpha2(0),HP1(0),HP2(0),Decycle(0);

alpha1=(Cosine(.707*360/HPPeriod1)+Sine(.707*360/HPPeriod1)-1)/Cosine(.707*360/HPPeriod1);

alpha2=(Cosine(.707*360/HPPeriod2)+Sine(.707*360/HPPeriod2)-1)/Cosine(.707*360/HPPeriod2);

HP1 = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP1[1]-(1-alpha1)*(1-alpha1)*HP1[2];

HP2 = (1 - alpha2 / 2)*(1 - alpha2 / 2)*(Close-2*Close[1]+Close[2]) + 2*(1-alpha2)*HP2[1]-(1-alpha2)*(1-alpha2)*HP2[2];Decycle=HP2-HP1;

Plot1(Decycle);

Plot2(0);

Thedecycleroscillatorcan

Page 285: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

beuseful fordetermining thetransition between uptrendsand downtrends by thecrossing of the zero line.Alternatively, the changes ofslope of the decycleroscillator are easier toidentify than the changes inslopeoftheoriginaldecycler.Optimum cutoff periods caneasily be found byexperimentation.The decycler and decycler

Page 286: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

oscillatorexamplesareshownin Figure 4.4, where thecutoffperiodis30bars.Inthecase of the decycleroscillator, the longer cutoffperiodissettobe60bars.

Figure4.4BothDecyclersShowtheInstantaneousTrendwithMinimumLag

Page 287: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 288: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Key PointstoRemember

1. A decycler filterfunctions the same as alow-passfilter.2. A decycler filter iscreated by subtractingtheoutputofahigh-passfilter from the input,thereby removing thehigh-frequency

Page 289: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

components bycancellation.3. A decycler filter hasverylowlag.4. A decycler oscillatoris createdby subtractingtheoutputofahigh-passfilter having a shortercutoff period from theoutput of another high-pass filter having alongercutoffperiod.5. A decycler oscillator

Page 290: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

shows transitionsbetween uptrends anddowntrends at the zerocrossings.

Page 291: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CHAPTER5

Band-PassFilters

“A little of the datanarrowly passed,” said

Page 292: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Tombroadly.

Perhapstheleastappreciatedand most underutilized filterin technical analysis is theband-pass filter. The band-pass filter simultaneouslydiminishes the amplitude atlowfrequencies,qualifying itasadetrender,anddiminishesthe amplitude at highfrequencies,qualifyingitasadata smoother. It passes onlythose frequency components

Page 293: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

frominputtooutputinwhichthe trader is interested. Thefilteringproducedbyaband-passfilterissuperiorbecausetherejectioninthestopbandsis related to its bandwidth.The degree of rejection ofundesired frequencycomponents is calledselectivity.The band-stop filter is the

dualoftheband-passfilter.Itrejects a band of frequency

Page 294: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

componentsasanotchat theoutput and passes all otherfrequency componentsvirtually unattenuated. Sincethe bandwidth of the deeprejection in the notch isrelatively narrow and sincethespectrumofmarketcyclesis relatively broad due tosystemicnoise, theband-stopfilter has little application intrading.

Page 295: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Band-PassFilterA band-pass filter can begenerated by cascading alow-pass filter and a high-pass filter. However, thisapproach results in reallypoor filtering unless a largenumber of data samples areusedtoincreasethedegreeofthe polynomials. However,

Page 296: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

digital signal processing(DSP) enables us tomap theentire0 to0.5cyclesperbarrange of a simple high-passfilter into the lower half-bandwidth of the pass bandandtoalsomaptheentire0to0.5cyclesperbarrangeofanexponential moving average(EMA) low-pass filter intothe upper half-bandwidth ofthe pass band. When we dothis,thetransferresponseofasimple pass-band filter is

Page 297: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

described by Equation 5-1.Theband-pass filterwasalsodescribedinTable1.1.

(5-1)Whereγ=Cos(360*/Period)

and δ = bandwith as afractionofPeriodλ=Cos(360/Period)

Since the degree of the

Page 298: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

polynomial in thedenominator of the transferresponseistwo,thisisatwo-pole band-pass filter. Inprogramming language,where the delay ofN bars isdenoted by “[N]”, theequationforatwo-poleband-passfilterbecomes

(5-2)

The frequency response ofa two-pole band-pass filter

Page 299: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

centered at a 10-bar cycleperiod, and having a passbandthatis30percentofthecenter frequency at the halfpower points (−3 dB) isshown in Figure 5.1. Notethatthisfilterhaszerosinthetransferresponsebothatzerofrequency and at theNyquistfrequency. The relativelysharp roll-off in the rejectbands occurs because thecomputational frequencies ofthe filter havebeen scaled to

Page 300: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the half-bandwidth of thefilter.

Figure5.1FrequencyResponseofaTwo-PoleBand-PassFilterTunedtoa10-BarCyclePeriodandHaving30PercentBandwith

Page 301: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 302: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Another example of thefrequencyresponseofaband-pass filter isshowninFigure5.2,where the inputdata isachirped frequency sine wavewhose period is continuouslyswept from a 10-bar cycleperiod to a 60-bar cycleperiod. The theoreticalclosing prices swing +/− 5fromacentralvalueof60.Inthis case, theband-pass filteris tuned to a 20-bar cycle

Page 303: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

period. In Figure 5.2, it isclear that signals whoseperiodsarebothlessthanandgreater than a 20-bar cycleareattenuated.

Figure5.2FrequencyResponseofaBand-PassFilterTunedtoa20-BarCyclePeriod

Page 304: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Readers can easily make

Page 305: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

their own chirped frequencysine wave data source inExcel.Make the first columnbeacounterfrom1to1,000.Theequationforaphaserateof change per sample so thecycleperiodvariesfrom10to60 as a counter varies from100to1,000isapproximatelyPhase = 0.1 − 0.000075 *Counter.Therefore,incellB1type“=60+5*Sin(6.28318*(0.1−0.000075*a1))”andthen copy cell B1 into cells

Page 306: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

B2throughB1000.ColumnBcanbetheopeningprice.Youcanmakethedatalookalittlemore realistic by makingcolumn C the high price asone greater than price incolumnB,makingcolumnDasthelowpricebeonelowerthan the price in column B,and letting column E be theclosing price and have thesame value of the price incolumn B. For thoseplatformssensitivetodatesin

Page 307: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

price data, export a real datafilehavingaboutfiveyearsofdatainCSVformattocapturethe dates. Then, copycolumnsB,C,D, andE intotheclipboardandthenEdit... Paste Special . . . Valuesinto the Open, High, Low,and Close columns,overwriting the values inthose columns with thechirped sine wave values.Finally, save the data file soyou can import it into your

Page 308: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

tradingplatform.One of the amazing

characteristicsof aband-passfilter is that if the centerperiodofthefilteristunedtoa static sine wave whoseperiod is the same as thecenter period of the filter,thenthereisabsolutelynolagin the output. Figure 5.3shows the output of a 20-barband-pass filter having a 30percent bandwidth compared

Page 309: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

to the 20-bar input data.However, if the band-passfilter is tuned to its previoushalf-power period of 17 barsper cycle, the 20-bar datacycleislongerthanthetunedfrequency of the filter. As aresult,theoutputresponsehasa 65-degree lag, as shown inFigure 5.4. However, if theband-passfilteristunedtoitsother previous half-powerperiod of 23 bars per cycle,the 20-bar data cycle is

Page 310: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

shorter than the tunedfrequency of the filter. As aresult,theoutputresponsehasa65-degreelead,asshowninFigure 5.5. The phase shiftacross the bandwidth of theband-pass filter isunavoidable. The phase shiftis doubled each time thenumberofpolesisdoubledinthe transfer response.Therefore, it is important touse the simplest filterpossible in trading to

Page 311: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

minimize phase shiftdistortion.

Figure5.3ABand-PassFilterPreciselyTunedHasNoLag

Page 312: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure5.465-DegreeLag

Page 313: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ResultsfromtheBand-PassFilter'sBeingTuned15PercentTooLong

Page 314: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 315: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure5.565-DegreeLeadResultsfromtheBand-PassFilter'sBeingTuned15PercentTooShort

Page 316: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 317: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Band-PassFilterQThequality factor,orQ,ofaband-pass filter is one of itsimportant characteristics.There are several interrelateddefinitions ofQ. Perhaps thesimplest is based onselectivity of the filter as theratioofitscenterfrequencytoits percentage bandwidth at

Page 318: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the half-power points. In ourexample of a 30 percentbandwidthfilter,theQwouldbe 3.33. Stated another way,Q=20/(23−17)=20/6=3.33.However, Q can also be

defined in terms of energyquantities. From therelationships in resonantelectronic circuits thedefinitionbecomes

(5-3)

Page 319: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

For example, a band-passfilter having a Q = 3.33wouldhavetheenergystoredin the filter but only abouthalftheenergydissipatedpercycle. Such a filter wouldhave its ringing quicklyquenched.Suchafilterwouldalsoquicklyadapttonewanddifferentcyclecomponentsatits input. However, a high-Qfilter would ring out a longtime in response to animpulse input. A bell is an

Page 320: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

example of such a high-Qfilter. High-Q filters havehigh selectivity in thefrequency domain, but theirringing obscures the cyclicinformation in thedata input.Therefore,theQofband-passfilters used in trading shouldbeaslowaspossibleandstillobtainthedesiredfiltering.Figure5.6 shows the input

dataas threecompletecyclesof a sine wave having a 20-

Page 321: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

bar cycle period. Thesubgraph shows the outputresponseofaband-passfiltertuned to a 20-bar period andhavingaQ=3.33.Theoutputswingexceedsthehalf-poweramplitude within one fullcycleperiodafterthedataareapplied to the input. Further,the output swing is dampedbelow the half-poweramplitudewithinahalfcycleafter the data input isremoved. However, a

Page 322: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

relativelyhighQfilterwillbeslow to rise in response tonewdataandwillcontinuetoringafterthedataisremoved,asshowninFigure5.7.Band-pass filters can be

more responsive in the timedomain by having a lowerQ(wider percentagebandwidth). For example,Figure5.8showstheresponseofaband-passfilterhavingaQ = 2. This filter quickly

Page 323: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

respondstonewdataandjustasquicklyhas theoutput falloff after the input data areremoved.

Figure5.6TransientResponseofaBand-PassFilterHavingaQ=3.33

Page 324: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure5.7Transient

Page 325: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ResponseofaBand-PassFilterHavingaQ=10

Page 326: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure5.8TransientResponseofaBand-PassFilterHavingaQ=2

Page 327: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Using a band-pass filter

Page 328: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

havinga30percentpassbandis a relatively goodcompromise betweenselectivity and transientresponsiveness for mosttradingapplications.

Page 329: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ AutomaticGain Control(AGC)A band-pass filter describedbyEquations5-1and5-2willaccurately display theamplitude of the cyclicswings in the input data.Consequently, the amplitudeof these swings will vary

Page 330: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

among stock ticker signalsbecausethepricesrangefrompenny stocks to well over$100 per share. A pennystock just cannot have aslarge a swing as a blue-chipstock because the basis ismuch smaller. Traders areused to indicators beingnormalized to a range like 0to 100 so that the indicatorscales the same regardless ofthe price amplitude swings.ThepurposeoftheAGCisto

Page 331: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

provideaconsistent indicatorappearance independentlyfrom the range of the priceswings. The process of theAGCdividesthecurrentpriceby the absolute value of therecent maximum swing sothatthenormalizedwaveformhas a maximum of 1 or aminimumof−1.Ihaveneverseen the AGC conceptapplied to technicalindicators, which is a shamebecause it can be applied

Page 332: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

universally.The specific kind of AGC

is called a fast attack−slowdecayAGC.Thenormalizingfactor is allowed to decay asmall amount before beingcompared to the next sampleof the signal so thenormalizing is not done onthe largest swing throughouthistory. If thenext sampleofthe signal is larger than thenormalizing factor, then the

Page 333: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

normalizing factor isimmediately assigned thevalue of the next sample.However, if the next sampleof the signal is smaller thanthe normalizing factor, thenthe normalizing factor isallowed to decay anothersmall amount and then iscomparedtothethirdsample,and so on. The amount ofdecay is exponential if thenormalizing factor is notreset.IfthedecayfactorisK

Page 334: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

for thefirstsample, thenit isK * K = K2 for the nextsample, and isK *K *K =K3 for the third sample, andsoon.Figure5.9depictstheAGC

action, where the absolutevalueof thesinewavesignalis shown by the solid line.The normalizing factor,shown by the dashed line,decays exponentially witheachsample.Whenthesignal

Page 335: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

exceeds the normalizingfactor, thenormalizing factoris assigned the new value ofthe signal so that when theinputsignal isdividedby thenormalizing factor the AGCalgorithm output normalizedthe input value to be 1. Theprocess is repeated for eachnewsampleofdata.

Figure5.9TheAGCNormalizingFactorDecaysExponentiallyandIsRapidly

Page 336: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ResettotheAbsoluteValueoftheCyclicSwing

Page 337: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Whenchangesaremadein

Page 338: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the time domain, there arealways implications made inthe frequency domain.Considering theoretical sinewave signals, the effectivegainoftheAGCisthedecayfactor to the exponent of thehalf period of the sine waveas

About the shortest cycleperiod useful for trading is a10-bar cycle, and cycle

Page 339: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

periods longer than 48 barscan often be consideredtrends. Therefore, we areconcernedwiththegainslopeover the range froma10-barperiodtoa48-barperiod.Thegainratioover thisrangecanbeexpressedas

Sincewemustacceptsomegain slope across the cycleperiods of interest, an

Page 340: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

arbitrary but reasonableselection is 1.5 dB. Thenumericalvalueoftheratioiscomputedas:

Knowing the desired gainratioacross theband,wecancomputethedecayfactoras:

Iwillusethisvalueforthe

Page 341: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

AGCdecayfactorthroughoutthe remainder of the bookunless the AGC is used foramplitude compensation as afunctionofthecycleperiod.

Page 342: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ SpectralDilationRemovalThe effect of SpectralDilation will be fullydescribed in Chapter 7. In anutshell, theamplitudeof themarket data spectrum is notflat, and traders must besensitive to that fact when

Page 343: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

employingfilters.The band-pass filter

attenuationincreases6dBperoctaveof thehalfbandwidth,starting at the upper andlowercutofffrequencies.Thisrelatively low rate ofattenuation is insufficient toremovetheeffectsofSpectralDilation on the long cycleperiod side of the filter.Therefore, a high-pass filtershouldbeconnectedinseries

Page 344: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

with the band-pass filter toensure that the SpectralDilation distortions are notallowedtoreachtheoutput.The critical frequency of

thehigh-passfilterissettobeone octave below the loweredgeoftheband-passfiltertominimize the interaction ofthetwofilterswithinthepassband.Sincetheloweredgeoftheband-passfilterisat0.5*Bandwidth relative to the

Page 345: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

center frequencyof thefilter,the critical frequency of thehigh-pass filter is set to be0.25 * Bandwidth relative tothe center frequency of theband-pass filter. That makesthe high-pass criticalfrequencyafulloctaveofthehalf-bandwidth below thecenterfrequency.

Page 346: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Band-PassFilterThe EasyLanguage code toimplement the band-passfilterisgiveninCodeListing5-1.Afterdeclaringvariables,the band-pass filtercalculation is preceded by ahigh-pass filter whose cutofffrequency is one half-bandwidth octave below the

Page 347: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

lower-frequency criticalfrequency of the band-passfilter to avoid interferencewith the action of the band-pass filter while stillremoving the effects ofSpectralDilation.

CodeListing5-1.EasyLanguage

CodefortheBand-PassIndicator

Page 348: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

{BandPassFilter©2013JohnF.Ehlers}

Inputs:Period(20),Bandwidth(.3);

Vars:alpha2(0),HP(0),gamma1(0),alpha1(0),beta1(0),BP(0),Peak(0),Signal(0),Trigger(0);

alpha2=(Cosine(.25*Bandwidth*360/Period)+Sine(.25*Bandwidth*360/Period)-1)/Cosine(.25*Bandwidth*360/Period);HP = (1 + alpha2 / 2)*(Close-Close[1])+(1-alpha2)*HP[1];

beta1=Cosine(360/Period);

gamma1=1/Cosine(360*Bandwidth/Period);

alpha1=gamma1-SquareRoot(gamma1*gamma1-1);BP = .5*(1 - alpha1)*(HP - HP[2]) + beta1*(1+alpha1)*BP[1]-alpha1*BP[2];

Page 349: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

IfCurrentbar=1orCurrentBar=2ThenBP=0;

Peak=.991*Peak[1];

IfAbsValue(BP)>PeakThenPeak=AbsValue(BP);IfPeak<>0ThenSignal=BP/Peak;

Plot1(Signal);Plot2(0);alpha2=(Cosine(1.5*Bandwidth*360/Period)+Sine(1.5*Bandwidth*360/Period)-1)/Cosine(1.5*Bandwidth*360/Period);Trigger = (1 + alpha2 / 2)*(Signal-Signal[1])+(1-alpha2)*Trigger[1];

Plot6(Trigger);

An example of theindicatorplottedoverroughlyayearondailydataofDollarGeneral (symbol DG) isshown in Figure 5.10. Notethe band-pass filter correctly

Page 350: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

identifies the peaks andvalleys in thedata.However,the band-pass filter is deadwrong when the prices gointoatrendasinMarch2012andJuneandJuly2012.Asadiscretionary indicator, onecansaytheband-passfilterisworking well when the filteroutput lookssimilar toasinewave. However, watch outwhen the filter outputcontainserraticsignals.

Page 351: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure5.10Band-PassIndicatorforDGPinpointsPeaksandValleys

Page 352: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

An interesting addition to

Page 353: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the band-pass filter is thesecond high-pass filterserially connected to theoutputoftheband-passfilter.In this case, the high-passfilter is tuned to the high-frequency side criticalfrequency of the band-passfilter. Doing this creates aleadingwaveformresemblingthe band-pass filter output,but still has a phase leadcharacteristic. If a leadingwaveform is attempted by

Page 354: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

taking the rate change of theband-pass filter output, theresultingwaveformwouldbetoo erratic to be of use as atrading indicator. As seen inFigure 5.11, the leadingtrigger crosses the band-passfilteroutputattheexactpeaksand valleys of the waveformexcept when the data aretrending.

Figure5.11TheLeadingTriggerWaveformClearly

Page 355: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

FlagsPeaksandValleysoftheBand-PassIndicatorinRealTime

Page 356: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 357: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Measuringthe CyclePeriodFigure 5.10 shows the cyclecontent of the data swingingpretty much as a variableamplitude sine wave withvariable periodicity. Theband-pass filter can be usedas a relatively simple

Page 358: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

measurementofthedominantcycle. A cycle is completewhen the waveform crosseszero two times from the lastzerocrossing.Therefore,eachsuccessive zero crossing ofthe indicator marks a halfcycle period. We canestablish the dominant cycleperiod as twice the spacingbetween successive zerocrossings.When we measure the

Page 359: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

dominant cycle period thisway, it is best to widen thepass band of the band-passfilter to avoid distorting themeasurement simply due tothe selectivity of the filter.Using an input bandwidth of0.7 produces an octave-widepassband.Forexample,ifthecenter period of the filter is20andtherelativebandwidthis 0.7, the bandwidth is 14.Thatmeans the pass band ofthefilterextendsfrom13-bar

Page 360: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

periods to 27-bar periods.That is, roughly an octaveexists because the longestperiod is twice the shortestperiod of the pass band. It isimperative that a high-passfilter is tuned one octavebelow the half-bandwidthedgeoftheband-passfiltertoensure a nominal zero meanofthefilteredoutput.Withouta zero mean, the zerocrossings can have asubstantialerror.Thecode to

Page 361: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

measure the dominant cycleusing the band-pass filter isgiven in Code Listing 5-2.Since the measurement canvary dramatically from zerocrossing tozerocrossing, thecode limits the changebetween measurements to benomore than 25 percent.Anexample of the dominantcycle period measurement isshowninFigure5.12.

Figure5.12Band-PassFilter

Page 362: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

MeasurementoftheDominantCyclePeriod

Page 363: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

While measuring the

Page 364: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

changing dominant cycleperiod via zero crossings ofthe band-pass waveform iseasy, it is not necessarily themost accurate method. Moreaccurate techniquesexamining the entire spectralcontent of the data arepresented in later chapters ofthisbook.

CodeListing5-2.DominantCycle

Page 365: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

MeasuredbyZeroCrossingsoftheBand-PassFilter

{ZeroCrossingsPeriodMeasurer©2013JohnF.Ehlers}

Inputs:Period(20),Bandwidth(.70);

Vars:alpha2(0),HP(0),gamma1(0),alpha1(0),beta1(0),BP(0),Peak(0),Real(0),counter(0),DC(0);

Page 366: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

alpha2=(Cosine(.25*Bandwidth*360/Period)+Sine(.25*Bandwidth*360/Period)-1)/Cosine(.25*Bandwidth*360/Period);HP = (1 + alpha2 / 2)*(Close-Close[1])+(1-alpha2)*HP[1];

beta1=Cosine(360/Period);

gamma1=1/Cosine(360*Bandwidth/Period);

alpha1=gamma1-SquareRoot(gamma1*gamma1-1);BP = .5*(1 - alpha1)*(HP - HP[2]) + beta1*(1+alpha1)*BP[1]-alpha1*BP[2];IfCurrentbar=1orCurrentBar=2ThenBP=0;

Peak=.991*Peak;

IfAbsValue(BP)>PeakThenPeak=AbsValue(BP);IfPeak<>0ThenReal=BP/Peak;

DC=DC[1];

IfDC<6ThenDC=6;

counter=counter+1;

IfRealCrossesOver0orRealCrossesUnder0ThenBeginDC=2*counter;If2*counter>1.25*DC[1]ThenDC=1.25*DC[1];If2*counter<.8*DC[1]ThenDC=.8*DC[1];counter=0;End;

Plot1(DC);

Page 367: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Key PointstoRemember

1. A band-pass filter isboth a detrender and asmoother combined intoonefilter.2.Attenuationofout-of-band frequencycomponents is superiorto that of high-passfilters and low-pass

Page 368: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

filters because therejection isscaled to thebandwidthofthefilter.3. A band-pass filtertuned precisely to aconsistent dominantcyclehasnolag.4. A band-pass filtertunedtoaperiodshorterthan the dominant cycleproduces an output thatleads the swing in theinputdata.

Page 369: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

5. A band-pass filtertuned to a period longerthan the dominant cycleproduces an output thatlags the swing in theinputdata.6.Theselectivityandthetransient response of aband-pass filter areinterrelated. A narrowpass-bandfilterisslowertoreacttochangesintheinputdata.Awiderpass-

Page 370: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

band filter adapts morequicklytochangesintheinputdata.7. A serially connectedsingle-pole high-passfilter tuned one octavebelowthelow-frequencycritical frequency of theband-pass filter isnecessary to eliminatethe effects of SpectralDilationandtocreateanoutput having a

Page 371: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

nominallyzeromean.8. A leading functioncan be created byserially connecting asingle-pole high-passfilter tuned to the high-frequency critical periodoftheband-passfilter.9. The dominant cycleperiodofthedatacanbeestimated by countingthe number of barsbetween zero crossings

Page 372: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

of the band-pass filteroutput.

Page 373: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CHAPTER6

MarketStructureandtheHurst

Page 374: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Coefficient“The market has adefinite structure,” saidTomrandomly.

It is well understood thatwhitenoisehasnocorrelationin time, and random walk(Brownianmotion) noise hasno correlation betweenincrements. Brownian walkscan be generated from a

Page 375: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

function where the spectraldensity isproportional to1/Fα,whereFisfrequency,αisapower law, and α = 1generally signifies “longmemory,” as I will describeinChapter8.Thus,1/Fnoiseis synonymous with long-rangedependence.Integrationof noise increases theexponentαby2,whereastheinverse operation ofdifferentiationdecreasesitby2. Therefore, 1/F α noise

Page 376: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

cannot be obtained by thesimple procedure ofintegration or ofdifferentiation of suchconvenient signals. Thewidespread occurrence ofsignals exhibiting suchbehavior suggests that ageneric mathematicalexplanation might exist. Theubiquityof1/Fαnoiseisoneof the oldest puzzles ofcontemporary physics andscienceingeneral.

Page 377: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure 6.1 displays sometime series and, in the samecolors,theirassociatedpowerspectra.Suchtimeseriesarisein many natural systems.Power spectra are plotted inlog-log coordinates, as iscustomary,because

Figure6.1TimeSeriesandSpectralDensitiesforSeveralKindsofNoise

Page 378: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 379: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

In other words, thelogarithmictransformrendersthe 1/F α power spectrum astraightlinewhoseslope,−α,can be easily estimated.Clearly, for such naturalsystems, observed byhumans, neither arbitrarilysmall nor arbitrarily largefrequencies can be recorded.These models are simply

Page 380: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

relevant to physicallyplausiblesituations.Noise in economic data is

usually studied as long-rangedependence or longmemory.Ithasbeen shown repeatedlythat the autocorrelationfunctions of economic timeseries,suchasseriesofstockprices over days, weeks, ormonths, or thegross nationalproduct of various countriesover years, do not decay

Page 381: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

exponentially as they wouldif the process generating theseries were a simpleautoregressive process.Instead, the autocorrelationfunctions of many economictime series reach a nonzeroasymptote and remain therefor the entire series, albeitoften at a low value,indicating that economicevents some distance in thepast continue to have aninfluence on current prices.

Page 382: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

You only need to do anInternet search on “stockmarket spectral density” tofind a number of academicpapers, both measured andtheoretical, regarding thefrequency content of themarket.The Hurst coefficient is

one way to attempt to get ahandle on the slope of thepowerdensityofmarketdata.The Hurst coefficient varies

Page 383: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

between 0 and 1, and isrelated to the α powercoefficient as H = 1 − α/2.TheHurstcoefficientismoreestimated than computed. Ifind the estimate using thefractal dimension is themostpractical for shorter-termmarket data. The Hurstcoefficient is related to thefractaldimensionasH= 2 −D. I would like to make itperfectly clear that the Hurstcoefficient or the fractal

Page 384: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

dimension has no directpractical application totradingnotonlybecause it isan estimate, but alsobecauseit has no predictive value.These computations onlyreflectthegeneralstructureofthe market, and the answeryouget isdependentonyourassumptions. For example,theHurst coefficient changesdramatically with the lengthof data used in making theestimate.

Page 385: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ FractalDimensionTo determine the fractaldimension of a generalizedpattern, we cover the patternwith a number “N” of smallobjects of several varioussizes“S.”Therelationshipofthenumberofobjects in twosetsofsizesis:

Page 386: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

As an example, we canstart with a pattern that is aline segment 10meters long.We chose the two smalldimensions as S1 = 1 meterand S2 = 0.1 meter. Placingboxes along the line we canfit ten 1-meter boxes on thesegment, therefore N1 = 10.

Page 387: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Similarly, we can fit onehundred 0.1-meter boxes onthe same 10-meter linesegment. Therefore, N2 =100.Thefractaldimensionofthelinethencomputesto:

As a second example, wewill use the pattern as asquare that is10metersonasideinsteadofalinesegment.Retaining the same sizes of

Page 388: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

our small boxes as 1 meterand 0.1 meter on a side,respectively,wegetN1=100and N2 = 10,000. When thesquare is our pattern, thefractal dimension thereforecomputestobe:

Aperfectsquarerepresentsan idealized geometry notfound in nature. Naturalfractals, such as that of a

Page 389: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

seashore, lack the trueregularity of an algorithmicstructure but are self-similarinastatisticalsense.Thus,inorder todetermine thefractaldimension of natural shapes,we must average themeasured fractal dimensionmadeoverdifferentscales.We could measure the

fractaldimensionofpricesbycovering the curve with aseriesof smallboxes.This is

Page 390: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

aburdensome task,but ifwetake into account that theprice samples are uniformlyspaced,we note that the boxcount is approximately theaverage slope of the curve.Therefore, we can estimatethe box count as the highestpriceduringanintervalminusthe lowest price during thatinterval,dividedbythelengthof the interval itself. Theequation for the number ofboxesisthen:

Page 391: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

We compute the fractaldimension by computing Nover two equal intervals toget the averaging over eachinterval.Interval1coverstheperiod from0 toT bars ago.Interval 2 covers the periodfrom T to 2T bars ago.Therefore, N1 = (HighestPrice − Lowest Price) overthe interval from 0 to T,

Page 392: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

dividedbyT.Similarly,N2=(Highest Price − LowestPrice) over the interval fromT to 2T, divided by T. WealsodefineanN3= (HighestPrice − Lowest Price) overthe entire interval from 0 to2T, divided by 2T. Sinceweare looking backwards intime, the slope computationofthefractaldimensionis:

Page 393: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The fractal dimensionvariesover the range fromD=1toD=2.SincetheHurstcoefficient is related to thefractaldimensionasH=2−D,sothatitvariesbetween0and 1. A value of 0.5indicates a true randomwalk(aBrowniantimeseries).Inarandom walk there is nocorrelation between anyelementandafutureelement.Acoefficientbetween0.5and1 indicates “persistent

Page 394: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

behavior,”thatis,along-termdependence. A Hurstcoefficientbetween0and0.5exists with time series with“antipersistentbehavior”—inother words, “acountertrender”(atermthatIdetest).

Page 395: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Computingthe HurstCoefficientThe EasyLanguage code tocomputetheHurstcoefficientis given inCodeListing 6-1.The only user input is thelengthofdatatobeused.Thenumber can be arbitrarilylarge if you have sufficient

Page 396: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

data.Theresultsarecriticallydependent on the input datalength selected. Afterdeclaring variables, thecoefficients of a 20-barSuperSmoother filter arecomputed. The computationsof N1, N2, and N3 are asdescribed in the previoussection. The fractaldimension is then convertedto the Hurst coefficient,which is subsequentlysmoothed in the

Page 397: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

SuperSmootherfilter.

CodeListing6-1.EasyLanguage

CodetoComputetheHurstCoefficient

{HurstCoefficient©2013JohnF.Ehlers}

Inputs:Length(30);{Lengthmustbeanevennumber}

Vars:a1(0),

Page 398: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

b1(0),c1(0),c2(0),c3(0),count(0),N1(0),N2(0),N3(0),HH(0),LL(0),Dimen(0),Hurst(0),SmoothHurst(0);

//SmoothwithaSuperSmootherFilterfromequation3

a1=expvalue(-1.414*3.14159/20);

b1=2*a1*Cosine(1.414*180/20);

c2=b1;

c3=-a1*a1;c1=1-c2-c3;

N3=(Highest(Close,Length)-Lowest(Close,Length))/Length;

HH=Close;

LL=Close;

Forcount=0toLength/2-1beginIfClose[count]>HHthenHH=Close[count];

Page 399: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

IfClose[count]<LLthenLL=Close[count];

End;

N1=(HH-LL)/(Length/2);

HH=Close[Length/2];

LL=Close[Length/2];

Forcount=Length/2toLength-1beginIfClose[count]>HHthenHH=Close[count];IfClose[count]<LLthenLL=Close[count];

End;

N2=(HH-LL)/(Length/2);

IfN1>0andN2>0andN3>0thenDimen=.5*((Log(N1+N2)-Log(N3))/Log(2)+Dimen[1]);

Hurst=2-Dimen;SmoothHurst = c1*(Hurst+Hurst[1])/2+c2*SmoothHurst[1]+c3*SmoothHurst[2];

Plot1(SmoothHurst);

Page 400: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ The HurstCoefficient inActionThe fractal dimensionindicator is applied toapproximately one year ofdata of Dollar General(symbol DG) in Figure 6.2using an input length of 30.With this setting, the Hurst

Page 401: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

coefficient swings betweenshowing persistence andantipersistence. However,when the input length isincreasedto200,asshowninFigure 6.3, the uptrend isreflected as the Hurstcoefficient rising tobeabove0.5.

Figure6.2UsinganInputLengthof30,theHurstCoefficientSwingsbetweenShowingPersistenceand

Page 402: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Antipersistence

Page 403: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure6.3TheLonger-TermTrendisIndicatedbyaHurstCoefficientGreaterthan0.5WhenanInputLengthof200IsUsed

Page 404: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

It is perhaps instructive to

Page 405: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

describe action of the Hurstcoefficient from anothertheoretical perspective. InFigure 6.4, the indicator isapplied to a theoretical sinewave whose period iscontinuously increasing fromleft to right from a period of10 bars to 40 bars. A periodof20barsisapproximatelyinthe horizontal center of thechart. In this case, I havegiven the Hurst coefficientindicator an input of 20.The

Page 406: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

periodicity in the persistentcase is due to the peaks andvalleysofthetimewaveformtending to “fill theboxes”ofthe fractal dimension. Fromthis perspective, the Hurstcoefficient can be used todefine trend modes (> 0.5)and cycle modes (< 0.5) inthe market relative to theselectedinputlength.

Figure6.4CyclePeriodsShorterthantheHurst

Page 407: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CoefficientInputParameterDisplayasAntipersistent;LongerCyclePeriodsDisplayasPersistent

Page 408: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 409: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Drunkard'sWalkHypothesis forMarketStructureThe efficient markets modelstatement that the price fullyreflects available informationhas been assumed to imply

Page 410: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

that successive price changesareindependentofeachother.In addition, it has usuallybeenassumed thatsuccessivechanges are identicallydistributed. Together, thesetwohypothesesconstitute therandom walk model. Thismodel says that theconditional and marginalprobabilitydistributionsofanindependent random variableare identical. In addition, itsays that the probability

Page 411: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

density function must be thesameforalltime.Thismodelisclearlyflawed.Ifthemeanreturn is constant over timethenthereturnisindependentof any information availableatagiventime.I assume that there are an

adequate number of tradersinvolved in making themarket that a statisticalanalysis involving a randomwalk is appropriate. There

Page 412: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

mustbeseveralconstraintstosucharandomwalk.Thefirstconstraint is that the pricesare constrained to onedimension—theycanonlygoup or down. The secondconstraint is that time mustprogressmonotonically.I propose a philosophical

basis of market action fromextensive work usingconstrained random walks inthe physical sciences.1 The

Page 413: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

expression of such a randomwalk is that of a drunkardmovingonaone-dimensionalarray of regularly spacedpoints. At regular intervalsthedrunkard flips a coin andmakesonesteptotherightorleft, depending on theoutcome of the coin toss. Attheendofn steps, he canbeatanyoneof2n+1sites,andthe probability that he is atanysitecanbecalculated.Letthe distance between the

Page 414: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

points on the lattice be Δ L,and let the time betweensuccessivestepsbeΔT.IfΔLandΔTareallowed toshrinktozeroinsuchawaythat(ΔL)2 / ΔT remains constant tothediffusionconstantD,thenthe equation governing thedistribution of thedisplacement of the randomwalkerfromhisstartingpointis

Page 415: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

This rather famous partialdifferential equation is calledthe diffusion equation. Thefunction P(x,t) can beinterpreted in two ways. Itcanbetakentoexpresseitherthe probability density or theconcentration of diffusingmatteratpositionxat time t.Following the latterinterpretation, it can, for

Page 416: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

example, describe the wayheat flows up the stem of asilverspoonwhenplacedinahotcupofcoffee.To better understand the

theory of diffusion, imaginethe way a smoke plumeleaves a smokestack. Thinkabouthowthesmokerisesascomparable to how a trendcarries itself through themarket. A gentle breezedeterminestheangletowhich

Page 417: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the smoke, or trend, is bent.The widening of the smokeplume represents theprobability density of thesmokeparticlesasa functionof distance from thesmokestack.Thiswideningisanalogous to the decreasedaccuracy of the prediction offuture trend prices furtherintothefuture.The formulation of the

drunkard's walk has no

Page 418: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

propertythatcanberegardedas the analog of momentum.Amorerealisticmodelofthemotion of a physical objectneeds to take into accountsome form of memory—weneed to know where theobject came from and thelikelihood that it willcontinuetomoveinthesamedirection. The simplestmodification of the randomwalkistoallowthecointossto determine the persistence

Page 419: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

of motion. In other words,with probability p thedrunkardmakeshisnextstepin the same direction as thelastone,andwithprobability1−phemakesamoveintheopposite direction. Theordinary drunkard's walkoccurswhenp=1/2becauseeithermove is equally likely.The interesting featureof themodified drunkard's walk isthat as the distance betweenthe point and the time

Page 420: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

between steps decreases, oneno longer obtains thediffusion equation, but ratherthefollowingequation:

in one dimension, where Tand c2 are constants. This isanother famous partialdifferential equation calledthe telegrapher's equation.This equation expresses theidea that diffusion occurs in

Page 421: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

restricted regions, such thatx2<c2t2.Thatis,thepositionmustbelessthanthevelocityof propagation (c)multipliedby time (t). More important,the telegrapher's equationdescribes the harmonicmotion of P(x, t) just assurely as it describes theelectric wave traveling downapairofwires.Harmonic motion is

ubiquitous. It is the natural

Page 422: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

response to a disturbance onany scale ranging from theatomic to the galactic. Youcan demonstrate the effect toyourself by holding a rulerover the edge of a table,bending the ruler down, andthen releasing it. Theresulting vibration isharmonic motion.Alternatively,youcanstretcha rubber band between yourfingers, pull the band to oneside, and then release it.The

Page 423: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

oscillations of the rubberbandalsoconstituteharmonicmotion.Sincethereareplentyof opportunities for marketdisturbances, it is only asmall stretch to extend thesolution to the drunkard'swalk problem from physicalphenomena and use it todescribe the action of themarket.The drunkard's walk

solution can describe two

Page 424: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

market conditions. The firstcondition, where theprobability is evenly dividedbetweenstepping to the rightortheleft,resultsinthetrendmode, described by thediffusion equation. Thesecond condition, where theprobability of motiondirectionisskewed,resultsinthecyclemode, describedbythe telegrapher's equation.The difference between thetwo conditions can be as

Page 425: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

simpleasthequestionthatthemajority of traders areconstantlyaskingthemselves.Ifthequestionis“Iwonderifthe market will go up ordown?,” then the probabilityofmarketmovementisabout50−50, establishing theconditions for a trend mode.However, if the question isposed as “Will the trendcontinue?,” then theconditions are such that thetelegrapher'sequationapplies.

Page 426: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Asaresult,thecyclemodeofthemarketcanbeestablished.The telegrapher's equation

solution also describes themeandering of a river.Viewed as an aerialphotograph,everyriverintheworld meanders. Thismeandering is not due to alack of homogeneity in thesoil, but to the conservationof energy. (You canappreciate that soil

Page 427: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

homogeneity is not a factorbecause other streams, suchas ocean currents, alsomeander in a nearlyhomogeneous medium.)Oceancurrentsarenotnearlyas visible as rivers and aretherefore not as familiar tomostofus.Everymeanderinariverisindependentofothermeanders, and thus all arecompletely random. If wewere to look at all themeanders as an ensemble,

Page 428: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

overlaying one on top of theotherlikeamultiple-exposurephotograph, the meanderrandomness would alsobecome apparent. Thecomposite envelope of theriver paths would be aboutthe same as the cross-sectionof the smoke plume.However,ifweareinagivenmeander, we are virtuallycertainof thegeneralpathofthe river for a short distancedownstream.Theresultisthat

Page 429: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the river can be described ashaving a short-termcoherencybutisrandomoverthelongerspan.River meanders are the

kindofcycleswehaveinthemarket.We canmeasure andusetheseshort-termcyclestoour advantage if we realizethey can come and go in thelongerterm.Wecanextendouranalogy

to understand when short-

Page 430: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

term cycles occur. Riversmeander in an attempt tomaintain a constant slope ontheirway to theocean. If theslope is too severe, themeanders have the sameeffect as a skierwhoweavesback and forth across theslopetoslowhisdescent.Theflow of a river physicallyadjusts itself for the purposeofenergyconservation.Ifthewaterspeedsup,thewidthofthe river decreases to yield a

Page 431: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

constant flow volume. Thefaster flow contains morekinetic energy, and the riverattempts to slow it down bychanging direction. At thesametime,theriverdirectioncannot change abruptlybecauseof themomentumofthe flow of water.Meandering results. Thus,meanders cause the river totake the path of leastresistance in the sense ofenergy conservation. We

Page 432: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

should think of markets thesame way. Time mustprogressassurelyastherivermust flow to the ocean.Overbought and oversoldconditions result from anattempt to conserve the“energy” of themarket. This“energy”arises from the fearandgreedoftraders.Again, itmay be useful to

test the principle ofconservation of energy for

Page 433: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

yourself.Teara stripabout1inchwidealong thesideofastandardsheetofpaperabout11 inches long. Grasp eachend of this strip between thethumbandforefingerofeachhand.Nowmove your handstoward each other. Yourcompressionisputtingenergyinto this strip, and its naturalresponsecantakeoneoffourmodes. These modes aredetermined by the boundaryconditions thatyou forced. If

Page 434: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

both hands are pointing up,the response is a singleupward arc, approximatingone alternation of a sinewave. If both hands arepointing down, the responseis a downward arc. If onehand is pointing up and theotherpointingdown,thestripresponse to the energy inputis approximately a full sinewave.Thefourlowestmodesare the natural responsesfollowing the principle of

Page 435: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

conservation of energy. Youcan introduce additionalbendsinthestrip,butaminorjiggling will cause the paperto snap to one of the fourlowestmodes,with the exactmode depending on theboundary conditions that youimpose. The two full sinewave modes areapproximately the secondharmonic of the two single-alternationmodes.

Page 436: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The market only has asingledominantcyclemostofthe time, as shown by thespectrum measurements inChapters8through10.Whenmultiple cycles aresimultaneously present, theyare generally harmonicallyrelated.Thisisnottosaythatnonharmonic simultaneouscycles cannot exist, just thatthey are rare enough to bediscounted in simplifiedmodelsofmarketaction.The

Page 437: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

general observation of asingle dominant cycle tendsto support thenotion that thenatural response to adisturbance is monotonicharmonicmotion.It is true that if you are a

hammer,therestoftheworldlooks like a nail. We musttakecaretorecognizethatallmarket action is not strictlydescribedbycyclesaloneandthatcycletoolsarenotalways

Page 438: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

appropriate.Amorecompletemodel of the market can beachieved by recognizing thefactthattherearetimeswhenthe solution to thetelegrapher's equationprevails and times when thesolution to the diffusionequation applies. We cantherefore divide the marketaction into a cyclemodeandatrendmode.Byhavingonlytwo modes in our marketmodel we can switch our

Page 439: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

trading strategy back andforthbetweenthem,usingthemore appropriate toolaccording to our situation.Since our digital signalprocessing tools analyzecycles,wecanestablishthatatrend mode is moreappropriateatanygiventimedue to the failure of a cyclemode.

Page 440: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Key PointstoRemember

1. The markets can becharacterized as noisehaving varying degreesoflong-termmemory.2. The Hurst coefficientis related to the powerspectral density of thenoise and to the fractaldimension. The use of

Page 441: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

these terms isinterchangeable.3. The Hurst coefficientis more estimated thancomputed.4. The Hurst coefficienthas no predictive valueand therefore has nodirect usefulness intrading.5.TheappearanceoftheHurst coefficient iscritically dependent on

Page 442: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

thelengthofdatausedtocomputeit.6. A Hurst coefficientless than 0.5 indicates acyclemode.7. A Hurst coefficientgreaterthan0.5indicatesatrendmode.8. A drunkard's walkmodel can also be usedto form a philosophicalbasisofmarketactivity.

Page 443: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Note1.G.H.WeissandR.J.Rubin,“RandomWalks:Theory and SelectedApplications,”Advancesin Chemical Physics 52(1982):363−505.

Page 444: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CHAPTER7

SpectralDilation

“The cycle swings aregetting bigger,” said

Page 445: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Tomexpansively.

Linear system theoryteaches that anyproblemcanbedividedintothree“boxes”:an input box, a transfer box,and an output box. Thetransfer box can be ascomplex as desired and canbe composed of many lesscomplex boxes wiredtogether. For this reason, Iassumed that if I applied afilter to inputdata theoutput

Page 446: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

wouldcontainonlyfrequencycomponents defined by thefilter. I have certainly beenawareof thefractalnatureofmarketdataandthelogspiralused by Fibonaccians, but itjust did not occur tome thatthe concept would extend tothefrequencyrangeofswing-tradingfilters.I coined the term Spectral

Dilation to encapsulate thesignificance of the effect.

Page 447: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

This effect has a profoundinfluence on all technicalindicators and is commonlyneglected because theseindicators are not viewedfrom the perspective of theirfrequency content. Theinterpretation of commonindicatorssuchastherelativestrength index (RSI) orStochastic are describedwiththe frequency distortions ofSpectralDilationimbeddedintheoutput.

Page 448: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ FrequencyContent ofIndicatorOutputsA“roofingfilter”canbeusedtolimitthefrequencycontentofaninputbeforeproceedingtoconstructanindicator.Theroofing filter is composed of

Page 449: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

a high-pass filter that passesonly frequency componentswhose periods are shorterthan 48 bars, for example. Italso is composed of aSuperSmoother filter thatpasses frequencycomponentswhoseperiodsarelongerthan10 bars. Thus, the roofingfilter is a wide bandwidthband-pass filter that passesonly frequency componentswhose periods fall between10barsand48bars.This,by

Page 450: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

itself, is a simple indicator.The EasyLanguage code forthisindicatorisgiveninCodeListing7-1, and the indicatoroutput is displayed in Figure7.1.

Figure7.1RoofingFilterDisplayDoesNotHaveaZeroMean

Page 451: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

While the roofing filter

Page 452: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

indicator wiggles inproportion to the wiggles inthe price data as you wouldexpect, it is noticeable thattheindicatorisabovezeroforextended periods where themarket is in an uptrend. Inotherwords, the filter outputdoesnothaveazeromeanasyou would expect if theoutput consisted only ofcyclic components whoseperiods fall between 10 barsand48bars.

Page 453: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CodeListing7-1.HP-LPRoofing

FilterEasyLanguage

Code{HP-LPRoofingFilter©2013JohnF.Ehlers}

Vars:alpha1(0),HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),

Page 454: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Filt(0);

//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48bars

alpha1=(Cosine(360/48)+Sine(360/48)-1)/Cosine(360/48);

HP = (1 - alpha1 / 2)*(Close-Close[1])+(1-alpha1)*HP[1];

//SmoothwithaSuperSmootherFilterfromequation3

a1=expvalue(-1.414*3.14159/10);

b1=2*a1*Cosine(1.414*180/10);

c2=b1;

c3=-a1*a1;

c1=1-c2-c3;

Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

Plot1(Filt);

Plot2(0);

The explanation for the

Page 455: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

lackofazeromeanisthattheinput data has a spectralpowerdensityproportionalto1/Fα,andthereforeincreasesamplitudeat the rateof6dBperoctave,moreor less.Thehigh-passfilterhasarejectionslope that increasesattenuation directlyproportional to F 0.5, or rollsoff at the rate of 6 dB peroctave. This response issimilar to the frequency

Page 456: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

responseshowninFigure1.2.Asaresult,theonlyeffectofthe high-pass filter is tobasically to equalize thefractal amplitude growth ofalllongerperiodsinthedata.Therefore, the filter outputstill contains all of thesefrequency components. Theonly way we can reduce theeffect of these lower-frequency components is tointroduce another high-passfilter, adding an additional 6

Page 457: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

dBperoctaveroll-off,sothattheneteffectofthefilterisasoriginally surmised. I haveadded Filt2 to the code inCode Listing 7-2, and theeffect is shown as the solidline in Figure 7.2. Theoriginal roofing filterresponse is shown with thecrosshatched markers. Notethat in addition toestablishinganominally zeromean, removalof the longer-cycle components caused by

Page 458: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

spectral dilation removes lagfromtheroofingfilteroutput.

Figure7.2ZeroMeanRoofingFilterOutputContainsOnlyDesiredFrequencyComponents

Page 459: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Since the roofing filter

Page 460: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

consists of the serialconnection of a one-polehigh-pass filter, aSuperSmoother, and anotherone-polehigh-passfilter, it isclearthebetterformulationoftheroofingfilterwouldbetheserial connection of a two-pole high-pass filter and theSuperSmoother.

CodeListing7-2.EasyLanguage

Page 461: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CodeforaZeroMeanRoofing

Filter{ZeroMeanRoofingFilter©2013JohnF.Ehlers

}

Vars:alpha1(0),HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),Filt2(0);

//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48bars

alpha1=(Cosine(360/48)+Sine(360/48)-1)/Cosine(360/48);

Page 462: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

HP = (1 - alpha1 / 2)*(Close-Close[1])+(1-alpha1)*HP[1];

//SmoothwithaSuperSmootherFilterfromequation3

a1=expvalue(-1.414*3.14159/10);

b1=2*a1*Cosine(1.414*180/10);

c2=b1;

c3=-a1*a1;

c1=1-c2-c3;

Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

Filt2= (1 - alpha1 / 2)*(Filt-Filt[1])+(1-alpha1)*Filt2[1];

Plot1(Filt);

Plot2(Filt2);

Plot6(0);

Page 463: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ RoofingFilter as anIndicatorThe roofing filter does anexcellent job of using onlythe frequency componentsbetween its upper and lowercriticalperiods.Allthatneedsto be done to create anindicator from the roofing

Page 464: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

filter is to add moregenerality by allowing thehigh-pass and low-passcriticalperiodsbesuppliedasindicator inputs. In the codeof Code Listing 7-3, the twohigh-pass filters have beenimplementedasasingletwo-polehigh-passfilter.The ideal time to buy is

whenthecycleisatatrough,and the ideal time to exit along position or to sell short

Page 465: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

iswhenthecycleisatapeak.These conditions are flaggedby the filter crossing itselfdelayed by twobars, and areincluded as part of theindicator.

CodeListing7-3.EasyLanguage

CodeforaRoofingFilterIndicator

{

Page 466: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

RoofingFilterIndicator©2013JohnF.Ehlers}

Inputs:LPPeriod(40),HPPeriod(80);

Vars:alpha1(0),HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),Filt2(0);

//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48bars

alpha1=(Cosine(.707*360/HPPeriod)+Sine(.707*360/HPPeriod)-1)/Cosine(.707*360/HPPeriod);

HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*(1-alpha1)*HP[2];

//SmoothwithaSuperSmootherFilterfromequation3

Page 467: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

a1=expvalue(-1.414*3.14159/LPPeriod);

b1=2*a1*Cosine(1.414*180/LPPeriod);

c2=b1;

c3=-a1*a1;

c1=1-c2-c3;

Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

Plot1(Filt);

Plot2(Filt[2]);

Plot6(0);

Anexampleof the roofingfilter indicator is shown inFigure 7.3, where the LPperiod rather arbitrarily hasbeen set at 40 and the HP

Page 468: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

period also has beenarbitrarily set at 80 bars. Acasual glance shows theroofing filter to be anexcellent indicator whosesignals are not marred bycomputational lag. The twoinputs can be set to get thebest response for a particularstock, exchange-traded fund,or future symbol. Thisindicator gives excellentguidance for discretionarytrading, but additional rules

Page 469: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

wouldberequiredtocreateagood mechanical tradingsystemfromit.If a normalized amplitude

indicator is desired, theautomaticgaincontrol(AGC)code fragment described inChapter5 canbe addedaftertheFiltcalculation.

Figure7.3TheRoofingFilterIsanOutstandingTechnicalIndicator

Page 470: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 471: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Impact ofSpectralDilation onConventionalIndicatorsConventional indicators arenot immune to the effects ofspectral dilation. Forexample, a Stochastic

Page 472: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

indicator remains near itsupperboundwhenthemarketisinanuptrendeventhougharelatively short lookbackperiod is used. This, ofcourse,isduetothepresenceofthelargerandlongercycliccomponents in the data. Idescribe the effect on theStochastic indicator withreference to Figure 7.4. AStochastic indicator basicallydisplays the current closingprice relative to the highest

Page 473: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

and lowest values in thelookback range. If you stopandthinkaboutit,thecurrentprice will tend to be in thehigh end of the range whenthemarketisinanuptrend.Ina broad sense, the classicStochastic indicator acts as aone-pole filter because thereisjustasingledifferencetermin the numerator of itscalculation. The firstsubgraphinFigure7.4showsmycalculationofaStochastic

Page 474: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

overa20-barlookbackrange.This calculation is the sameasthestandard,exceptIuseaSuperSmoother for thesmoothing instead ofmovingaverages. The bottomsubgraph shows an identicalcalculation except that theStochastic calculations areprecededbytheroofingfilterthat constrains the cycliccomponentstofallwithintherange from 10-bar to 48-barperiods. Clearly, the

Page 475: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Stochastic indicator has beendramatically altered by theinsertionoftheroofingfilter.

Figure7.4SpectralDilationRemovalHasaDramaticImpactontheStochasticIndicator

Page 476: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The interpretation and use

Page 477: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

oftheStochasticindicator,orany other indicator, precededby the roofing filter will notbe addressed.Thosekindsofapplicationscanfillbooksallby themselves. Therefore, Iwill leave it to the reader toexplore how standardindicators can be improvedsimply by inserting theroofing filter before theindicator computations arebegun.

Page 478: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Asapointofreference,theEasyLanguage code used tocreatethebottomsubgraphinFigure 7.4 is given in CodeListing7-4.

CodeListing7-4.EasyLanguage

CodetoComputetheModifiedStochasticIndicator

Page 479: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

{ModifiedStochasticIndicator©2013JohnF.Ehlers}

Inputs:Length(20);

Vars:alpha1(0),HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),HighestC(0),

LowestC(0),count(0),Stoc(0),MyStochastic(0);

//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48bars

alpha1=(Cosine(.707*360/48)+Sine(.707*360/48)-1)/Cosine(.707*360/48);

HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*

Page 480: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

(1-alpha1)*HP[2];

//SmoothwithaSuperSmootherFilterfromequation3

a1=expvalue(-1.414*3.14159/10);

b1=2*a1*Cosine(1.414*180/10);

c2=b1;

c3=-a1*a1;

c1=1-c2-c3;

Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

HighestC=Filt;

LowestC=Filt;

Forcount=0toLength-1BeginIfFilt[count]>HighestCthenHighestC=Filt[count];IfFilt[count]<LowestCthenLowestC=Filt[count];

End;

Stoc=(Filt-LowestC)/(HighestC-LowestC);

MyStochastic = c1*(Stoc+Stoc[1])/2+c2*MyStochastic[1]+c3*MyStochastic[2];

Plot1(MyStochastic);

Page 481: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

WellesWilder defined theRSIas

RSisshorthandforrelativestrength. That is, CU is thesum of the difference inclosing prices over theobservationperiodwherethatdifference is positive.Similarly, CD is the sum ofthe difference in closing

Page 482: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

prices over the observationperiod where that differenceis negative, but the sum isexpressed as a positivenumber. When we substituteCU/CDforRSandsimplifytheRSIequation,weget

Page 483: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

In other words, the RSI isthe percentage of the sum ofthedeltaclosesuptothesumofallthedeltaclosesovertheobservation period. The only

Page 484: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

variable here is theobservation period. To havemaximum effectiveness theobservation period should behalf of the measured period.If the observation period ishalf thedominantcycle, thenfor a pure sine wave, thecloses up is exactly equal tothetotalclosesduringpartofthe cycle from the valley tothepeak.Inthiscase,theRSIwould have a value of 100.During another part of the

Page 485: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

cycle—the next half cycle—therewould be no closes up.During this half cycle, theRSI would have a value ofzero.So,inprinciple,halfthemeasuredcycle is thecorrectchoice for the RSIobservation period. In Figure7.5 I have shown a standardRSI (except I used aSuperSmoother filter) in thefirst subgraph with amodifiedRSIthatisprecededby a roofing filter in the

Page 486: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

second subgraph. Themodified RSI is far moreresponsive and has less lagbecause the low frequencycomponents have beenremoved by the high-passpartof the roofing filter.TheRSI is functionally the sameas a single-pole high-passfilterbecause theCUterminthe numerator is just asummation of one-bardifferences.

Page 487: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure7.5TheModifiedRSIIsMoreResponsivethantheStandardRSI

Page 488: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

TheEasyLanguagecodeto

Page 489: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

compute the modified RSIindicator is given in CodeListing7-5.Thecomputationstarts with the roofing filter,followed by the routinecalculations for an RSI. Ihave included an optionalSuper-Smoother to producethe MyRSI variable. Theindicatorlagcanbereducedalittle by not using asmoothing filter, but thedecreased lag comes at theexpense of the indicator's

Page 490: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

beingmoreirregular.

CodeListing7-5.EasyLanguage

CodetoComputetheModifiedRSI

Indicator{ModifiedRSIIndicator©2013JohnF.Ehlers}

Inputs:Length(10);

Vars:alpha1(0),

Page 491: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),ClosesUp(0),ClosesDn(0),count(0),Denom(0),MyRSI(0);

//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48bars

alpha1=(Cosine(.707*360/48)+Sine(.707*360/48)-1)/Cosine(.707*360/48);

HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*(1-alpha1)*HP[2];

//SmoothwithaSuperSmootherFilterfromequation3

a1=expvalue(-1.414*3.14159/10);

b1=2*a1*Cosine(1.414*180/10);

c2=b1;

c3=-a1*a1;

Page 492: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

c1=1-c2-c3;

Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

ClosesUp=0;

ClosesDn=0;

Forcount=0toLength-1BeginIfFilt[count]>Filt[count+1]ThenClosesUp=ClosesUp+(Filt[count]-Filt[count+1]);IfFilt[count]<Filt[count+1]ThenClosesDn=ClosesDn+(Filt[count+1]-Filt[count]);

End;

Denom=ClosesUp+ClosesDn;

IfDenom<>0andDenom[1]<>0ThenMyRSI=c1*(ClosesUp/Denom+ClosesUp[1]/Denom[1])/2+c2*MyRSI[1]+c3*MyRSI[2];

Plot1(MyRSI);

Plot2(.7);

Plot6(.3);

Page 493: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Key PointstoRemember

1. Spectral Dilation isinherentlypartofmarketdata, arising from thefractalnatureofthedata.That is, longer cycleperiods necessarily havecorrespondingly largeramplitudeswings.2. Spectral Dilation is

Page 494: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

virtually ignored in allcommon technicalindicators.3. Ignoring SpectralDilation has led toerroneous, and oftenwacky, interpretation ofmarketactivity.4. Spectral Dilation canbecorrectedbyplacingaroofing filter before thecomputation ofindicators.

Page 495: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

5. A roofing filterestablishes a near zeromean of detrended databy allowing only cycliccomponents within thefilter pass band to bepassed on for furtheranalysis.6. The roofing filter,itself, can be asuccessful technicalindicator.7. Insertion of the

Page 496: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

roofing filter willdramatically change theuseand interpretationofstandard indicators,basically making themallnewindicators.

Page 497: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CHAPTER8

Autocorrelation“The correlations oftenrepeat,” said Tomperiodically.

Page 498: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Thisisanimportantchapterfor algorithmic tradersbecause the autocorrelationprocess yields a number ofunique and useful indicators.Autocorrelation is a simpleconcept.Themostrecentdatastream of a ticker symbol iscorrelatedwith a data streamof that same ticker symboldelayedbyaparametercalledlag. This computation isimportant to traders because

Page 499: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

unconventional processingleads to ascertaining theperiodicity of the price datawithout the distortion ofSpectral Dilation.Autocorrelation also leads tosome particularly insightfulturningpointsignals.

Page 500: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■BackgroundPeterSwerling isbestknownfor the class of statistically“fluctuating target”scatteringmodels he developed in theearly 1950s to characterizethe performance of pulsedradar systems, referred to asSwerling targets. He notedthat the return radar echoeswere noisy because ofsemirandom reflections from

Page 501: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

different parts of the aircraftbecause of the changingaspect of aircraft relative tothe radar transmitter. Therewere different kinds offluctuations due to targetshape and size, radarwavelength,andsoon.Somefluctuations would occurpulse to pulse, and otherswouldvarymoreslowly,suchas from scan to scan of theantenna. In fact, his earlywork led to the design of

Page 502: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

modern stealthy aircraft. Thenoisy radar echoes weresuccessfully modeled as aconstant plus a randomnumber with memory. Interms recognized by traders,the echoes were modeled asan exponential movingaverage (EMA) passesnumbers. The time constantoftheEMAwasdifferentforthevariousmodels,andmorecomplex models includedseveral EMAs. The Swerling

Page 503: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

model is entirely consistentwiththe1/Fαspectralmodelthat uses random inputswithlong-termmemory.Since there has been a

mountain of opinionregarding the randomness ofthemarket,itisreasonabletoapply a Swerling-like modeltoward the generation ofsynthetic data. Code Listing8-1 shows theEasyLanguagecode for generating such

Page 504: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

syntheticdata,andFigure8.1shows a presentation in thesubgraph below real marketdata.Theresult issubjective,butappearstobeareasonableapproximation to realmarketmovement. There is norelationship between the realpricesinthetopsubgraphandthe synthetic prices in thelower subgraph. Sincerandomnumbersareused,thedisplay will change everytime the indicator is

Page 505: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

computed. Therefore, Figure8.1 is simplyoneexampleofsynthetic prices. I probablycould have made thesimulation look a little morerealistic if I had taken morecare randomizing the dailypriceranges.

CodeListing8-1.EasyLanguageCodetoCreate

Page 506: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

SyntheticPricesUsingRandomNumberswithMemory

{SyntheticPrices©2013JohnF.Ehlers}

Inputs:alpha1(.05);

Vars:Opn(0),Hgh(0),Lw(0),Cls(0);

Cls = alpha1*(45+Random(10))+(1-alpha1)*Cls[1];

Hgh=Cls+Random(.125);

Page 507: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Lw=Cls-Random(.125);

Opn=Cls+(Random(.25)-.125);

IfOpn>HghThenOpn=Hgh;

IfOpn<LwThenOpn=Lw;

Plot1(Opn,“O”,Blue,0,3);

Plot2(Hgh,“H”,Blue,0,2);

Plot3(Lw,“L”,Blue,0,2);

Plot4(Cls,“C”,Blue,0,3);

Figure8.1RandomNumberswithMemoryProduceReasonableSyntheticPrices

Page 508: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Since synthetic prices

Page 509: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

createdbytakinganEMAofrandom numbers are areasonable approximation torealmarket prices, the pricescan be viewed as randomnumbers with memory. Alogical extension is that wecan gain insight into marketactivitybycorrelatingcurrentprices with prices in therecent history to takeadvantageofthememorypartof the model. At least thatwasmypremise.

Page 510: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■AutocorrelationIf we correlate a waveformcomposed of perfectlyrandomnumbersbyitself,thecorrelation will be perfect.However,ifwelagoneofthedata streams by just one bar,the correlation will bedramatically reduced. In along memory process with

Page 511: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

normally distributed randomnumbers the autocorrelationfollowsthepowerlaw:

whereC is a constant and αhasanominalvalueofunity.One of the underlying

principles of technicalanalysisisthatmarketdatadonot follow this power law ofan efficient market, and wetherefore can extractinformation from the partial

Page 512: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

correlation of theautocorrelationfunction.For example, assume the

data being examined is aperfect sine wave whoseperiod is 20 bars. Theautocorrelationwithzero lag,averagedoveronefullperiodof the sine wave, is unity.That is, the correlation isperfect. Introducing a lag ofonebarintheautocorrelationprocess causes the average

Page 513: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

correlation to be decreasedslightly. Introducing anotherbar of lag further decreasesthe average correlation, andso on. That is, until a lag of10 bars is reached. In thiscase, the positive alternationofthesinewaveiscorrelatedwith the negative alternationof the lagged waveform andthenegativealternationofthesine wave is correlated withthepositivealternationofthelagged waveform, with the

Page 514: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

result that perfectanticorrelation has beenreached. Continued lagincreases causes the averagecorrelation to increaseuntilalag of 20 bars is reached.When the lag is equal to theperiod of the sine wavewaveform, the correlation isagain perfect. In thistheoretical example, thecorrelation values as afunction of lag vary exactlyasasinewave.

Page 515: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Market data areconsiderably messier thanpurely random numbers orperfect sine waves butcontain features of both.However, the characteristicsthat are uncovered byautocorrelation offer uniquetrading perspectives. Sincethe process is relativelycomplicated, describing howthe computer code in CodeListing 8-2works is the bestpathtowardunderstanding.

Page 516: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CodeListing8-2.EasyLanguageCodeforthe

AutocorrelationIndicator

{AutocorrelationIndicator©2013JohnF.Ehlers}

Inputs:AvgLength(0);

Vars:alpha1(0), Filt2= (1 - alpha1 / 2)*(Filt-Filt[1])+(1-alpha1)*Filt2[1];HP(0),a1(0),

Page 517: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

b1(0),c1(0),c2(0),c3(0),Filt(0),M(0),N(0),X(0),Y(0),

Lag(0),count(0),Sx(0),Sy(0),Sxx(0),Syy(0),Sxy(0),Color1(0),Color2(0),Color3(0);

Arrays:Corr[48](0),AuroraRaw[48](0),Aurora[48](0);

//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48bars

alpha1=(Cosine(.707*360/48)+Sine(.707*360/48)-1)/Cosine(.707*360/48);

HP = (1 - alpha1 / 2)*

Page 518: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*(1-alpha1)*HP[2];

//SmoothwithaSuperSmootherFilterfromequation3

a1=expvalue(-1.414*3.14159/10);

b1=2*a1*Cosine(1.414*180/10);

c2=b1;

c3=-a1*a1;

c1=1-c2-c3;

Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

//Pearsoncorrelationforeachvalueoflag

ForLag=0to48Begin//SettheaveraginglengthasMM=AvgLength;IfAvgLength=0ThenM=Lag;//InitializecorrelationsumsSx=0;Sy=0;Sxx=0;Syy=0;Sxy=0;

Page 519: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

//AdvancesamplesofbothdatastreamsandsumPearsoncomponentsForcount=0toM-1BeginX=Filt[count];Y=Filt[Lag+count];Sx=Sx+X;Sy=Sy+Y;Sxx=Sxx+X*X;Sxy=Sxy+X*Y;Syy=Syy+Y*Y;End;//Computecorrelationforeachvalueoflag If (M*Sxx - Sx*Sx)*(M*Syy-Sy*Sy)>0ThenCorr[Lag]=(M*Sxy-Sx*Sy)/SquareRoot((M*Sxx-Sx*Sx)*(M*Syy-Sy*Sy));//Scaleeachcorrelationtorangebetween0and1 Corr[Lag] = .5*(Corr[Lag]+1);

End;

//PlotasaHeatmap

ForLag=3to48BeginIfCorr[Lag]>.5ThenBegin//VariescolorfromgreenatCorr[Lag]=1toyellow Color1 = 255*(2-2*Corr[Lag]);Color2=255;EndElseBegin//VariescolorfromyellowtoredatCorr[Lag]=0Color1=255;

Page 520: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Color2=2*255*Corr[Lag];End;Color3=0;IfLag=3ThenPlot3(3,“S5”,RGB(Color1,Color2,Color3),0,4);IfLag=4ThenPlot4(4,“S4”,RGB(Color1,Color2,Color3),0,4);IfLag=5ThenPlot5(5,“S5”,RGB(Color1,Color2,Color3),0,4);IfLag=7ThenPlot7(7,“S7”,RGB(Color1,Color2,Color3),0,4);IfLag=7ThenPlot7(7,“S7”,RGB(Color1,Color2,Color3),0,4);IfLag=8ThenPlot8(8,“S8”,RGB(Color1,Color2,Color3),0,4);

IfLag=9ThenPlot9(9,“S9”,RGB(Color1,Color2,Color3),0,4);IfLag=10ThenPlot10(10,“S10”,RGB(Color1,Color2,Color3),0,4);IfLag=11ThenPlot11(11,“S11”,RGB(Color1,Color2,Color3),0,4);IfLag=12ThenPlot12(12,“S12”,RGB(Color1,Color2,Color3),0,4);IfLag=13ThenPlot13(13,“S13”,RGB(Color1,Color2,Color3),0,4);IfLag=14ThenPlot14(14,“S14”,RGB(Color1,Color2,Color3),0,4);IfLag=15ThenPlot15(15,“S15”,RGB(Color1,Color2,Color3),0,4);IfLag=16ThenPlot16(16,“S16”,RGB(Color1,Color2,Color3),0,4);IfLag=17ThenPlot17(17,“S17”,RGB(Color1,Color2,Color3),0,4);IfLag=18ThenPlot18(18,“S18”,RGB(Color1,Color2,Color3),0,4);IfLag=19ThenPlot19(19,“S19”,RGB(Color1,Color2,Color3),0,4);IfLag=20ThenPlot20(20,“S20”,RGB(Color1,Color2,Color3),0,4);IfLag=21ThenPlot21(21,“S21”,RGB(Color1,Color2,Color3),0,4);IfLag=22ThenPlot22(22,“S22”,RGB(Color1,Color2,Color3),0,4);IfLag=23ThenPlot23(23,“S23”,RGB(Color1,Color2,Color3),0,4);IfLag=24ThenPlot24(24,“S24”,RGB(Color1,Color2,Color3),0,4);IfLag=25ThenPlot25(25,“S25”,RGB(Color1,Color2,Color3),0,4);IfLag=26ThenPlot26(26,“S26”,RGB(Color1,Color2,Color3),0,4);

Page 521: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

IfLag=27ThenPlot27(27,“S27”,RGB(Color1,Color2,Color3),0,4);IfLag=28ThenPlot28(28,“S28”,RGB(Color1,Color2,Color3),0,4);IfLag=29ThenPlot29(29,“S29”,RGB(Color1,Color2,Color3),0,4);IfLag=30ThenPlot30(30,“S30”,RGB(Color1,Color2,Color3),0,4);

IfLag=31ThenPlot31(31,“S31”,RGB(Color1,Color2,Color3),0,4);IfLag=32ThenPlot32(32,“S32”,RGB(Color1,Color2,Color3),0,4);IfLag=33ThenPlot33(33,“S33”,RGB(Color1,Color2,Color3),0,4);IfLag=34ThenPlot34(34,“S34”,RGB(Color1,Color2,Color3),0,4);IfLag=35ThenPlot35(35,“S35”,RGB(Color1,Color2,Color3),0,4);IfLag=36ThenPlot36(36,“S36”,RGB(Color1,Color2,Color3),0,4);IfLag=37ThenPlot37(37,“S37”,RGB(Color1,Color2,Color3),0,4);IfLag=38ThenPlot38(38,“S38”,RGB(Color1,Color2,Color3),0,4);IfLag=39ThenPlot39(39,“S39”,RGB(Color1,Color2,Color3),0,4);IfLag=40ThenPlot40(40,“S40”,RGB(Color1,Color2,Color3),0,4);IfLag=41ThenPlot41(41,“S41”,RGB(Color1,Color2,Color3),0,4);IfLag=42ThenPlot42(42,“S42”,RGB(Color1,Color2,Color3),0,4);IfLag=43ThenPlot43(43,“S43”,RGB(Color1,Color2,Color3),0,4);IfLag=44ThenPlot44(44,“S44”,RGB(Color1,Color2,Color3),0,4);IfLag=45ThenPlot45(45,“S45”,RGB(Color1,Color2,Color3),0,4);IfLag=46ThenPlot46(46,“S46”,RGB(Color1,Color2,Color3),0,4);IfLag=47ThenPlot47(47,“S47”,RGB(Color1,Color2,Color3),0,4);IfLag=48ThenPlot48(48,“S48”,RGB(Color1,Color2,Color3),0,4);

End;

Page 522: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The only input into theautocorrelation indicator isthe length over which theaveragingistobedone.Withthe default value of zero, theaveraging length is equal toeach lag. That way, theaveraging contains themaximum number of datasamples without overlappingthe original data stream andthe laggeddata stream.Afterdeclaring the variables andthe arrays, undesired long

Page 523: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

wave cyclic components areremovedbya two-polehigh-pass filter tuned to 48 bars.This value was selectedbecause it is more than twomonths of daily data and isfour hours of five-minuteintraday bars. It is unlikelythatlongerwaveswouldhavea beneficial impact on cyclictrading.Thehigh-passfilterisfollowed by theSuperSmoother of Equation3-3, and whose transfer

Page 524: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

response is displayed inFigure 3.10. The 10-barperiod for this filter wasselected for practical tradingreasons.Thinkofitthisway:The shortest period possibleto use (the Nyquistfrequency) has only twosamples per period. If youwere trading this period andgotahighsample,youcouldenter only on the next bar atthe low sample. This wouldbe an easy trade if the cycle

Page 525: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

period were consistent, butmarket cycles are notconsistent. The situation isnot much better at cycliccomponentsanoctavesloweratfourbarsperperiod.Thereisjustnotenoughtimetogetthesignalandthenimplementthe trade. At another octaveslower at eight samples percycle, one can start toconsider rapid tradingbecausethereareseveralbarsof follow-through after the

Page 526: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

signalisobtained.Inaperfectworld, you would be tradingasoftenasevery fourbars—onehalfoftheshortestusefulcyclic period. Thus, thecombination of the high-passfilter and the SuperSmootherformaroofingfilterthatpassonly the desired range offrequency components usefulfortrading.Textbook Pearson

correlation is accomplished

Page 527: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

for each of the lag periodsfrom 1 to 48, and acorrelation value is assignedto each lag period. Thevariable Y is the base datastream, and thevariableX isthe data stream delayed bythe lag variable for eachcalculation loop. The valuesofX,Y,X*X,X*Y,andY* Y are summed over theaveraginglengthbeforebeingapplied to the correlationequation. The default

Page 528: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

averaging length is equal tothe lag so that the fullduration of the lag iscorrelated and averaged. Thecorrelation resulting from thecomputations varies fromminus 1 to plus 1, andtherefore is rescaled to varybetween 0 and 1 for plottingpurposes.There is a considerable

amount of information to bedisplayed, and so aheatmap

Page 529: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

isusedtomakesenseofitall.Thegeneralschemeisthatforeach horizontal axis timeposition the verticaldisplacement is equal to thelag from 3 to 48. Thecorrelationvalueforeachlagisconvertedtoacolor.Color1isredandColor2isgreen.When the correlation has avalue of 1, there is onlygreen. At a correlation valueof 0.5, both red and greenhave their maximum values,

Page 530: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

creating yellow by theircombination. When thecorrelationvalueiszero,thenthere isonly red. In thiswaya “stoplight” display iscreated,where green denotesperfect correlation, reddenotes perfectanticorrelation, and yellowrepresents intermediatevalues.The autocorrelation

indicator applied to

Page 531: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

approximatelyoneyear'sdataof Dollar General (symbolDG) is shown in Figure 8.2.Following along the bottomoftheindicatorsubgraph,theautocorrelation indicatorturns red at every pricereversal, indicatinganticorrelation. The indicatoris green between the pricereversals, indicating goodcorrelation of the databetween the price reversals.Rising vertically in the

Page 532: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

subgraph, the indicatormorphsintoamorecloudlikedisplay because of theadditionalsmoothingoverthelonger lag periods. Theseclouds tend to give mixedmessages. For example, thedataareanticorrelatedforlagperiods around 20 barsbecauseof thered“cloud”inthat area. However, the dataare well correlated for lagperiods between 30 and 40barsoverthesameperiod.

Page 533: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure8.2AutocorrelationIndicatorShowsCorrelationtoItselfOveraRangeofLagPeriods

Page 534: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Since averaging tends to

Page 535: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

obscure the meaning of thedisplay in the short term,where the display can beusefulfortrading,itwouldbeinteresting to see the displaywheretheaveraginglengthisonly three bars for all valuesof the lag period. Three barsis the minimum amount ofdata that can be used foraveraging. We do this bychanging the input from itsdefault value of 0 to a valueof 3.The resulting display is

Page 536: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

showninFigure8.3.

Figure8.3AutocorrelationIndicatorwithanAveragingPeriodofThree

Page 537: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Aside from appearing

Page 538: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

psychedelic, there are twodistinct characteristics of theautocorrelation indicatorusing minimum averaging.First,thereisasharpreversalfrom red to green and fromgreen to red at the timing ofprice reversals forallperiodsof lag. Second, there is avariation of the thickness ofthe bars and the number ofbarsovertheverticalrangeofthe indicator as a functionoftime.

Page 539: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The meaning of theindicator becomes clearerwhen applied to a theoreticalsinewavewhoseperiodis20bars in Figure 8.4. In thiscase,thesharpreversalsfromred to green and vice versaoccur exactly threebars afterthe peaks and valleys of thesine wave. Carefulexaminationoftheseparationofthelagperiodsbetweenthebottom of a red bar to thebottom of the next red bar

Page 540: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

aboveit(orgreenbarsifyouprefer) shows that theseparation is exactly 20bars.Inotherwords,theseparationyields the periodicity of thewaveform. Knowing thischaracteristic, we can extractthe spectral information fromtheautocorrelationfunction.

Figure8.4AutocorrelationofaTheoretical20-BarSineWave

Page 541: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 542: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■AutocorrelationPeriodogramConstruction of theautocorrelation periodogramstartswiththeautocorrelationfunction using the minimumthree bars of averaging. Thecyclic information isextracted using a discrete

Page 543: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Fourier transform (DFT) ofthe autocorrelation results.This approach has at leastfour distinct advantages overother spectral estimationtechniques.Theseare:

1. Rapid response. Thespectralestimatesstarttoformwithin a half-cycleperiodoftheirinitiation.2.Relativecyclicpoweras a function of time isestimated. The

Page 544: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

autocorrelation at allcycleperiodscanbelowif there are no cyclespresent, for example,during a trend. Previousworks treated themaximum cycleamplitude at each timebarequally.3.Theautocorrelation isconstrained to bebetween minus one andplus one regardless of

Page 545: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the period of themeasured cycle period.Thisobviatestheneedtocompensate for SpectralDilation of the cycleamplitude as a functionofthecycleperiod.4. The resolution of thecyclic measurement isinherently high and isindependent of anywindowing function ofthepricedata.

Page 546: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The autocorrelationperiodogram is describedwith reference to theEasyLanguage code in CodeListing 8-3. Theautocorrelation periodogramstarts with the same code asin Code Listing 8-2. Afterdeclaring variables,prefiltering is accomplishedby a 48-bar high-pass filterfollowed by a 10-barSuperSmoother described inEquation 3-3. The

Page 547: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

autocorrelation isaccomplished for each valueof lag using a textbookPearsoncorrelationapproach.The DFT is accomplished

by correlating theautocorrelation at each valueof lag with the cosine andsine of each period ofinterest. The sum of thesquares of each of thesevalues represents the relativepowerateachperiodfromthe

Page 548: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

familiar trigonometricequation:

There can be largevariations in the powermeasurementfrombartobar,and EMA is used to smooththe power measurement ateachperiod.Inthenextblockofcodea

fast attack−slow decayautomaticgaincontrol(AGC)is used to normalize the

Page 549: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

spectral components and todevelop the variance of thespectralpowerovertime.TheAGCconceptwas introducedin Chapter 5. If the currentpower is greater than thevariable MaxPwr, then thevariable MaxPwr isimmediately set to the valueof the current power.However,ifthecurrentpowerislessthanMaxPwr,thentheMaxPwr is allowed to decayto0.991ofitspreviousvalue.

Page 550: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The dominant cycle isextracted from the spectralestimate in the next block ofcodeusingacenter-of-gravity(CG) algorithm. The CGalgorithm measures theaverage center of two-dimensional objects. It iscomputedby summing theYvalues and independentlysumming the X * Y values.Dividing the latter by theformer yields the averageposition along the X axis

Page 551: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

wherealltheYvaluesreside.In the case of computing thedominant cycle, theYvaluesare power and the X valuesare the periods. Thus, thealgorithm computes theaverage period at which thepowers are centered. That isthe dominant cycle. Thedominantcycleisavaluethatvaries with time and can beused to automatically tuneother indicators such as theband-pass filter, commodity

Page 552: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

channel index (CCI), relativestrength index (RSI),Stochastic,andsoon.The spectrum values vary

between 0 and 1 after beingnormalized.These values areconvertedtocolors.Whenthespectrum is greater than 0.5,the colors combine red andgreen, with yellow being theresultwhenspectrum=1andredbeing theresultwhen thespectrum = 0.5. When the

Page 553: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

spectrum is less than0.5, thered saturation is decreased,with the result the color isblack when spectrum = 0.Since themaximum value ofthe spectrum is unity, I haveincludedanoptionalblockofcode (which has beencommented out by the curlybrackets) that providesadditional visual resolutionby raising the spectralcomponents to a higherpower. The selection of the

Page 554: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

powertobeusedisarbitrary.

CodeListing8-3.AutocorrelationPeriodogramEasyLanguage

Code{AutocorrelationPeriodogram©2013JohnF.Ehlers}

Vars:AvgLength(3),M(0),N(0),

Page 555: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

X(0),Y(0),alpha1(0),HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),Lag(0),count(0),Sx(0),Sy(0),Sxx(0),Syy(0),Sxy(0),Period(0),Sp(0),Spx(0),MaxPwr(0),DominantCycle(0),Color1(0),Color2(0),Color3(0);

Arrays:Corr[48](0),CosinePart[48](0),

Page 556: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

SinePart[48](0),SqSum[48](0),R[48,2](0),Pwr[48](0);

//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48bars

alpha1=(Cosine(.707*360/48)+Sine(.707*360/48)-1)/Cosine(.707*360/48);

HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*(1-alpha1)*HP[2];

//SmoothwithaSuperSmootherFilterfromequation3

a1=expvalue(-1.414*3.14159/10);

b1=2*a1*Cosine(1.414*180/10);

c2=b1;

c3=-a1*a1;

c1=1-c2-c3;Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

//PearsoncorrelationforeachvalueoflagForLag=0to48Begin//SettheaveraginglengthasMM=AvgLength;

Page 557: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

IfAvgLength=0ThenM=Lag;Sx=0;Sy=0;Sxx=0;Syy=0;Sxy=0;Forcount=0toM-1BeginX=Filt[count];Y=Filt[Lag+count];Sx=Sx+X;Sy=Sy+Y;Sxx=Sxx+X*X;Sxy=Sxy+X*Y;Syy=Syy+Y*Y;End; If (M*Sxx - Sx*Sx)*(M*Syy-Sy*Sy)>0ThenCorr[Lag]=(M*Sxy-Sx*Sy)/SquareRoot((M*Sxx-Sx*Sx)*(M*Syy-Sy*Sy));End;

ForPeriod=10to48BeginCosinePart[Period]=0;SinePart[Period]=0;ForN=3to48BeginCosinePart[Period]=CosinePart[Period]+Corr[N]*Cosine(370*N/Period);SinePart[Period]=SinePart[Period]+Corr[N]*Sine(370*N/Period);End;SqSum[Period]=CosinePart[Period]*CosinePart[Period]+SinePart[Period]*SinePart[Period];

End;

Page 558: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ForPeriod=10to48BeginR[Period,2]=R[Period,1];R[Period,1]=.2*SqSum[Period]*SqSum[Period]+.8*R[Period,2];

End;

//FindMaximumPowerLevelforNormalization

MaxPwr=.995*MaxPwr;

ForPeriod=10to48BeginIfR[Period,1]>MaxPwrThenMaxPwr=R[Period,1];

End;

ForPeriod=3to48BeginPwr[Period]=R[Period,1]/MaxPwr;

End;

//ComputethedominantcycleusingtheCGofthespectrum

Spx=0;

Sp=0;

ForPeriod=10to48BeginIfPwr[Period]>=.5ThenBeginSpx=Spx+Period*Pwr[Period];Sp=Sp+Pwr[Period];End;

End;

IfSp<>0ThenDominantCycle=Spx/Sp;

Page 559: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Plot2(DominantCycle,“DC”,RGB(0,0,255),0,2);

{

//IncreaseDisplayResolutionbyraisingtheNormPwrtoahighermathematicalpower(optional)

ForPeriod=10to48BeginPwr[Period]=Power(Pwr[Period],2);

End;

}

//PlotasaHeatmap

Color3=0;

ForPeriod=10to48BeginIfPwr[Period]>.5ThenBeginColor1=255; Color2 = 255*(2*Pwr[Period]-1);End

ElseBeginColor1=2*255*Pwr[Period];Color2=0;End;IfPeriod=3ThenPlot3[0](3,“S5”,RGB(Color1,Color2,Color3),0,4);IfPeriod=4ThenPlot4[0](4,“S4”,RGB(Color1,Color2,Color3),0,4);IfPeriod=5ThenPlot5[0](5,“S5”,RGB(Color1,Color2,Color3),0,4);

Page 560: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

IfPeriod=6ThenPlot6[0](6,“S6”,RGB(Color1,Color2,Color3),0,4);IfPeriod=7ThenPlot7[0](7,“S7”,RGB(Color1,Color2,Color3),0,4);IfPeriod=8ThenPlot8[0](8,“S8”,RGB(Color1,Color2,Color3),0,4);IfPeriod=9ThenPlot9[0](9,“S9”,RGB(Color1,Color2,Color3),0,4);IfPeriod=10ThenPlot10[0](10,“S10”,RGB(Color1,Color2,Color3),0,4);IfPeriod=11ThenPlot11[0](11,“S11”,RGB(Color1,Color2,Color3),0,4);IfPeriod=12ThenPlot12[0](12,“S12”,RGB(Color1,Color2,Color3),0,4);IfPeriod=13ThenPlot13[0](13,“S13”,RGB(Color1,Color2,Color3),0,4);IfPeriod=14ThenPlot14[0](14,“S14”,RGB(Color1,Color2,Color3),0,4);IfPeriod=15ThenPlot15[0](15,“S15”,RGB(Color1,Color2,Color3),0,4);IfPeriod=16ThenPlot16[0](16,“S16”,RGB(Color1,Color2,Color3),0,4);IfPeriod=17ThenPlot17[0](17,“S17”,RGB(Color1,Color2,Color3),0,4);IfPeriod=18ThenPlot18[0](18,“S18”,RGB(Color1,Color2,Color3),0,4);IfPeriod=19ThenPlot19[0](19,“S19”,RGB(Color1,Color2,Color3),0,4);IfPeriod=20ThenPlot20[0]

Page 561: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

(20,“S20”,RGB(Color1,Color2,Color3),0,4);IfPeriod=21ThenPlot21[0](21,“S21”,RGB(Color1,Color2,Color3),0,4);

IfPeriod=22ThenPlot22[0](22,“S22”,RGB(Color1,Color2,Color3),0,4);IfPeriod=23ThenPlot23[0](23,“S23”,RGB(Color1,Color2,Color3),0,4);IfPeriod=24ThenPlot24[0](24,“S24”,RGB(Color1,Color2,Color3),0,4);IfPeriod=25ThenPlot25[0](25,“S25”,RGB(Color1,Color2,Color3),0,4);IfPeriod=26ThenPlot26[0](26,“S26”,RGB(Color1,Color2,Color3),0,4);IfPeriod=27ThenPlot27[0](27,“S27”,RGB(Color1,Color2,Color3),0,4);IfPeriod=28ThenPlot28[0](28,“S28”,RGB(Color1,Color2,Color3),0,4);IfPeriod=29ThenPlot29[0](29,“S29”,RGB(Color1,Color2,Color3),0,4);IfPeriod=30ThenPlot30[0](30,“S30”,RGB(Color1,Color2,Color3),0,4);IfPeriod=31ThenPlot31[0](31,“S31”,RGB(Color1,Color2,Color3),0,4);IfPeriod=32ThenPlot32[0](32,“S32”,RGB(Color1,Color2,Color3),0,4);IfPeriod=33ThenPlot33[0](33,“S33”,RGB(Color1,Color2,Color3),0,4);IfPeriod=34ThenPlot34[0]

Page 562: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

(34,“S34”,RGB(Color1,Color2,Color3),0,4);IfPeriod=35ThenPlot35[0](35,“S35”,RGB(Color1,Color2,Color3),0,4);IfPeriod=36ThenPlot36[0](36,“S36”,RGB(Color1,Color2,Color3),0,4);IfPeriod=37ThenPlot37[0](37,“S37”,RGB(Color1,Color2,Color3),0,4);IfPeriod=38ThenPlot38[0](38,“S38”,RGB(Color1,Color2,Color3),0,4);IfPeriod=39ThenPlot39[0](39,“S39”,RGB(Color1,Color2,Color3),0,4);IfPeriod=40ThenPlot40[0](40,“S40”,RGB(Color1,Color2,Color3),0,4);IfPeriod=41ThenPlot41[0](41,“S41”,RGB(Color1,Color2,Color3),0,4);IfPeriod=42ThenPlot42[0](42,“S42”,RGB(Color1,Color2,Color3),0,4);IfPeriod=43ThenPlot43[0](43,“S43”,RGB(Color1,Color2,Color3),0,4);

IfPeriod=44ThenPlot44[0](44,“S44”,RGB(Color1,Color2,Color3),0,4);IfPeriod=45ThenPlot45[0](45,“S45”,RGB(Color1,Color2,Color3),0,4);IfPeriod=46ThenPlot46[0](46,“S46”,RGB(Color1,Color2,Color3),0,4);IfPeriod=47ThenPlot47[0](47,“S47”,RGB(Color1,Color2,Color3),0,4);IfPeriod=48ThenPlot48[0]

Page 563: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

(48,“S48”,RGB(Color1,Color2,Color3),0,4);End;

The autocorrelationperiodogram for DollarGeneral (symbol DG) overapproximately one year ofdata is shown in Figure 8.5.The spectrum display is intimesynchronizationwiththeprice bars above it. Thevertical scale is the cyclelength in termsofnumberofbars. Using this scale, the

Page 564: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

spectrum display is equallyapplicable to intradaydataasit is to daily or weekly data.The cycle strength is coloredfromyellowtoblackasifthemeasurement is going fromwhite hot through red hot tocold. It is obvious from thespectrum display that marketcycles are evanescent—theycomeandgoandchangetheirperiodicity over time. Theblue line throughroughly thecenter of the strongest

Page 565: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

components in the spectrumis the computed dominantcycle.

Figure8.5AutocorrelationPeriodogramforDG

Page 566: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure 8.5 is a time-

Page 567: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

frequency representation(TFR)thatiseasilyusablebytraders by interpreting colorsasthestrengthofthespectralcomponents.Academia1 usescontour plots and waterfalldiagrams to display theresultsoftheircalculations.Awide range of techniques isemployed to measure thespectra of market data,including wavelets. Many ofthese techniques require

Page 568: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

analytic data that are noteasily available to traders.Mostimportant,noneofthesetechniques havecompensation for SpectralDilation.

Page 569: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■AutocorrelationReversalsOne of the distinctivecharacteristics of Figures 8.3and 8.4 is that theautocorrelation shifts fromgreen to red or from red togreen at all values of lag atthe cyclic reversals of the

Page 570: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

price. Therefore, all we needdo to determine thesereversalsistosumthebar-to-bar differences of theautocorrelation functionacrossallvaluesoflag.Whenthe sum is large a turningpointhasbeenidentified.TheEasyLanguage code tocompute these turning pointsisshowninCodeListing8-4.The indicated reversals arevery sensitive to thesmoothing of the price data.

Page 571: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Therefore, the LPLength ismade available as anindicator input todecreaseorincrease the number ofindicatedreversalsasdesired.The AvgLength parameter

is also made available as anindicator because thisaveraging also impacts thenumber of indicatedreversals. Care should betaken when increasing thevalue of this input because

Page 572: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the lag of the indicatorincreases in direct proportiontotheincreaseofthevalueoftheAvgLength.Typicaldelayof the indicatorwillbeaboutthree bars when theAvgLength parameter is settoavalueof3.TheHPLengthparameteris

also made available as aninput for complete flexibilityof the indicator. However,changing its value has a

Page 573: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

relatively minor impact ontheindicatedreversals.

CodeListing8-4.EasyLanguage

CodetoCompute

AutocorrelationReversals

{AutocorrelationReversals©2013JohnF.Ehlers}

Page 574: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Inputs:HPLength(48),

LPLength(10),AvgLength(3);

Vars:alpha1(0),HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),M(0),N(0),X(0),Y(0),Lag(0),count(0),Sx(0),Sy(0),Sxx(0),Syy(0),Sxy(0),SumDeltas(0),Reversal(0);

Arrays:

Page 575: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Corr[48,2](0);

//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48bars

alpha1=(Cosine(.707*360/48)+Sine(.707*360/48)-1)/Cosine(.707*360/48);

HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*(1-alpha1)*HP[2];

//SmoothwithaSuperSmootherFilterfromequation3

a1=expvalue(-1.414*3.14159/LPLength);

b1=2*a1*Cosine(1.414*180/LPLength);

c2=b1;

c3=-a1*a1;

c1=1-c2-c3;

Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

//Pearsoncorrelationforeachvalueoflag

ForLag=3to48BeginCorr[Lag,2]=Corr[Lag,1];//SettheaveraginglengthasMM=AvgLength;IfAvgLength=0ThenM=Lag;

Page 576: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

//InitializecorrelationsumsSx=0;Sy=0;Sxx=0;Syy=0;Sxy=0;//AdvancesamplesofbothdatastreamsandsumPearsoncomponentsForcount=0toM-1BeginX=Filt[count];Y=Filt[Lag+count];Sx=Sx+X;Sy=Sy+Y;Sxx=Sxx+X*X;Sxy=Sxy+X*Y;Syy=Syy+Y*Y;End;//Computecorrelationforeachvalueoflag If (M*Sxx - Sx*Sx)*(M*Syy-Sy*Sy)>0ThenCorr[Lag,1]=(M*Sxy-Sx*Sy)/SquareRoot((M*Sxx-Sx*Sx)*(M*Syy-Sy*Sy));//Scaleeachcorrelationtorangebetween0and1 Corr[Lag, 1] = .5*(Corr[Lag,1]+1);

End;

SumDeltas=0;ForLag=3to48BeginIf(Corr[Lag,1]>.5andCorr[Lag,2]<.5)Or(Corr[Lag,1]<.5andCorr[Lag,2]>.5)ThenSumDeltas=SumDeltas+1;

Page 577: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

End;

Reversal=0;

IfSumDeltas>24ThenReversal=1;

Plot1(Reversal);

The autocorrelationreversals indicator is shownin Figure 8.6 using twodifferent values of theLPLength input. Thereversalsinthefirstsubgraphare computed using anLPLength of 20, and wouldbe suitable for trading

Page 578: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

systems holding positions inthe range from10bars to 20bars. The reversals in thebottom subgraph arecomputedusinganLPLengthof 10, and would be moresuitable for more activetrading systems holdingpositionsfromafewdaystoaweek.

Figure8.6TheNumberofIndicatedReversalsIsDecreasedbyIncreasingthe

Page 579: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ValueoftheLPLengthParameter

Page 580: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 581: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Key PointstoRemember

1. The autocorrelationperiodogram has theleast latency of allmarket data spectralestimates.2. The autocorrelationperiodogramautomatically estimatesthe totalcyclicpower in

Page 582: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

thedataasa functionoftime.3. The autocorrelationperiodogramprovidesanaccurate estimate of themarketspectrumwithoutthe need forcompensation forSpectralDilation.4. The autocorrelationperiodogram resolutionis independent of anywindowing function of

Page 583: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

thepricedata.5. Price reversals areindicated by a dramaticswitch in correlations atall values of lag. Thesereversals can be used asareliableindicator.

Page 584: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Note1. Boualem Boushash,Time-Frequency SignalAnalysis (Kidlington,Oxford, UK: ElsevierLtd.,2003).

Page 585: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CHAPTER9

FourierTransforms

“The spectrum displaysare colorful,” said Tom

Page 586: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

plainly.

In technical circles the termFFT (fast Fourier transform)is nearly synonymous withfrequency measurement, andtherefore the expectation isthatFouriertransformswouldbe the techniqueofchoice tomeasure market cycles.However,doingsomeanstheviolation of three basicrequirements of Fouriertransforms. These

Page 587: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

requirementsare:1.Thedata sampleusedis a representative of aninfinitely long string ofdata.2. The data must bestationary (unchangingcharacteristics) over thesample.3. Only an integernumber of cycles overthesamplelengthcanbeanalyzed to avoid end

Page 588: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

effectsintheanalysis.As we saw in Chapter 8,

marketcyclesareevanescent.They come and go andchange periodicity. This factalone is not consistent withrequirements 1 and 2 above.Supposewestartwith64barsof data. The smallest integernumber of cycles fitting inthis data is one (a 64-barcycle). The next shortestallowablecycleperiodis64/

Page 589: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

2=32barcyclebecause2isnextlargestintegernumberofallowed cycles. The nextshortest allowed cycle periodis64/3=21.3bars,andthenext shortest is 64 / 4 = 16bar cycle, and so on. Theshortest allowed cycle periodis a two-bar cycle, becauseany shorter cycle periodviolatestheNyquistsamplingcriteria of requiring at leasttwo samples per cycle. Thepointisthatitisunrealisticto

Page 590: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

expect a relatively short 12-bar market cycle to remainconsistent in amplitude andfrequency even over arelatively short data sampleof 64 bars. But even if thestationarity constraint ismet,the short data sample yieldsan extremely poormeasurement resolution. Forexample, the closest spectrallines between a 16-bar cycleand a 21.3-bar cycle yield aresolution of 5 bars, or 31

Page 591: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

percent relative to the 16-barcycle. The only way toimprove the resolution is toincreasethelengthofthedatasample, which exacerbatestheproblemswithstationarityand averaging out short-termresults over the longer term.Further, increasing the datalength increases the latencyofthemeasuredresult,furthercontributingtolag.Nonetheless, I have been

Page 592: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

able to bludgeon thetechnology by taking liberallicense with themathematicsto compute a Fouriertransform that produces aspectralestimatethatisusefulfortraders.Theapproachistocompute a moving discreteFourier transform (DFT).Each computation is a blockcalculationoverthehistoricaldata window, and the entireblockcomputationisrepeatedfor each succeeding bar of

Page 593: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

data.Oneofthetricksusedistocompute theDFTin termsofcycleperiodrather than inthe more conventionalcomputation in terms offrequency.Traders can relateto a 20-bar cycle period, buttheequivalent0.05cyclesperbar frequency has noparticular meaning. Anotherkey feature to making theDFT usable is to display thespectral estimate as a heatmap.

Page 594: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ SpectralDilationItisobvious,oncestated,thatannual cycle swings aregreater than monthly cycleswings, that monthly cycleswings are greater than dailycycle swings, and that dailycycle swingsaregreater thanhourly cycle swings. This isSpectral Dilation. Spectral

Page 595: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Dilation is approximatelylinearly proportional to theperiod of the cycle beingconsidered. If one is seekingthe dominant cycle over arelativelysmallrangeofcycleperiods,SpectralDilationcanbe ignored. However, if thedominant cycle is beingextracted from datacontaining several octaves ofcycle periods, then fractaldilationmustbecompensatedinthecomputationalprocess.

Page 596: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

I discovered the necessityfor Spectral Dilationcompensation whencorrelatingthespectralresultsusing the autocorrelationperiodogram and the DFTdescribedinthischapter.Theautocorrelation periodogramdescribed in Chapter 8requires no compensationbecause the relativeamplitudes of the spectralcomponents are extractedfrom the correlation

Page 597: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

waveforms that areconstrainedtoswingbetween−1and+1.However,spectralcomponents used in thecomputation of the DFT aresubject to Spectral Dilation.Therefore, Spectral Dilationcompensation is required fora correct spectral estimateusingtheDFTalgorithm.

Page 598: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ DiscreteFourierTransform(DFT)TheDFT isaccomplishedbycorrelating the data with thecosineandsineofeachperiodof interest over the selectedwindow period. The sum of

Page 599: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the squares of each of thesecorrelated values representsthe relative power at eachperiod from the familiartrigonometricequation:

The code to compute theDFT is shown in CodeListing 9-1. The only userinput is whether to selectSpectral Dilationcompensation. The defaultselection is to use the

Page 600: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

compensation. The defaultwindow length is 48 bars,selected to be one full cycleperiod of the longest cycleperiod to be computed. Thearrays are sized for thelongest cycle period's being48 bars. After declaring thevariables, the data areprefiltered in a high-passfilter having a 48-bar cutoffperiod to be consistent withour longest computed cycleperiod and then smoothed in

Page 601: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

theSuperSmoother,describedinEquation3-3,andhavinga10-bar cutoff period to beconsistent with the shortestcycleperiodofinterest.EasyLanguageexecutesthe

entire code from top tobottom for each new bar ofdata from oldest to newest.Computation of the DFT foreach new data bar starts bymultiplying the data with asinewaveandacosinewave,

Page 602: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

respectively, divided by theperiod being calculated andsumming the products overthe window length. In thiscase, thewindow lengthwasmade to be equal to theperiod of the longest cycleperiod to be computed. Thesine part and cosine part ofthe wave at each period aresquared and summed tocompute the power at eachperiod. The wave amplitudeof each period computation

Page 603: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

was divided by the valuefractaldilationcompensation.If the spectral dilationcompensation input is set tofalse,thewaveamplitudesaresimplydividedby1,withtheeffect that there is nocompensation.Inthenextblockofcode,a

fast attack−slow decayautomaticgaincontrol(AGC)is used to normalize thespectral components and to

Page 604: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

minimize the variance of thespectralpowerovertime.TheAGCconceptwas introducedin Chapter 5 of this book;however, in thiscase,wearescalingonthebasisofpowerrather than on waveamplitude. Therefore, thecorrect decay factor is thesquare root of 0.991, or0.995.If thecurrentpowerisgreater than the variableMaxPwr, then the variableMaxPwrisimmediatelysetto

Page 605: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the value of the currentpower. However, if thecurrent power is less thanMaxPwr,thentheMaxPwr isallowed to decay to 0.995 ofitspreviousvalue.The dominant cycle is

extracted from the spectralestimate in the next block ofcodeusingacenter-of-gravity(CG) algorithm. The CGalgorithm measures theaverage center of two-

Page 606: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

dimensional objects. It iscomputedby summing theYvalues and independentlysumming the X * Y values.Dividing the latter by theformer yields the averageposition along the X axiswherealltheYvaluesreside.In the case of computing thedominantcycle, theYvaluesare power and the X valuesare the periods. Thus, thealgorithm computes theaverage period at which the

Page 607: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

powers are centered. That isthe dominant cycle. Thedominantcycleisavaluethatvaries with time and can beused to automatically tuneother indicators such as theband-pass filter, commoditychannel index (CCI), relativestrength index (RSI),Stochastic,andsoon.The spectrum values vary

between 0 and 1 after beingnormalized.These values are

Page 608: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

convertedtocolors.Whenthespectrum is greater than 0.5the colors combine red andgreen, with yellow being theresultwhenspectrum=1andredbeing theresultwhen thespectrum = 0.5. When thespectrum is less than0.5, thered saturation is decreased,with the result that the coloris black when spectrum = 0.Since themaximum value ofthe spectrum is unity, I haveincludedanoptionalblockof

Page 609: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

code (which has beencommented out by the curlybrackets) that providesadditional visual resolutionby raising the spectralcomponents to a higherpower. The selection of thepowertobeusedisarbitrary.

CodeListing9-1.EasyLanguage

CodetoComputea

Page 610: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

DFTSpectralEstimate

{DiscreteFourierTransform(DFT)©2013JohnF.Ehlers}

Inputs:SpectralDilationCompensation(true);

Vars:alpha1(0),HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),Period(0),N(0),M(0),MaxPwr(0),Comp(0),

Page 611: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Sp(0),Spx(0),DominantCycle(0),Color1(0),Color2(0);

//ArraysaresizedtohaveamaximumPeriodof48bars

Arrays:CosinePart[48](0),SinePart[48](0),Pwr[48](0);

//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48bars

alpha1=(Cosine(.707*360/48)+Sine(.707*360/48)-1)/Cosine(.707*360/48);

HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*(1-alpha1)*HP[2];

//SmoothwithaSuperSmootherFilter

a1=expvalue(-1.414*3.14159/10);

b1=2*a1*Cosine(1.414*180/10);

c2=b1;

c3=-a1*a1;

c1=1-c2-c3;Filt = c1*

Page 612: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

//ThisistheDFT

ForPeriod=10to48BeginComp=Period;IfSpectralDilationCompensation=FalseThenComp=1;CosinePart[Period]=0;SinePart[Period]=0;//FindCosineandSinecorrelatedcomponents,compensatedforfractaldilationForN=0to47BeginCosinePart[Period]=CosinePart[Period]+Filt[N]*Cosine(360*N/Period)/Comp;SinePart[Period]=SinePart[Period]+Filt[N]*Sine(360*N/Period)/Comp;End;Pwr[Period]=CosinePart[Period]*CosinePart[Period]+SinePart[Period]*SinePart[Period];End;

//FindMaximumPowerLevelforNormalization

MaxPwr=.995*MaxPwr[1];

ForPeriod=8to48BeginIfPwr[Period]>MaxPwrThenMaxPwr=Pwr[Period];End;

//NormalizePowerLevelsandConverttoDecibels

ForPeriod=10to48BeginIFMaxPwr>0ThenPwr[Period]=Pwr[Period]/MaxPwr;End;

//ComputethedominantcycleusingtheCGofthespectrum

Spx=0;

Page 613: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Sp=0;

ForPeriod=10to48BeginIfPwr[Period]>=.5ThenBeginSpx=Spx+Period*Pwr[Period];Sp=Sp+Pwr[Period];End;

End;

IfSp<>0ThenDominantCycle=Spx/Sp;Plot2(DominantCycle,“DC”,RGB(0,0,255),0,2);

{

//IncreaseDisplayResolutionbyraisingtheNormPwrtoahighermathematicalpower(optional)

ForPeriod=10to48BeginPwr[Period]=Power(Pwr[Period],3);

End;}

//PlottheSpectrumasaHeatmap

ForPeriod=10to48Begin//ConvertPowertoRGBColorforDisplayIfPwr[Period]>=.5ThenBeginColor1=255; Color2 = 255*(2*Pwr[Period]-1);End;IfPwr[Period]<.5ThenBeginColor1=255*2*Pwr[Period];

Page 614: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Color2=0;End;IfPeriod=10ThenPlot10(10,“S10”,RGB(Color1,Color2,0),0,4);IfPeriod=11ThenPlot11(11,“S11”,RGB(Color1,Color2,0),0,4);IfPeriod=12ThenPlot12(12,“S12”,RGB(Color1,Color2,0),0,4);IfPeriod=13ThenPlot13(13,“S13”,RGB(Color1,Color2,0),0,4);IfPeriod=14ThenPlot14(14,“S14”,RGB(Color1,Color2,0),0,4);IfPeriod=15ThenPlot15(15,“S15”,RGB(Color1,Color2,0),0,4);IfPeriod=16ThenPlot16(16,“S16”,RGB(Color1,Color2,0),0,4);IfPeriod=17ThenPlot17(17,“S17”,RGB(Color1,Color2,0),0,4);IfPeriod=18ThenPlot18(18,“S18”,RGB(Color1,Color2,0),0,4);IfPeriod=19ThenPlot19(19,“S19”,RGB(Color1,Color2,0),0,4);IfPeriod=20ThenPlot20(20,“S20”,RGB(Color1,Color2,0),0,4);IfPeriod=21ThenPlot21(21,“S21”,RGB(Color1,Color2,0),0,4);IfPeriod=22ThenPlot22(22,“S22”,RGB(Color1,Color2,0),0,4);IfPeriod=23ThenPlot23(23,“S23”,RGB(Color1,Color2,0),0,4);IfPeriod=24ThenPlot24(24,“S24”,RGB(Color1,Color2,0),0,4);IfPeriod=25ThenPlot25(25,“S25”,RGB(Color1,Color2,0),0,4);IfPeriod=26ThenPlot26(26,“S26”,RGB(Color1,Color2,0),0,4);IfPeriod=27ThenPlot27(27,“S27”,RGB(Color1,Color2,0),0,4);IfPeriod=28ThenPlot28(28,“S28”,RGB(Color1,Color2,0),0,4);IfPeriod=29ThenPlot29(29,“S29”,RGB(Color1,Color2,0),0,4);IfPeriod=30ThenPlot30(30,“S30”,RGB(Color1,Color2,0),0,4);IfPeriod=31ThenPlot31(31,“S31”,RGB(Color1,Color2,0),0,4);IfPeriod=32ThenPlot32(32,“S32”,RGB(Color1,Color2,0),0,4);IfPeriod=33ThenPlot33(33,“S33”,RGB(Color1,Color2,0),0,4);IfPeriod=34ThenPlot34(34,“S34”,RGB(Color1,Color2,0),0,4);IfPeriod=35ThenPlot35(35,“S35”,RGB(Color1,Color2,0),0,4);IfPeriod=36ThenPlot36(36,“S36”,RGB(Color1,Color2,0),0,4);

Page 615: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

IfPeriod=37ThenPlot37(37,“S37”,RGB(Color1,Color2,0),0,4);IfPeriod=38ThenPlot38(38,“S38”,RGB(Color1,Color2,0),0,4);IfPeriod=39ThenPlot39(39,“S39”,RGB(Color1,Color2,0),0,4);IfPeriod=40ThenPlot40(40,“S40”,RGB(Color1,Color2,0),0,4);IfPeriod=41ThenPlot41(41,“S41”,RGB(Color1,Color2,0),0,4);IfPeriod=42ThenPlot42(42,“S42”,RGB(Color1,Color2,0),0,4);IfPeriod=43ThenPlot43(43,“S43”,RGB(Color1,Color2,0),0,4);IfPeriod=44ThenPlot44(44,“S44”,RGB(Color1,Color2,0),0,4);IfPeriod=45ThenPlot45(45,“S45”,RGB(Color1,Color2,0),0,4);IfPeriod=46ThenPlot46(46,“S46”,RGB(Color1,Color2,0),0,4);IfPeriod=47ThenPlot47(47,“S47”,RGB(Color1,Color2,0),0,4);IfPeriod=48ThenPlot48(48,“S48”,RGB(Color1,Color2,0),0,4);

End;

AsamplecomputationandspectraldisplayoftheDFTisshown in Figure 9.1.Harmonic components areclearly present (at periods of

Page 616: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

half and one-third thestronger dominant cycleperiod). Nonetheless, thespectral estimate comparesfavorably with the preferredautocorrelation periodogram,as shown in Figure 9.2. Thisresult is remarkableconsidering all theconcessions made to puretheory.

Figure9.1AnExampleofaDFTSpectralEstimate

Page 617: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure9.2DFTSpectral

Page 618: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

EstimateComparesFavorablywithanAutocorrelationPeriodogram

Page 619: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 620: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Key PointstoRemember

1. The practicalcomputation of a DFTfor market datadisregards theoreticalrequirements.2.TheDFTfortradersiscomputed in terms ofcycle period rather thanfrequency for ease of

Page 621: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

interpretation.3. The DFT calculationshould includecompensation forSpectralDilation.4. The DFT results ascomputed in Figure 9.1compare favorably withthe results of theautocorrelationperiodogram.

Page 622: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CHAPTER10

CombFilterSpectralEstimates

“Youcantakethattothe

Page 623: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

bank,” said Tomrepeatedly.

Band-pass filters weredescribed in Chapter 5. Theconcept of this chapter is toarrange a bank of thesefilters, each tuned to adifferent cycle period andoverlapping,andapplyingthesame data to the input ofthese filters. The band-passfilterscanbepicturedasteethin a comb, only the teeth

Page 624: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

overlap. With this combstructure the relativeamplitudes of the signals attheoutputofthefilterswouldconstitute an estimate of thespectral content of the inputdata. The measurementresolution and,correspondingly,thetransientresponse of themeasurementisbycontrolofthebandwidthof each filter. It is just thateasy. This is the mostconceptuallypureandeasyto

Page 625: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

understand of all the spectralestimateapproaches.

Page 626: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ SpectralDilationBefore beginning, it isimperative to again addressthe issueofSpectralDilationof market data cycleamplitudes. This is acharacteristic intrinsic to thenature of market data.Compensation for SpectralDilation is mandatory when

Page 627: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

making cycle periodmeasurements over arelatively large range and istherefore included in thisspectral estimation approach.Spectral Dilation of marketcycles was discussed morefullyinChapter7.

Page 628: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ComputingaComb FilterSpectralEstimateSince the concept ofcomputingaspectralestimatebased measuring the outputpowers of a bank ofoverlapping band-pass filters

Page 629: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

issostraightforward,thebestwayofdescribingtheprocessis with reference to theEasyLanguage code in CodeListing10-1.

CodeListing10-1.EasyLanguage

CodetoComputeaCombFilter

SpectralEstimate{

Page 630: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CombBandPassSpectrum©2013JohnF.Ehlers}

Vars:alpha1(0),HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),Comp(0),beta1(0),gamma1(0),delta1(0),N(0),M(0),Period(0),Sp(0),Spx(0),MaxPwr(0),DominantCycle(0),Color1(0),Color2(0),Color3(0);

Arrays:

Page 631: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

BP[48,48](0),Pwr[48](0);

//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48bars

alpha1=(Cosine(.707*360/48)+Sine(.707*360/48)-1)/Cosine(.707*360/48);

HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*(1-alpha1)*HP[2];

//SmoothwithaSuperSmootherFilterfromequation3

a1=expvalue(-1.414*3.14159/10);

b1=2*a1*Cosine(1.414*180/10);

c2=b1;

c3=-a1*a1;

c1=1-c2-c3;Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

ForN=10to48Begin

Page 632: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ForM=48DownTo2BeginBP[N,M]=BP[N,M-1];End;End;

IfCurrentBar>12ThenBeginForN=10to48BeginComp=N;IfSpectralDilationCompensation=FalseThenComp=1;beta1=Cosine(360/N);gamma1=1/Cosine(360*Bandwidth/N);alpha1=gamma1-SquareRoot(gamma1*gamma1-1);BP[N,1]=.5*(1-alpha1)*(Filt-Filt[2])+beta1*(1+alpha1)*BP[N,2]-alpha1*BP[N,3];Pwr[N]=0;ForM=1toNBeginPwr[N]=Pwr[N]+(BP[N,M]/Comp)*(BP[N,M]/Comp);End;End;End;

//FindMaximumPowerLevelforNormalization

MaxPwr=.995*MaxPwr;

ForPeriod=ShortestPeriodto48BeginIfPwr[Period]>MaxPwrThenMaxPwr=Pwr[Period];

Page 633: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

End;

//NormalizePowerLevelsandConverttoDecibels

ForPeriod=10to48BeginIfMaxPwr>0ThenPwr[Period]=Pwr[Period]/MaxPwr;End;

//ComputethedominantcycleusingtheCGofthespectrum

Spx=0;

Sp=0;

ForPeriod=ShortestPeriodtoLongestPeriodBeginIfPwr[Period]>=.5ThenBeginSpx=Spx+Period*Pwr[Period];Sp=Sp+Pwr[Period];End;

End;

IfSp<>0ThenDominantCycle=Spx/Sp;Plot2(DominantCycle,“DC”,RGB(0,0,255),0,2);

{

//IncreaseDisplayResolutionbyraisingthePwrtoahighermathematicalpower

Page 634: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ForPeriod=10to48BeginPwr[Period]=Power(Pwr[Period],3);

End;}

ForN=10to48BeginColor3=0;IfPwr[N]>.5ThenBeginColor1=255; Color2 = 255*(2*Pwr[N]-1);EndElseBeginColor1=2*255*Pwr[N];Color2=0;End;IfN=10ThenPlot10(N,“S10”,RGB(Color1,Color2,Color3),0,5);IfN=11ThenPlot11(N,“S11”,RGB(Color1,Color2,Color3),0,5);IfN=12ThenPlot12(N,“S12”,RGB(Color1,Color2,Color3),0,5);IfN=13ThenPlot13(N,“S13”,RGB(Color1,Color2,Color3),0,5);IfN=14ThenPlot14(N,“S14”,RGB(Color1,Color2,Color3),0,5);IfN=15ThenPlot15(N,“S15”,RGB(Color1,Color2,Color3),0,5);IfN=16ThenPlot16(N,“S16”,RGB(Color1,Color2,Color3),0,5);IfN=17ThenPlot17(N,“S17”,RGB(Color1,Color2,Color3),0,5);IfN=18ThenPlot18(N,“S18”,RGB(Color1,Color2,Color3),0,5);IfN=19ThenPlot19(N,“S19”,RGB(Color1,Color2,Color3),0,5);IfN=20ThenPlot20(N,“S20”,RGB(Color1,Color2,Color3),0,5);IfN=21ThenPlot21(N,“S21”,RGB(Color1,Color2,Color3),0,5);

Page 635: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

IfN=22ThenPlot22(N,“S22”,RGB(Color1,Color2,Color3),0,5);IfN=23ThenPlot23(N,“S23”,RGB(Color1,Color2,Color3),0,5);IfN=24ThenPlot24(N,“S24”,RGB(Color1,Color2,Color3),0,5);IfN=25ThenPlot25(N,“S25”,RGB(Color1,Color2,Color3),0,5);IfN=26ThenPlot26(N,“S26”,RGB(Color1,Color2,Color3),0,5);IfN=27ThenPlot27(N,“S27”,RGB(Color1,Color2,Color3),0,5);IfN=28ThenPlot28(N,“S28”,RGB(Color1,Color2,Color3),0,5);IfN=29ThenPlot29(N,“S29”,RGB(Color1,Color2,Color3),0,5);IfN=30ThenPlot30(N,“S30”,RGB(Color1,Color2,Color3),0,5);IfN=31ThenPlot31(N,“S31”,RGB(Color1,Color2,Color3),0,5);IfN=32ThenPlot32(N,“S32”,RGB(Color1,Color2,Color3),0,5);IfN=33ThenPlot33(N,“S33”,RGB(Color1,Color2,Color3),0,5);IfN=34ThenPlot34(N,“S34”,RGB(Color1,Color2,Color3),0,5);IfN=35ThenPlot35(N,“S35”,RGB(Color1,Color2,Color3),0,5);IfN=36ThenPlot36(N,“S36”,RGB(Color1,Color2,Color3),0,5);IfN=37ThenPlot37(N,“S37”,RGB(Color1,Color2,Color3),0,5);IfN=38ThenPlot38(N,“S38”,RGB(Color1,Color2,Color3),0,5);IfN=39ThenPlot39(N,“S39”,RGB(Color1,Color2,Color3),0,5);IfN=40ThenPlot40(N,“S40”,RGB(Color1,Color2,Color3),0,5);IfN=41ThenPlot41(N,“S41”,RGB(Color1,Color2,Color3),0,5);IfN=42ThenPlot42(N,“S42”,RGB(Color1,Color2,Color3),0,5);IfN=43ThenPlot43(N,“S43”,RGB(Color1,Color2,Color3),0,5);IfN=44ThenPlot44(N,“S44”,RGB(Color1,Color2,Color3),0,5);IfN=45ThenPlot45(N,“S45”,RGB(Color1,Color2,Color3),0,5);IfN=46ThenPlot46(N,“S46”,RGB(Color1,Color2,Color3),0,5);IfN=47ThenPlot47(N,“S47”,RGB(Color1,Color2,Color3),0,5);IfN=48ThenPlot48(N,“S48”,RGB(Color1,Color2,Color3),0,5);

End;

Page 636: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The arrays and plottingroutines have been sized toaccommodate the range ofband-pass filter periods from10 to 48 bars.After the datahave been preconditioned bythe combination of the two-pole high-pass andSuperSmoother filters toallow only the cycliccomponents of interest to beanalyzed, the band-passfilters for each of thechannels is filled with

Page 637: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

historical values to allowcomputation and averaginglaterinthecode.Since the entire

EasyLanguage code isimplemented from top tobottomwith eachnewbarofdata, the next block of codeselects each band-passchannel and computes thecurrent filtered value at theoutput of each channel. Thewave amplitude of each

Page 638: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

channel is divided by itscenter period to compensatefor the AGC frequency roll-off that comes later, squaredto compute the power outputof the channel, and averagedoverthelengthofthechannelperiod.Inthenextblockofcodea

fast attack−slow decayautomaticgaincontrol(AGC)is used to normalize thespectral components and to

Page 639: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

minimize the variance of thespectralpowerovertime.TheAGCconceptwas introducedinChapter5;however,inthiscase, we are scaling on thebasisofpowerrather thanonwave amplitude. Therefore,thecorrectdecayfactoristhesquare root of 0.991, or0.995.If thecurrentpowerisgreater than the variableMaxPwr, then the variableMaxPwrisimmediatelysettothe value of the current

Page 640: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

power. However, if thecurrent power is less thanMaxPwr,thentheMaxPwr isallowed to decay to 0.995 ofitspreviousvalue.Ofcourse,anyactioninthe

timedomainhas implicationsin the frequency domain. Inthiscase,thefastattack−slowdecayAGChas the effect ofan exponential decay in thetimedomain. Itseffect in thefrequencydomainisthesame

Page 641: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

as an exponential movingaverage (EMA). Therefore,the frequency roll-off of thisde facto filter must becompensated for during thespectrum computation. TheAGC frequency responseslope is approximately 6 dBper octave across thefrequency band of interest,and therefore dividing eachchannel band-pass waveamplitude by the respectivechannel period provided a 6

Page 642: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

dB per octave compensationfor the AGC action. Forreference, an octave is a 2:1frequency or period ratio. Afactor of 2 in the waveamplitude is a factor of 4 inthe power ratio, and a factorof4 inpower corresponds to6dB.The dominant cycle is

extracted from the spectralestimate in the next block ofcodeusingacenterofgravity

Page 643: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

(CG) algorithm. The CGalgorithm measures theaverage center of two-dimensional objects. It iscomputedby summing theYvalues and independentlysumming the X * Y values.Dividing the latter by theformer yields the averageposition along the X axiswherealltheYvaluesreside.In the case of computing thedominant cycle, theYvaluesare power and the X values

Page 644: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

are the periods. Thus, thealgorithm computes theaverage period at which thepowers are centered. That isthe dominant cycle. Thedominantcycleisavaluethatvaries with time and can beused to automatically tuneother indicators such as theband-pass filter, commoditychannel index (CCI), relativestrength index (RSI),Stochastic,andsoon.

Page 645: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The spectrum values varybetween 0 and 1 after beingnormalized.These values areconvertedtocolors.Whenthespectrum is greater than 0.5,the colors combine red andgreen, with yellow being theresultwhenspectrum=1,andredbeing theresultwhen thespectrum = 0.5. When thespectrum is less than0.5, thered saturation is decreased,with the result that the coloris black when spectrum = 0.

Page 646: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Since themaximum value ofthe spectrum is unity, I haveincludedanoptionalblockofcode (which has beencommented out by the curlybrackets) that providesadditional visual resolutionby raising the spectralcomponents to a higherpower. The selection of thepowertobeusedisarbitrary.Anexampleofthespectral

estimate computed by the

Page 647: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

array of band-pass filtersusing a pass-band value of0.3 is shown in Figure 10.1.This estimate is comparedwith the autocorrelationperiodogram and DFTmethods in Figure 10.2. Thethree techniques provide aconsistent estimate of thespectral content of the data.In my opinion, theautocorrelation periodogramis the superior approachbecause themeasurementhas

Page 648: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

less latency, has a widerrange of amplitude swings,does not require historicalaveraging, and does notrequire Spectrum Dilationcompensation. For thesereasons I will be using theautocorrelation periodogramapproach to compute thedominant cycle in theremainderofthisbook.

Figure10.1CombFilterSpectralEstimateforDG

Page 649: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure10.2Comparisonof

Page 650: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

theCombFilter,DFT,andAutocorrelationPeriodogramSpectralEstimatesforDG

Page 651: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 652: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Key PointstoRemember

1. Market data spectracan be estimated byapplying the data to abank of band-passfilters, each tuned to adifferent center periodwith overlapping passbands. The relativeoutput power of the

Page 653: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

filters provides anestimate of the cycliccontentofthedata.2. Compensation forSpectral Dilation shouldbe included in thecomputationsforacombfilter estimate of thespectrum.3. The autocorrelationperiodogram is thepreferred method ofobtaining spectral

Page 654: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

estimatesofmarketdata.

Page 655: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CHAPTER11

AdaptiveFilters

“We should adjust theindicators,” said Tom

Page 656: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

rigidly.

Adaptive filters can haveseveral different meanings.For example, PerryKaufman's adaptive movingaverage (KAMA)1 andTushar Chande's variableindex dynamic average(VIDYA)2 adapt to changesin volatility. By definition,these filters are reactive toprice changes, and therefore

Page 657: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

theyclosethebarndoorafterthe horse is gone. Theadaptive filters discussed inthis chapter are the familiarStochastic, relative strengthindex (RSI), commoditychannel index (CCI), andband-pass filter. The keyparameter in eachcase is thelookback period used tocalculate the indicator. Thislookbackperiodiscommonlyafixedvalue.However,sincethe measured cycle period is

Page 658: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

changing,aswehaveseeninprevious chapters, it makessense to adapt theseindicators to the measuredcycle period. When tradablemarket cycles are observed,theytendtopersistforashortwhile. Therefore, by tuningthe indicators to themeasurecycle period they areoptimized for currentconditionsandcanevenhavepredictivecharacteristics.

Page 659: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Thedominant cycleperiodis measured using theautocorrelation periodogramalgorithm. That dominantcycle dynamically sets thelookback period for theindicators. I employmy ownstreamlined computation forthe indicators that providesmoother and easier tointerpret outputs thantraditional methods. Further,theindicatorcodeshavebeenmodified to remove the

Page 660: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

effects of spectral dilation.Thisbasicallycreatesawholenewsetofindicatorsforyourtradingarsenal.

Page 661: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ AdaptiveRelativeStrengthIndex(RSI)Welles Wilder had justintroduced the RSI3 when Ibegan trading. I asked mybrokerwhy14dayswasusedin the calculation. His

Page 662: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

response was something like“because Wilder said so.”You have no idea howunsatisfying that responsewas to an engineer, and thatstarted me on my decades-long quest to find theoptimum indicator settings. Ithink I can now describethoseoptimumsettings.Wilder's original RSI was

definedby

Page 663: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

where

“ClosesUP” meant that iftoday'sclosewashigher thanyesterday's close, we wouldadd the difference in closingprices to the average.Similarly, “closes DOWN”meant that if today's closewas lower than yesterday's,we would add the positive

Page 664: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

differenceinclosingpricestotheaverage.Wecansimplifythe RSI equation if wesubstitute RSI = CU / CD.Then,

Increasing generality, CUcan mean the sum of closesupoveranyinterval,andCD

Page 665: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

can mean the sum of closesdown over the same period.Additionally, the factor of100 is recognized asproviding a simple scaling.So,RSIisjusttheratioofthesum of closes up to the sumof the absolute value of allthedifferentialclosingprices.

Thequestionthenbecomeswhat is thebest lengthtouse

Page 666: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

fortheRSIsummation.Ifweuseanextremelylonglength,then the closes up will beapproximately half of theabsolute value of all theclosing price differentials. Inthis case, the RSI wouldhover near 0.5 andwould bebasicallyworthless.However,if the length used forsummationisveryshort,thenthe RSI would be stuck at 1for extended periods inuptrends andwould be stuck

Page 667: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

at 0 for extended periods indowntrends. In a perfectworldwherepricesswingasasine wave having the periodof the dominant cycle, theRSI would just touch thevalueof1iftheupswinghalfofthedominantcycleisusedfor thesummation.Similarly,theRSIwould just touch thevalue of 0 if the downswinghalf of the dominant cycle isused for the summation.Therefore,togettheoptimum

Page 668: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

swing of the RSI indicator,the best adaptive summationlength to use is half themeasureddominantcycle.The adaptive RSI starts

with the computation of thedominant cycle using theautocorrelation periodogramapproach. Rather thandescribing the computations,the reader is referred to thedescription in Chapter 8.Code Listing 11-1 contains

Page 669: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the EasyLanguage code forthe adaptive RSI, and theidentification of the RSIindicator itself following thedominant cycle calculation isnoted by the comment neartheend.Sincetheobjectiveisto use only those frequencycomponents passed by theroofingfilter,thevariableFiltis used as a data input ratherthan closing prices. Ratherthanindependentlytakingtheaverages of the numerator

Page 670: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

and denominator, I chose toperform smoothing on theratio using theSuperSmoother filterdescribed in Chapter 3. Thecoefficients for theSuperSmoother filters havepreviously been computed inthe dominant cyclemeasurementpartofthecode.I have included referencelinesatthe30percentand70percent levels, but these caneasily be adjusted to 20

Page 671: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

percent/80 percent orwhatever else serves thepurpose.

CodeListing11-1.EasyLanguageCodefortheAdaptiveRSI

{AdaptiveRSI(c)2013JohnF.Ehlers}Vars:AvgLength(3),M(0),N(0),

Page 672: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

X(0),Y(0),alpha1(0),HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),Lag(0),count(0),Sx(0),Sy(0),Sxx(0),Syy(0),Sxy(0),Period(0),Sp(0),Spx(0),MaxPwr(0),DominantCycle(0),Color1(0),Color2(0),Color3(0);Arrays:Corr[48](0),CosinePart[48](0),SinePart[48](0),

Page 673: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

SqSum[48](0),R[48,2](0),Pwr[48](0);//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48barsalpha1=(Cosine(.707*360/48)+Sine(.707*360/48)-1)/Cosine(.707*360/48);HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*(1-alpha1)*HP[2];//SmoothwithaSuperSmootherFilterfromequation3a1=expvalue(-1.414*3.14159/10);b1=2*a1*Cosine(1.414*180/10);c2=b1;c3=-a1*a1;c1=1-c2-c3;Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];//PearsoncorrelationforeachvalueoflagForLag=0to48Begin//SettheaveraginglengthasMM=AvgLength;IfAvgLength=0ThenM=Lag;Sx=0;Sy=0;Sxx=0;Syy=0;Sxy=0;

Page 674: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Forcount=0toM-1BeginX=Filt[count];Y=Filt[Lag+count];Sx=Sx+X;Sy=Sy+Y;Sxx=Sxx+X*X;Sxy=Sxy+X*Y;Syy=Syy+Y*Y;End; If (M*Sxx - Sx*Sx)*(M*Syy-Sy*Sy)>0ThenCorr[Lag]=(M*Sxy-Sx*Sy)/SquareRoot((M*Sxx-Sx*Sx)*(M*Syy-Sy*Sy));End;ForPeriod=10to48BeginCosinePart[Period]=0;SinePart[Period]=0;ForN=3to48BeginCosinePart[Period]=CosinePart[Period]+Corr[N]*Cosine(360*N/Period);SinePart[Period]=SinePart[Period]+Corr[N]*Sine(360*N/Period);End;SqSum[Period]=CosinePart[Period]*CosinePart[Period]+SinePart[Period]*SinePart[Period];End;ForPeriod=10to48BeginR[Period,2]=R[Period,1];R[Period,1]=.2*SqSum[Period]*SqSum[Period]+.8*R[Period,2];End;//FindMaximumPowerLevelforNormalizationMaxPwr=.991*MaxPwr;ForPeriod=10to48Begin

Page 675: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

IfR[Period,1]>MaxPwrThenMaxPwr=R[Period,1];End;ForPeriod=3to48BeginPwr[Period]=R[Period,1]/MaxPwr;End;//ComputethedominantcycleusingtheCGofthespectrumSpx=0;Sp=0;ForPeriod=10to48BeginIfPwr[Period]>=.5ThenBeginSpx=Spx+Period*Pwr[Period];Sp=Sp+Pwr[Period];End;End;IfSp<>0ThenDominantCycle=Spx/Sp;IfDominantCycle<10ThenDominantCycle=10;IfDominantCycle>48ThenDominantCycle=48;//AdaptiveRSIstartshere,usinghalfthemeasureddominantcyclefortuningVars:ClosesUp(0),ClosesDn(0),Denom(0),MyRSI(0);ClosesUp=0;ClosesDn=0;Forcount=0toIntPortion(DominantCycle/2-1)BeginIfFilt[count]>Filt[count+1]ThenClosesUp=ClosesUp+(Filt[count]-Filt[count+1]);IfFilt[count]<Filt[count+1]ThenClosesDn=ClosesDn+(Filt[count+1]-Filt[count]);End;

Page 676: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Denom=ClosesUp+ClosesDn;IfDenom<>0andDenom[1]<>0ThenMyRSI=c1*(ClosesUp/Denom+ClosesUp[1]/Denom[1])/2+c2*MyRSI[1]+c3*MyRSI[2];Plot1(MyRSI);Plot2(.7);Plot6(.3);

TheadaptiveRSIhasbeenapplied to Dollar General(symbol DG) over roughlythe last year in Figure 11.1.Note that the indicatorreaches zero or one onlywhen the prices have had acyclic swing over half theperiodofthedominantcycle.

Page 677: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

These events happenrelatively rarely, and showthat the indicator is properlytuned.

Figure11.1AdaptiveRSIIsProperlyTunedtoHalftheDominantCyclePeriod

Page 678: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 679: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ AdaptiveStochasticIndicatorThe basic idea of thestochastic indicator is that itmeasures the current closingprice relative to the lowestclose over the observationrange, and normalize thatrelative price to the range

Page 680: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

betweenthehighestcloseandthe lowest close over theobservation range. Sincefinding the highest close andlowest close over thedominant cycle period isassured only by searchingover the entire dominantcycle period, the entiredominantcycleperiodisusedfor the observation range inthecalculations.The adaptive stochastic

Page 681: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

indicator starts with thecomputation of the dominantcycle using theautocorrelation periodogramapproach. Rather thandescribing the computations,the reader is referred to thedescription in Chapter 8.Code Listing 11-2 containsthe EasyLanguage code forthe adaptive stochasticindicator, and theidentification of the indicatoritself following the dominant

Page 682: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

cycle calculation is noted bythe comment near the end.Since the objective is to useonly those frequencycomponents passed by theroofingfilter,thevariableFiltis used as a data input ratherthanclosingprices.

CodeListing11-2.EasyLanguageCodeforthe

Page 683: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

AdaptiveStochasticIndicator

{AdaptiveStochastic(c)2013JohnF.Ehlers}Vars:AvgLength(3),M(0),N(0),X(0),Y(0),alpha1(0),HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),Lag(0),

Page 684: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

count(0),Sx(0),Sy(0),Sxx(0),Syy(0),Sxy(0),Period(0),Sp(0),Spx(0),MaxPwr(0),DominantCycle(0);Arrays:Corr[48](0),CosinePart[48](0),SinePart[48](0),SqSum[48](0),R[48,2](0),Pwr[48](0);//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48barsalpha1=(Cosine(.707*360/48)+Sine(.707*360/48)-1)/Cosine(.707*360/48);HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*(1-alpha1)*HP[2];//SmoothwithaSuperSmootherFilterfromequation3a1=expvalue(-1.414*3.14159/10);b1=2*a1*Cosine(1.414*180/10);

Page 685: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

c2=b1;c3=-a1*a1;c1=1-c2-c3;Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];//PearsoncorrelationforeachvalueoflagForLag=0to48Begin//SettheaveraginglengthasMM=AvgLength;IfAvgLength=0ThenM=Lag;Sx=0;Sy=0;Sxx=0;Syy=0;Sxy=0;Forcount=0toM-1BeginX=Filt[count];Y=Filt[Lag+count];Sx=Sx+X;Sy=Sy+Y;Sxx=Sxx+X*X;Sxy=Sxy+X*Y;Syy=Syy+Y*Y;End; If (M*Sxx - Sx*Sx)*(M*Syy-Sy*Sy)>0ThenCorr[Lag]=(M*Sxy-Sx*Sy)/SquareRoot((M*Sxx-Sx*Sx)*(M*Syy-Sy*Sy));End;ForPeriod=10to48Begin

Page 686: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CosinePart[Period]=0;SinePart[Period]=0;ForN=3to48BeginCosinePart[Period]=CosinePart[Period]+Corr[N]*Cosine(360*N/Period);SinePart[Period]=SinePart[Period]+Corr[N]*Sine(360*N/Period);End;SqSum[Period]=CosinePart[Period]*CosinePart[Period]+SinePart[Period]*SinePart[Period];End;ForPeriod=10to48BeginR[Period,2]=R[Period,1];R[Period,1]=.2*SqSum[Period]*SqSum[Period]+.8*R[Period,2];End;//FindMaximumPowerLevelforNormalizationMaxPwr=.995*MaxPwr;ForPeriod=10to48BeginIfR[Period,1]>MaxPwrThenMaxPwr=R[Period,1];End;ForPeriod=3to48BeginPwr[Period]=R[Period,1]/MaxPwr;End;//ComputethedominantcycleusingtheCGofthespectrumSpx=0;Sp=0;ForPeriod=10to48BeginIfPwr[Period]>=.5ThenBeginSpx=Spx+Period*Pwr[Period];Sp=Sp+Pwr[Period];End;End;

Page 687: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

IfSp<>0ThenDominantCycle=Spx/Sp;IfDominantCycle<10ThenDominantCycle=10;IfDominantCycle>48ThenDominantCycle=48;//StochasticComputationstartshereVars:HighestC(0),LowestC(0),Stoc(0),SmoothNum(0),SmoothDenom(0),AdaptiveStochastic(0);HighestC=Filt;LowestC=Filt;Forcount=0toDominantCycle-1BeginIfFilt[count]>HighestCthenHighestC=Filt[count];IfFilt[count]<LowestCthenLowestC=Filt[count];End;Stoc=(Filt-LowestC)/(HighestC-LowestC);AdaptiveStochastic = c1*(Stoc+Stoc[1])/2+c2*AdaptiveStochastic[1]+c3*AdaptiveStochastic[2];Plot1(AdaptiveStochastic);Plot2(.7);Plot6(.3);

Thefirststep is to identify

Page 688: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the highest “close” and thelowest “close” over theperiod of the currentdominant cycle.The variableStoc iscomputedas the ratioofthecurrentvalueofFilt tothe price range and is theunfiltered value of theadaptive stochastic.TheStocvariable is filtered using theSuperSmoother filter firstdescribe inChapter3.Ratherthanindependentlytakingtheaverages of the numerator

Page 689: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

and denominator, I chose toperform smoothing on theratio Stoc using theSuperSmoother filterdescribed in Chapter 3. Thecoefficients for theSuperSmoother filters havepreviously been computed inthe dominant cyclemeasurementpartofthecode.I have included referencelinesatthe30percentand70percent levels, but these caneasily be adjusted to 20

Page 690: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

percent/80 percent orwhatever else serves thepurpose.The adaptive Stochastic

has been applied to DollarGeneral (symbol DG) overroughlythelastyearinFigure11.2. An eyeball scancomparing the prices and theadaptivestochasticshowsthatthis indicator accuratelyportrays the relativedetrended prices over the

Page 691: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

length of the dominant cycleperiod, and has manycharacteristics in commonwiththeadaptiveRSI.

Figure11.2AdaptiveStochasticAccuratelyDisplaystheRelativeDetrendedPricesovertheChannelLengthoftheDominantCyclePeriod

Page 692: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 693: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ AdaptiveCCI(CommodityChannelIndex)The CCI indicator was firstdescribed by DonaldLambert4 as a means of

Page 694: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

statistically estimating wherethe current prices lie withinthe length of a channel. Hebasically compares thecurrent price relative to amoving average of pricesoverthelengthofthechannelto the standard deviation ofprices over the same length.A standard deviation is justthe square root of theaveraged squared differenceof the prices from theirmoving averages. As a

Page 695: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

shorthandwayof thinkingofit,thebasicideaoftheCCIistaking the ratio of the“instantaneous deviation” tothe standard deviation.Lambertalsodividestheratioby 0.015, which is the sameas multiplying the ratio by66.7. This scaling factor sets+100 and −100 asapproximations to the plusand minus one standarddeviation if the data had aGaussian probability

Page 696: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

distribution. That is not agood assumption, which canbe proven heuristically bymeasuring the dataprobability distributions overalotofdata.Thetimelengthtobeused

for the channel in thecalculations is widely variedin the literature. In all cases,thelengthisratherarbitrarilyestablishedtofittheindicatorto some preconceived event.

Page 697: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

It seems tome that it wouldbe better to use one fullperiod of the dominant cycleas the length of data to beused.TheadaptiveCCIindicator

startswiththecomputationofthe dominant cycle using theautocorrelation periodogramapproach. Rather thandescribing the computations,the reader is referred to thedescription in Chapter 8.

Page 698: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Code Listing 11-3 containsthe EasyLanguage code forthe adaptive CCI indicator,and the identification of theindicatoritselfisnotedbythecomment near the endfollowing thedominant cyclecalculation. Since theobjective is touseonly thosefrequencycomponentspassedby the roofing filter, thevariableFilt isusedasadatainput rather than the averageofthehigh,low,andcloseas

Page 699: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

wasdonebyLambert.

CodeListing11-3.EasyLanguageCodefortheAdaptiveCCI

{AdaptiveCCI(c)2013JohnF.Ehlers}Vars:AvgLength(3),M(0),N(0),X(0),Y(0),alpha1(0),HP(0),

Page 700: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),Lag(0),count(0),Sx(0),Sy(0),Sxx(0),Syy(0),Sxy(0),Period(0),Sp(0),Spx(0),MaxPwr(0),DominantCycle(0);Arrays:Corr[48](0),CosinePart[48](0),SinePart[48](0),SqSum[48](0),R[48,2](0),Pwr[48](0);//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48barsalpha1=(Cosine(.707*360/48)+Sine(.707*360/48)-1)/Cosine(.707*360/48);HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*

Page 701: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*(1-alpha1)*HP[2];//SmoothwithaSuperSmootherFilterfromequation3a1=expvalue(-1.414*3.14159/10);b1=2*a1*Cosine(1.414*180/10);c2=b1;c3=-a1*a1;c1=1-c2-c3;Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];//PearsoncorrelationforeachvalueoflagForLag=0to48Begin//SettheaveraginglengthasMM=AvgLength;IfAvgLength=0ThenM=Lag;Sx=0;Sy=0;Sxx=0;Syy=0;Sxy=0;Forcount=0toM-1BeginX=Filt[count];Y=Filt[Lag+count];Sx=Sx+X;Sy=Sy+Y;Sxx=Sxx+X*X;Sxy=Sxy+X*Y;

Page 702: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Syy=Syy+Y*Y;End; If (M*Sxx - Sx*Sx)*(M*Syy-Sy*Sy)>0ThenCorr[Lag]=(M*Sxy-Sx*Sy)/SquareRoot((M*Sxx-Sx*Sx)*(M*Syy-Sy*Sy));End;ForPeriod=10to48BeginCosinePart[Period]=0;SinePart[Period]=0;ForN=3to48BeginCosinePart[Period]=CosinePart[Period]+Corr[N]*Cosine(360*N/Period);SinePart[Period]=SinePart[Period]+Corr[N]*Sine(360*N/Period);End;SqSum[Period]=CosinePart[Period]*CosinePart[Period]+SinePart[Period]*SinePart[Period];

End;

ForPeriod=10to48BeginR[Period,2]=R[Period,1];R[Period,1]=.2*SqSum[Period]*SqSum[Period]+.8*R[Period,2];

End;

//FindMaximumPowerLevelforNormalization

MaxPwr=.991*MaxPwr[1];

ForPeriod=10to48BeginIfR[Period,1]>MaxPwrThenMaxPwr=R[Period,1];

Page 703: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

End;

ForPeriod=3to48BeginIfMaxPwr<>0ThenPwr[Period]=R[Period,1]/MaxPwr;

End;

//ComputethedominantcycleusingtheCGofthespectrum

Spx=0;

Sp=0;

ForPeriod=10to48BeginIfPwr[Period]>=.5ThenBeginSpx=Spx+Period*Pwr[Period];Sp=Sp+Pwr[Period];End;

End;

IfSp<>0ThenDominantCycle=Spx/Sp;

IfDominantCycle<10ThenDominantCycle=10;

IfDominantCycle>48ThenDominantCycle=48;

Vars:

Page 704: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Price(0),AvePrice(0),RMS(0),Num(0),Denom(0),Ratio(0),MyCCI(0);

//AdaptiveCCIstartshere,usinghalfthemeasureddominantcyclefortuning

Price=Filt;

AvePrice=0;

Forcount=0toDominantCycle-1Begin;AvePrice=AvePrice+Price[count];

End;

AvePrice=AvePrice/DominantCycle;

RMS=0;

Forcount=0toDominantCycle-1Begin;RMS=RMS+(Price[count]-AvePrice[count])*(Price[count]-AvePrice[count]);

End;

Page 705: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

RMS=SquareRoot(RMS/DominantCycle);

Num=Price-AvePrice;

Denom=.015*RMS;

Ratio=Num/Denom;

MyCCI = c1*(Ratio+Ratio[1])/2+c2*MyCCI[1]+c3*MyCCI[2];

Plot1(MyCCI);

Plot2(100);

Plot6(-100);

The first step in thecomputation is to find theaverage “price.” It isimportant to use this long

Page 706: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

form to compute the averageprice rather than the fastalgorithmofdroppingoff1 /N of the oldest price andadding 1 / N of the currentprice to the average becauseN is varying from bar to bardue to the tuning using thedominant cycle period. Oncethe moving average iscomputed, it is used tocomputetherootmeansquare(RMS)of theprices.RMS issynonymous with the

Page 707: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

standard deviation. Aftercreating the numerator andthe denominator, the ratio issmoothed using theSuperSmoother filterdescribed in Chapter 3. Thecoefficients for theSuperSmoother filters havepreviously been computed inthe dominant cyclemeasurementpartofthecode.I have included referencelines at the +100 and −100levels.

Page 708: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

TheadaptiveCCIhasbeenapplied to Dollar General(symbol DG) over roughlythe past year in Figure 11.3.This indicator accuratelydisplays the level of thecurrent prices within achannel. The duration of thechannel length is determinedby the measured dominantcycle period. The adaptiveCCI exceeds the plus orminusone standarddeviationonlyoccasionally.

Page 709: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure11.3AdaptiveCCIShowsthePriceLocationwithintheChannelLengthDeterminedbytheMeasuredDominantCyclePeriod

Page 710: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 711: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ AdaptiveBand-PassFilterIf a band-pass filter can bedesigned, it just makes sinceto tune that filter to themeasured dominant cycle toeliminate all the otherfrequency components thatare of no interest. The band-

Page 712: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

pass filter was described inChapter5.Here, theadaptiveband-pass indicator startswith the computation of thedominant cycle using theautocorrelation periodogramapproach. Code Listing 11-4contains the EasyLanguagecode for the adaptive band-pass indicator, and theidentification of the indicatoritselfisnotedbythecommentnear the end following thecalculation of the dominant

Page 713: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

cycle.

CodeListing11-4.EasyLanguage

CodetoComputetheAdaptive

Band-PassFilter{AdaptiveBandPassIndicator(c)2013JohnF.Ehlers

}

Inputs:Bandwidth(.3);

Page 714: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Vars:AvgLength(3),M(0),N(0),X(0),Y(0),alpha1(0),HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),Lag(0),count(0),Sx(0),Sy(0),Sxx(0),Syy(0),Sxy(0),Period(0),Sp(0),Spx(0),MaxPwr(0),DominantCycle(0);

Arrays:Corr[48](0),

Page 715: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CosinePart[48](0),SinePart[48](0),SqSum[48](0),R[48,2](0),Pwr[48](0);

//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48bars

alpha1=(Cosine(.707*360/48)+Sine(.707*360/48)-1)/Cosine(.707*360/48);

HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*(1-alpha1)*HP[2];

//SmoothwithaSuperSmootherFilterfromequation3

a1=expvalue(-1.414*3.14159/10);

b1=2*a1*Cosine(1.414*180/10);

c2=b1;

c3=-a1*a1;

c1=1-c2-c3;

Page 716: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

//Pearsoncorrelationforeachvalueoflag

ForLag=0to48Begin//SettheaveraginglengthasMM=AvgLength;IfAvgLength=0ThenM=Lag;Sx=0;Sy=0;Sxx=0;Syy=0;Sxy=0;Forcount=0toM-1BeginX=Filt[count];Y=Filt[Lag+count];Sx=Sx+X;Sy=Sy+Y;Sxx=Sxx+X*X;Sxy=Sxy+X*Y;Syy=Syy+Y*Y;End; If (M*Sxx - Sx*Sx)*(M*Syy-Sy*Sy)>0ThenCorr[Lag]=(M*Sxy-Sx*Sy)/SquareRoot((M*Sxx-Sx*Sx)*(M*Syy-Sy*Sy));

End;

Page 717: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ForPeriod=10to48BeginCosinePart[Period]=0;SinePart[Period]=0;ForN=3to48BeginCosinePart[Period]=CosinePart[Period]+Corr[N]*Cosine(360*N/Period);SinePart[Period]=SinePart[Period]+Corr[N]*Sine(360*N/Period);End;SqSum[Period]=CosinePart[Period]*CosinePart[Period]+SinePart[Period]*SinePart[Period];

End;

ForPeriod=10to48BeginR[Period,2]=R[Period,1];R[Period,1]=.2*SqSum[Period]*SqSum[Period]+.8*R[Period,2];

End;

//FindMaximumPowerLevelforNormalization

MaxPwr=.995*MaxPwr;

ForPeriod=10to48BeginIfR[Period,1]>MaxPwrThenMaxPwr=R[Period,1];

End;

ForPeriod=3to48BeginPwr[Period]=R[Period,1]/MaxPwr;

Page 718: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

End;

//ComputethedominantcycleusingtheCGofthespectrum

Spx=0;

Sp=0;

ForPeriod=10to48BeginIfPwr[Period]>=.5ThenBeginSpx=Spx+Period*Pwr[Period];Sp=Sp+Pwr[Period];End;

End;

IfSp<>0ThenDominantCycle=Spx/Sp;

IfDominantCycle<10ThenDominantCycle=10;

//AdaptiveBandPassindicatortunesaBandPassfilterto90%oftheperiodoftheDominantCycle

Vars:gamma1(0),alpha2(0),beta1(0),BP(0),Peak(0),Signal(0),

Page 719: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Lead(0),LeadPeak(0),LeadSignal(0);

beta1=Cosine(360/(.9*DominantCycle));

gamma1=1/Cosine(360*Bandwidth/(.9*DominantCycle));

alpha2=gamma1-SquareRoot(gamma1*gamma1-1);

BP = .5*(1 - alpha2)*(Filt - Filt[2]) + beta1*(1+alpha2)*BP[1]-alpha2*BP[2];

IfCurrentbar=1orCurrentBar=2ThenBP=0;

Peak=.991*Peak[1];

IfAbsValue(BP)>PeakThenPeak=AbsValue(BP);

IfPeak<>0ThenSignal=BP/Peak;

Lead = 1.3*(Signal+Signal[1]-Signal[2]-Signal[3])/4;

LeadPeak=.93*LeadPeak[1];

IfAbsValue(Lead)>LeadPeakThenLeadPeak=Absvalue(Lead);

Page 720: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

IfLeadPeak<>0ThenLeadSignal=.7*Lead/LeadPeak;

Plot1(Signal);

Plot14(.9*Signal[1]);

Plot2(0);

Plot6(.707);

Plot10(-.707);

One way to make a band-pass filter have a leadingphasecapabilityistotunethefilter to aperiod shorter thanthe period of the cycle beingmeasured. In this case, thebandwidth of filter is set to

Page 721: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

0.3.That is30percentof thetuned center period.Therefore,thehalfbandwidthis 15 percent. We tune thefilter tobe10percent towardthe shorter period from thedominant cycle period toprovide the phase lead whilestill having the data ofinterest be within the filterbandwidth. This provides aphase lead of the dominantcycle tobe somethingon theorder of 60 degrees, or one-

Page 722: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

sixth of a cycle. If thedominantcyclewere18bars,for example, then thedetuning of the filter wouldproduce a 3-bar lead. Thisleading function is not huge,butitissignificant.Aconvenienttriggerlineis

included in the adaptiveband-pass filter to signal themore highly likely buy andsell points. The trigger iscomputeas90percentof the

Page 723: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

amplitude of the adaptiveband-pass filter line and isdelayedbyonebar.Whiletheline crossings occur after thepeak of the band-pass filter,phase lead provides for thegenerationofa timelysignal.Significant trading signalsshould also include thecriteria that the line crossingoccuratgreaterthanthe+0.7and less than the −0.7referencelines.

Page 724: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The adaptive band-passfilter has been applied toDollar General (symbol DG)over roughly thepast year inFigure 11.4. This indicatoraccurately displays cyclicentry points when the twoindicator lines cross outsidethe plus or minus 0.7referencelines.

Figure11.4TheAdaptiveBand-PassFilterShowsBuyingandSelling

Page 725: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Opportunities

Page 726: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ AdaptiveIndicatorComparisonIt is instructive to view theadaptive indicators on asingle chart so they can becompared on a head-to-headbasis. This comparison isavailable inFigure 11.5. Themost striking difference is

Page 727: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

that the band-pass filter hasmore high-frequencycomponents. It is alsoapparent to me that the RSI,Stochastic,andCCIallprettymuchindicatethesamethingin the broad general sense.Without indicator transformsto enhance interpretation,which we cover in Chapter15, there isnooverwhelmingreason toselectone indicatoroveranother.

Page 728: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure11.5ComparisonoftheAdaptiveIndicators

Page 729: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 730: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Key PointstoRemember

1. When length is aninput parameter to anyindicator, that indicatorcan often be optimizedby tuning that length tothe dominant cycleperiod or a fractionthereof.2.Thepreferredmethod

Page 731: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

of computing thedominant cycle is usingthe autocorrelationperiodogram.3. The RSI indicator isoptimized over half theperiod of the measureddominant cycle to reachfull-scaleswingswithoutoversaturation.4. The stochasticindicator is optimizedover the full period of

Page 732: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the measured dominantcycle to ensure thehighest close and thelowest close have beenincluded.5. The CCI indicator isoptimized over the fullperiod of the measureddominantcycletoensureacompletemeasurementof the standarddeviation.6.Theband-passfilteris

Page 733: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

optimized by tuning thefilterto90percentofthemeasured dominantcycle period. Thisprovidesanapproximate60-degree phase lead intheindicator.

Page 734: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Notes1. P. J. Kaufman,Trading Systems andMethods, 3rd ed. (NewYork: John Wiley &Sons, 1998), pp. 436–438.

2. T. S. Chande and S.Kroll, The NewTechnical Trader (NewYork: John Wiley &Sons,1994).

Page 735: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

3. J.WellesWilder, Jr.,New Concepts inTechnical TradingSystems (Winston-Salem, NC: Hunter,1978).

4. D. Lambert,Commodities Magazine,October1980.

Page 736: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CHAPTER12

TheEvenBetterSinewave

Page 737: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Indicator“This is heavy stuff,”saidTomlighty.

I first introduced theSinewave Indicator as earlyas 1996.1,2 The concept wasbased on the idea that notechnical indicator ispredictive.All indicators relyon historical data, and aretherefore their signals are

Page 738: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

always lagging. However,cycles exist in the market,and it is often true that anobserved cycle will continuefor a short while into thefuture. Therefore, if we cantransfer the cyclic dataswingstoasinewave,wecanthen artificially advance thephase of the sine wave tocreateapredictiveindicator.Two conditions must be

satisfied to make the

Page 739: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Sinewave Indicator useful.First,themarketmustbeinacyclemode.Making a cyclicprediction when the data arein a trend is basically futile.Second, the period of thedominant cycle must beestimated with reasonableaccuracy. The downside oftheSinewaveIndicatoristhattheamplitudeswingsmustbefrom−1 to +1, and thereforethereisnodirectindicationofwhenthemarketisinatrend

Page 740: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

mode.Since the roofing filter

givescontrolofthefrequencycontent of the data to beanalyzed, the basic idea is touse the frequency content toan advantage. This controlenables the Even BetterSinewave Indicator to notonly enter a trade as quicklyas possible, but also use thetrend component to give theconfidence to stay with an

Page 741: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

existing trade without beingwhipsawed.

Page 742: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Even BetterSinewaveApproachThe original SinewaveIndicator was created byseeking the dominant cyclephase angle thathad thebestcorrelation between the pricedata and a theoreticaldominant cycle sine wave.

Page 743: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The Even Better SinewaveIndicator skips all the cyclemeasurements completelyand relies on a strongnormalization of thewaveform at the output of amodified roofing filter. Themodifiedroofingfilterusesasingle-polehigh-pass filter todeliberatelyretainthelonger-periodtrendcomponents.Thesingle-pole high-pass filterbasicallylevelstheamplitudeof all the cycle components

Page 744: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

that would otherwise belarger with longerwavelengths due to SpectralDilation.Therefore,whenthewaveform is normalized tothe power in the waveformover a short period of time,the longer wavelengthcontributions tend to be anindication to stay in a tradewhenthemarketisinatrend.TheEvenBetter Sinewave

Indicator works

Page 745: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

extraordinarilywellwhen themarket is in a trend mode.This means that thespectacular failures of mostswing wave indicators aremitigated when the expectedprice turning point does notoccur.Although I have not

studied it extensively, itappears that the Even BetterSinewave Indicator workswellonfutures intradaydata.

Page 746: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

It takes a position in thecorrectdirectionand tends tostay with the good tradeswithout excessivewhipsawing.

Page 747: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Even BetterSinewaveDescriptionThe Even Better SinewaveIndicator is described withreference to theEasyLanguage code given inCode Listing 12-1. The onlyuser input for the indicator isthe expected maximum

Page 748: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

duration of the trades whenthe market is in a trend.Making the duration inputparameter shorter willincreasethenumberoftradesover a given time span, andwill have a minor effect ofentering the trades a littlesooner. Conversely,increasing the duration inputparameter has the primaryeffect of holding andindicated trade positionlonger.

Page 749: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CodeListing12-1.EvenBetter

SinewaveIndicatorEasyLanguage

Code{EvenBetterSinewaveIndicator©2013JohnF.Ehlers

}

Inputs:Duration(40);

Vars:alpha1(0),HP(0),a1(0),

Page 750: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

b1(0),c1(0),c2(0),c3(0),Filt(0),count(0),Wave(0),Pwr(0);

//HighPassfiltercycliccomponentswhoseperiodsareshorterthanDurationinput

alpha1=(1-Sine(360/Duration))/Cosine(360/Duration);

HP = .5*(1 + alpha1)*(Close-Close[1])+alpha1*HP[1];

//SmoothwithaSuperSmootherFilterfromequation3

a1=expvalue(-1.414*3.14159/10);

b1=2*a1*Cosine(1.414*180/10);

c2=b1;

c3=-a1*a1;

c1=1-c2-c3;

Page 751: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

//3BaraverageofWaveamplitudeandpower

Wave=(Filt+Filt[1]+Filt[2])/3;

Pwr=(Filt*Filt+Filt[1]*Filt[1]+Filt[2]*Filt[2])/3;

//NormalizetheAverageWavetoSquareRootoftheAveragePower

Wave=Wave/SquareRoot(Pwr);

Plot1(Wave);

After declaring variables,thedataisfilteredinasingle-pole high-pass filter. Asingle-pole high-pass filter isdeliberately selected to

Page 752: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

equalize the data spectrumand allow trendingcomponentsthroughthefilterintotheindicator.Thedegreeof the spectrum allowedthrough the filter isestablished by the durationinput. The value of theduration input is set to beapproximatelythelengthofatradepositioninacontinuingtrend. The default value ofthe duration input is 40 bars,soamaximumtradeduration

Page 753: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

of about two months can beexpected with this setting.Increasing the duration inputwill increase the maximumdurationofatradeinatrend.This has the implication thatyouwill be working throughsome additional drawdownsthroughout the tradewith thebenefit that you will not bewhipsawedoutofaprofitabletrendingtrade.The high-pass filtered data

Page 754: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

is then filtered in aSuperSmoother filter whosecritical period is set to 10bars.After the data is passed

through themodified roofingfilter thethree-baraverageofthe wave amplitude and thepower are computed. Poweris proportional to the squareof the wave amplitude. TheEvenBetterSinewaveisthencomputedbynormalizing the

Page 755: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

averaged wave amplitude tothe square root of theaveraged power, causing theindicator to swing between−1and+1.

Page 756: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Using theEven BetterSinewaveIndicatorThe Even Better SinewaveIndicator is shown in Figure12.1, using the defaultduration setting of 40 bars.This means that the

Page 757: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

maximum length of a tradewhenthemarketisinatrendis about twomonths. This isbecause the high-pass filterstarts to attenuate the cycliccomponents that are longerthan40bars.

Figure12.1TheDefaultEvenBetterSinewaveIndicatorHoldsaPositionforaboutTwoMonthsinaTrend

Page 758: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Interpretation of the Even

Page 759: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Better Sinewave is simple.Holdalongpositionwhentheindicator value is near +1,and hold a short position (orgo flat if trading to the longsideonly)when the indicatorvalueisnear−1.The trade duration in a

trendcanbeextendedjustbyincreasing the duration inputvalue. For example, theindicator using a durationvalue of 40 is shown in

Page 760: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure12.2.Sureenough,theindicated longposition in theuptrend is extended. Doingthiscausessomeoftheshort-term reversals during thetrend to be eliminated. Theduration input parameter isadjusted to fit your tradingstyle.

Figure12.2TradePositionLengthisIncreasedbyIncreasingtheDurationInputParameter

Page 761: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Conversely, decreasing the

Page 762: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

duration input parametershortens the maximum tradelengthwhenthemarketisinatrend,beingmoresensitivetotheshorterwavelengthsinthedata. For example, Figure12.3 shows the indicatorwhenthedurationinputissetto20bars.Somecare shouldbetakenwhenshorteningtheduration input because theresulting shorter trades aremore sensitive to entry andexittimingandcomputational

Page 763: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

lagoftheindicator.

Figure12.3DecreasingtheDurationInputParameterMaketheEvenBetterSinewaveIndicatorMoreSensitivetoShort-TermVariationsintheData

Page 764: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 765: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Key PointstoRemember

1. The Even BetterSinewave Indicator is avariant of the roofingfilter,usingasingle-polehigh-passfilter.2. The unambiguoussignals of the EvenBetter SinewaveIndicator are generated

Page 766: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

bynormalizingthewaveamplitude to the squarerootofthepower.3.TheonlyinputfortheEven Better SinewaveIndicator is the durationparameter.4. The durationparameter controls themaximum length of anindicated position bysettingthecriticalperiodofthehigh-passfilter.

Page 767: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Notes1. John F. Ehlers, “Stayin Phase,” Stocks &Commodities,November 1996, Vol.14,No.11,p.69.

2.JohnF.Ehlers,RocketScience for Traders:Digital SignalProcessing Applications(Hoboken, NJ: JohnWiley & Sons, 2001),

Page 768: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Chapter9.

Page 769: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CHAPTER13

Convolution“I need to know whenthe market reverses,”saidTompointedly.

Page 770: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Oneofthemajorobjectivesof technical analysis is todecisively identify a majorreversalsothatonecantradethe market primarily in thedirectionoftheensuingtrend.Convolution is just the tickettomeetthatobjective.In mathematics,

convolution is an operationon two functions thatproduces a third function.Convolution is similar to

Page 771: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

cross-correlation between thetwo input functions—with atwist. A somewhat antiquename for convolution isfaltung,whichmeans foldingin German. It is this foldingconcept that makesconvolution useful fortrading.In this chapter, we will

spare you the details of themathematics and will jumpfrom the theoretical concept

Page 772: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

tousefultradingexamples.

Page 773: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ TheoreticalFoundationConsiderwhat happens at anidealizedmarketbottom.Theprices decrease linearly untilthe bottom is reached andthenincreaselinearlyafterthebottom has occurred. If wefold these idealized pricesabout themarket bottom, thetwo price segments are

Page 774: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

perfectly correlated. That is,we have cross-correlated twomarket segments that havebeen folded at the horizontalpoint of the market bottom.This perfect correlationoccurs only at the idealizedmarket bottom that, in fact,establishes the need forprefiltering before thecorrelation is calculated sothat a relatively highcorrelation can be achievedusingrealdata.

Page 775: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure 13.1 shows twographic examples ofconvolution in an initialuptrend.Intheleft-handcase,the folding has been done inthe middle of a continuingtrend.Theresultantisthatthetwo price segments are notcorrelated after the foldingoperation. However, if thefolding isdoneatexactly themarketpeak,asshownintheright-handcase,thetwopricesegments are exactly

Page 776: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

correlated after the foldingoperation.

Figure13.1HighCorrelationsOccurOnlyatMajorMarketTurningPoints

Page 777: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 778: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Since high correlationexists only at the marketturningpoint,theconvolutionindicator is dependent on thelookback period used in thecalculation. Assuming thetwo price segments have anequal timeduration, thepeakcorrelation occurs at half thelookback period of theindicator. For example, if a13-bar period is used, themarket peak would appear

Page 779: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

witha7-bardelay.Thesamemarket peak would appearwith a 19-bar delay if a 39-bar lookback period wereused in the convolutioncomputation.The caseof themarketpeak'snotoccurringatthefoldingpointisillustratedin Figure 13.2, showing howthe correlation decreaseswhen the folding point doesnotoccuratthemarketpeak.

Figure13.2GoodCorrelation

Page 780: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

OccursOnlyWhentheFoldingIsDoneattheMarketReversalPoint

Page 781: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 782: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Stillanothercase isshownin Figure 13.3, where themarket trend is brieflyinterruptedandthenresumes.As long as the lookbackperiodisequaltoorlessthantwice the distance betweenthetwoverticaldottedlines,ahigh-correlation event willoccur at half the lookbackperiod. However, when thelookback period becomeslonger, thenoncorrelated line

Page 783: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

segment is included in theconvolution computation andthe overall correlation isreduced.

Figure13.3InterruptionsinMarketTrendsHaveHighCorrelationsforOnlyShortPeriods

Page 784: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 785: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

When the correlation isplotted as a conventionalindicator,thehigh-correlationpointwillshowupataspikethat is delayed half thelookback period from thecurrent data bar. If thelookback period is short, thecorrelation spikes will berelatively current, but therewill be a lot of them. If thelookback period is long,convolution basically reports

Page 786: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ancienthistory,andtheshort-term interruptions will beeliminated.Consequently,theconvolution display isdependent on the lookbackperiod used in thecomputation.

Page 787: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Heat MapDisplayThe convolution indicatorcovers a range of lookbackperiods.Thevertical scale ofthe indicator is the lookbackperiod, and the indicatorvalue is converted to colors.An indicator is repeatedlycalculated for each lookbackperiod for each new bar of

Page 788: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

data.Theresultisaheatmapdisplay that is in time syncwith the price data and thevalues of the indicator areshown for the full range ofusefullookbackperiods.When the convolution

computationsaredisplayedascolors over the range oflookback periods, theresultingchartshowsthehighcorrelation points as“plumes” that point back

Page 789: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

preciselytothemajormarketreversals.Theinterruptionsinmarket trends show up asforeshorted and vestigialplumes.The convolution for

approximately the last yearon the Dollar General(symbol DG) is shown inFigure 13.4. By taking thedirection of the trend intoaccount, market tops aredisplayed as red plumes

Page 790: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

(signaling a reversal to thedownside), and marketbottoms are displayed asgreen plumes (signaling areversal to the upside). Theforeshortened plumes inJanuary 2011 signal that theuptrendfromthefallof2010is still in play. For theremainder of 2011, the fiveredplumes and the sixgreenplumes absolutely nail themajor market reversals. Thereversal points are located at

Page 791: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

thebottomoftheconvolutionsubgraph, and the longplumes identify each as amajor turning point. Since afinite amount of data isrequired tomake the shortestcalculation, convolution ismovedfourbarstothelefttobetter correlate the indicatorwith the actual turningpoint.This technique is similar tothat of a centered movingaverage.

Page 792: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure13.4ConvolutionNailedEachMarketReversaloverthePastYear

Page 793: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 794: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ ComputingConvolutionFor those interested incomputing the convolutionindicator on their own, theprocess is relativelystraightforward. A filter tominimize the effects ofSpectralDilationprecedestheactual calculation, and theshortest and longest periods

Page 795: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ofthisfilterareprofitasuserinputs.Thedefaultvaluesare40 bars and 80 bars. Theshortest period can bereduced to reducecomputational lag, but at theexpense of additional displayartifacts near the bottom ofthe display. After declaringthe variables and the arrays,undesired long-wave cycliccomponentsareremovedbyatwo-pole high-pass filtertuned to the longest period.

Page 796: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The high-pass filter isfollowed by theSuperSmoother of Equation3-3, whose transfer responseis displayed in Figure 3.10.The 40-bar period for thisfilter was selected to reducethe displays of all but themajor turning points. Sincethe market data are fractal(thelongercycleperiodshavethelargerswings),wewanttoavoid spurious displays ofrelatively minor turning

Page 797: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

points.Thus,thecombinationofthehigh-passfilterandtheSuperSmoother form a“roofing”filterthatpassesthedesired range of frequencycomponents useful forconvolution.Textbook Pearson

correlation is accomplishedfor each of the lookbackperiods from 1 to 48, and acorrelation value is assignedtoeach lookbackperiod.The

Page 798: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

variable X is the base datastream, and thevariableY isthe data stream folded backforeachcalculationloop.ThevaluesofX,Y,X*X,X*Y,andY*Y are summed overthe lookback length beforebeing applied to thecorrelation equation. Thecorrelation resulting from thecomputations varies from −1to +1. These correlationvalues are applied to an

Page 799: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

inverse Fisher transform2 tosharpen the display and thenrescaled to vary between 0and1forplottingpurposes.There is a considerable

amount of information to bedisplayed, and a heatmap isused to make sense of it all.Thegeneralschemeisthatforeach horizontal axis timeposition the verticaldisplacement is equal to thelag from 3 to 48. The

Page 800: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

correlationvalueforeachlagisconvertedtoacolor.If theslope of the prices over thelookback period is positive,then the hue is red. Thesaturation of the red color isdetermined by the value ofthecorrelation.Iftheslopeofthe prices over the lookbackperiod is negative, then thehue is green. The saturationof the green color isdetermined by the value ofthecorrelation.

Page 801: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

TheEasyLanguagecodetocompute the Convolutionindicator is given in CodeListing13-1.

CodeListing13-1.EasyLanguage

CodetoComputeandDisplayConvolution

{ConvolutionIndicator(c)2013JohnF.Ehlers

Page 802: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

}

Inputs:ShortestPeriod(40),LongestPeriod(80);

Vars:alpha1(0),HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),N(0),II(0),X(0),Y(0),Sx(0),Sy(0),Sxx(0),Syy(0),Sxy(0),Color1(0),Color2(0),Color3(0);

Arrays:

Page 803: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Corr[48](0),Slope[48](0),Convolution[48](0);

//HighPassfiltercycliccomponentswhoseperiodsareshorterthan48bars

alpha1=(Cosine(1.414*360/LongestPeriod)+Sine(1.414*360/LongestPeriod)-1)/Cosine(1.414*360/LongestPeriod);

HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*(1-alpha1)*HP[2];

//SmoothwithaSuperSmootherFilterfromequation3

a1=expvalue(-1.414*3.14159/ShortestPeriod);

b1=2*a1*Cosine(1.414*180/ShortestPeriod);

c2=b1;

c3=-a1*a1;

c1=1-c2-c3;

Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

Page 804: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ForN=1to48BeginSx=0;Sy=0;Sxx=0;Syy=0;Sxy=0;ForII=1toNBeginX=Filt[II-1];Y=Filt[N-II];Sx=Sx+X;Sy=Sy+Y;Sxx=Sxx+X*X;Sxy=Sxy+X*Y;Syy=Syy+Y*Y;End; If (N*Sxx - Sx*Sx)*(N*Syy-Sy*Sy)>0ThenCorr[N]=(N*Sxy-Sx*Sy)/SquareRoot((N*Sxx-Sx*Sx)*(N*Syy-Sy*Sy));Slope[N]=1;IfFilt[IntPortion(.5*N)]<FiltThenSlope[N]=-1;Convolution[N]=(1+(ExpValue(3*Corr[N])-1)/(ExpValue(3*Corr[N])+1))/2;

End;

//PlotasaHeatmap

ForN=3to48BeginIfSlope[N]>0ThenBegin

Page 805: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Color1=255*Convolution[N];Color2=0;End;IfSlope[N]<0ThenBeginColor1=0;Color2=255*Convolution[N];End;Color3=0; If N = 2 Then Plot2[4](2,“S2”,RGB(Color1,Color2,Color3),0,4); If N = 3 Then Plot3[4](3,“S3”,RGB(Color1,Color2,Color3),0,4); If N = 4 Then Plot4[4](4,“S4”,RGB(Color1,Color2,Color3),0,4); If N = 5 Then Plot5[4](5,“S5”,RGB(Color1,Color2,Color3),0,4); If N = 6 Then Plot6[4](6,“S6”,RGB(Color1,Color2,Color3),0,4); If N = 7 Then Plot7[4](7,“S7”,RGB(Color1,Color2,Color3),0,4); If N = 8 Then Plot8[4](8,“S8”,RGB(Color1,Color2,Color3),0,4); If N = 9 Then Plot9[4](9,“S9”,RGB(Color1,Color2,Color3),0,4); If N = 10 Then Plot10[4](10,“S10”,RGB(Color1,Color2,Color3),0,4); If N = 11 Then Plot11[4](11,“S11”,RGB(Color1,Color2,Color3),0,4); If N = 12 Then Plot12[4]

Page 806: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

(12,“S12”,RGB(Color1,Color2,Color3),0,4); If N = 13 Then Plot13[4](13,“S13”,RGB(Color1,Color2,Color3),0,4); If N = 14 Then Plot14[4](14,“S14”,RGB(Color1,Color2,Color3),0,4); If N = 15 Then Plot15[4](15,“S15”,RGB(Color1,Color2,Color3),0,4); If N = 16 Then Plot16[4](16,“S16”,RGB(Color1,Color2,Color3),0,4); If N = 17 Then Plot17[4](17,“S17”,RGB(Color1,Color2,Color3),0,4); If N = 18 Then Plot18[4](18,“S18”,RGB(Color1,Color2,Color3),0,4); If N = 19 Then Plot19[4](19,“S19”,RGB(Color1,Color2,Color3),0,4); If N = 20 Then Plot20[4](20,“S20”,RGB(Color1,Color2,Color3),0,4); If N = 21 Then Plot21[4](21,“S21”,RGB(Color1,Color2,Color3),0,4); If N = 22 Then Plot22[4](22,“S22”,RGB(Color1,Color2,Color3),0,4); If N = 23 Then Plot23[4](23,“S23”,RGB(Color1,Color2,Color3),0,4); If N = 24 Then Plot24[4](24,“S24”,RGB(Color1,Color2,Color3),0,4); If N = 25 Then Plot25[4](25,“S25”,RGB(Color1,Color2,Color3),0,4); If N = 26 Then Plot26[4](26,“S26”,RGB(Color1,Color2,Color3),0,4);

Page 807: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

If N = 27 Then Plot27[4](27,“S27”,RGB(Color1,Color2,Color3),0,4); If N = 28 Then Plot28[4](28,“S28”,RGB(Color1,Color2,Color3),0,4); If N = 29 Then Plot29[4](29,“S29”,RGB(Color1,Color2,Color3),0,4); If N = 30 Then Plot30[4](30,“S30”,RGB(Color1,Color2,Color3),0,4); If N = 31 Then Plot31[4](31,“S31”,RGB(Color1,Color2,Color3),0,4); If N = 32 Then Plot32[4](32,“S32”,RGB(Color1,Color2,Color3),0,4); If N = 33 Then Plot33[4](33,“S33”,RGB(Color1,Color2,Color3),0,4); If N = 34 Then Plot34[4](34,“S34”,RGB(Color1,Color2,Color3),0,4); If N = 35 Then Plot35[4](35,“S35”,RGB(Color1,Color2,Color3),0,4); If N = 36 Then Plot36[4](36,“S36”,RGB(Color1,Color2,Color3),0,4); If N = 37 Then Plot37[4](37,“S37”,RGB(Color1,Color2,Color3),0,4); If N = 38 Then Plot38[4](38,“S38”,RGB(Color1,Color2,Color3),0,4); If N = 39 Then Plot39[4](39,“S39”,RGB(Color1,Color2,Color3),0,4); If N = 40 Then Plot40[4](40,“S40”,RGB(Color1,Color2,Color3),0,4); If N = 41 Then Plot41[4]

Page 808: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

(41,“S41”,RGB(Color1,Color2,Color3),0,4); If N = 42 Then Plot42[4](42,“S42”,RGB(Color1,Color2,Color3),0,4); If N = 43 Then Plot43[4](43,“S43”,RGB(Color1,Color2,Color3),0,4); If N = 44 Then Plot44[4](44,“S44”,RGB(Color1,Color2,Color3),0,4); If N = 45 Then Plot45[4](45,“S45”,RGB(Color1,Color2,Color3),0,4); If N = 46 Then Plot46[4](46,“S46”,RGB(Color1,Color2,Color3),0,4); If N = 47 Then Plot47[4](47,“S47”,RGB(Color1,Color2,Color3),0,4); If N = 48 Then Plot48[4](48,“S48”,RGB(Color1,Color2,Color3),0,4);

End;

Page 809: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Key PointstoRemember

1. Convolution issynonymous with“folding.” Theconvolution indicatorfinds price reversalpointsbyidentifyingthehighestcorrelationofthedata by folding it in thetime dimension about

Page 810: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

thelookbackperiod.2. The major pricereversals are identifiedby plumes pointingbackward to the time ofthepricereversal.3.Topsandbottomscanbe identified by colorusing the price slope toassignthecolorvalues.

Page 811: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Notes1. John Ehlers and RicWay, “SwamiChartsConvolution,” Stocks &Commodities, October2012, Vol. 30, No. 10,pp.10–13.

2. John Ehlers, “TheInverse FisherTransform,” Stocks &Commodities, 2004,Vol. 22, No. 5, pp.

Page 812: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

38−42.

Page 813: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CHAPTER14

TheHilbertTransformer

“The wave has animaginary component,”

Page 814: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

saidTomrealistically.

An analytic signal allowsfor time-variable parametersand isageneralizationof thephasor concept, which isrestricted to time-invariantamplitude, phase, andfrequency. The analyticrepresentation of a real-valued function or signalfacilitatesmanymathematicalmanipulations of the signal.For example, computing the

Page 815: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

phaseofasignalorthepowerin the wave is much simplerusinganalyticsignals.The Hilbert transformer is

the technique to create ananalytic signal from a realone.TheconventionalHilberttransformeristheoreticallyaninfinite-length FIR filter.Evenwhenthefilterlengthistruncatedtoausefulbutfinitelength, the induced lag is fartoo large to make the

Page 816: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

transformer useful fortrading.I have therefore created a

modified Hilbert transformerthat has only a small lag butstill has performancecharacteristics superior tothose of a truncated FIRHilberttransformer.The modified Hilbert

transformercanbeusedasaneffective trading indicatorbecause the quadrature

Page 817: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

component output leads thereal output in the samemanneracosinewaveleadsasine wave. In this sense, amodified Hilbert transformerisapredictiveindicator.In this chapter, I

demonstrate three differentways to measure the time-variantdominantcycleperiodusing analytic signals. Theseare all basically measuringtheinstantaneousphaseofthe

Page 818: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

signal and, in essence,summing the phases toestimate the cycle period.Sincethesmoothinglengthisusually less than one fullcycle period, the results arefairlynoisyandare thereforeonly marginally useful fortrading.Iincludethecodeforthese dominant cyclemeasurements primarily forcompleteness and becausesomeone smarter than memay be able to use them

Page 819: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

successfully.

Page 820: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ AnalyticSignalsWithout getting allmathy onyou, I will try a simplifieddescription of the theory ofnumbers for you to reach anunderstanding of analyticsignals.Thenumbersthatyouknow and love extend fromminusinfinitytoplusinfinityalongastraightline.Thisline

Page 821: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

includes integers, rationalnumbers, irrational numbers,and even zero. This is notexactly as trivial as it seemsbecausetheRomannumerals,for example, had no conceptof zero. It wasn't until 976A.D. that the Persianencyclopedist Muhammadibn Ahmad al-Khwarizmi(fromwhomwegetthewordalgorithm) used the notationand wasn't until 1202 A.D.thatFibonnaci introduced the

Page 822: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

concept of zero to Europe atthe beginning of theRenaissance. Of course, thatwas beforemargin calls, andso the idea of negativenumbers didn't arise untilrelatively recently. With thatdigression, the main idea isthatall“real”numberscanbepicturedasbeingonastraightline.A straight line is not the

only constructwe can use to

Page 823: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

visualize a numberingsystem. For example, if weplace numbers on a planesurface we can describenumbers by their location onthe plane. We do this byusing a “real” axis and an“imaginary” axis that is atright angles to the real axis.Thenamesarenotnecessarilysignificant except in ahistoricalcontext.Afterall,ifwe can have irrationalnumbers we can have an

Page 824: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

imaginaryaxis.Figure 14.1 shows the

relevance of analytic signalstotradersusingindicators.Asa function of time the sinewave starts at zero andincreases toward itsmaximum value while thecosine wave starts at itsmaximum value anddecreases in amplitude. Notethat the cosine wave crosseszero just as the sine wave

Page 825: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

reaches its maximum valueand has zero slope. Thecosine wave represents therate of change of the sinewave. These two waveformscan also be represented asvectors in the complex planehavingtherealandimaginaryaxes. The waves in the timedomain are represented byprojections on the imaginaryaxisas the twovectors rotatecounterclockwise. A fullcycle in the time domain is

Page 826: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

completed when the vectorsrotate a full 360 degrees inthecomplexplane.

Figure14.1SineandCosineWavesasAnalyticSignals

Notethatthevectorsinthe

Page 827: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

complex plane are at rightangles, and are said to beorthogonal. Because of theright angle property, I oftenrefertothesinecomponentasthe in-phase component, andthe cosine component is thequadrature component. Moregenerally, orthogonalitymeansthat theproductof thetwo vectors is uncorrelated.For example, the sum ofsin(x) * cos(x) over a fullcycle iszero.Knowingabout

Page 828: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

analytic signals opens thedoor to making someinteresting calculations usingmarket data. For example,sin2(x) + cosine2(x) is equalto a constant.We also knowthis frombasic trigonometry.Failingtocomputethesumofthesquaresasaconstantisanindication of the failure ofcreatingananalyticsignal.Inthis case, that failure meansthe market is probably

Page 829: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

transitioning between a cyclemodeandatrendmode.Analytic signals also open

thepossibilityofmakingveryrapid measurements of thedominant cycle period byexamining the ratechangeofphase angle of the vectors inthe complex plane. Forexample if the vector anglechanges 18 degrees per bar,the dominant cycle periodmustbe20barsbecause that

Page 830: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

rateofchangegivesatotalof360 degree over the 20-barperiod.

Page 831: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ HilbertTransformerMathematicsA Hilbert transformer is justanFIRfilterwhosepurposeisto create a quadraturecomponentfromtherealdatastream. The filter length istheoretically infinite, but canbe truncated as an

Page 832: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

approximation. The filtercoefficients can be expressedasSin2(πn/2)/n,wherenisthe position from the centerof the filter. Coefficientsolder thanhalf thefilterhaveanegativesign.Forexample,a 23-element Hilberttransformer filter hascoefficientsas:

The frequency response of

Page 833: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

this filter is shown in Figure14.2. This filter outputresponse has ripplethroughout its pass band androll-offatzerofrequencyandtheNyquist frequencydue totruncationof thecoefficients.Ideally, the Hilberttransformer is an all-passfilter.Wecanmanipulate thecoefficients to reduce theamount of in-band ripple;however, it is not worth theeffort. The problem is that

Page 834: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

this FIR filter has a 11-barlag.More generally, the FIRfilterlagis(N−1)/2,wherethere are an odd number ofelements in the filter. In ourcase, a lag of 11 bars is justunacceptablefortrading.

Figure14.2FrequencyResponseofa23-ElementHilbertTransformer

Page 835: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 836: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The lag of a Hilberttransformer can be reducedby reducing the number ofelements in the filter. In thelimit, the shortest truncatedHilbert transformer has thecoefficientsas:

This shorter Hilberttransformerisnicefortradingbecause ithasonlyaone-barlag. However, the frequencyresponseof the three-element

Page 837: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Hilbert transformer has asubstantial amplitude slopeacross the pass band, asshown in Figure 14.3. Thepass band of interest extendsfrom approximately a 50-barperiod(frequency=0.02)toa10-bar period (frequency =0.1). The shorter Hilberttransformer is also notacceptable for tradingbecause of the hugeamplitude variation over thepassband.

Page 838: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure14.3FrequencyResponseofaThree-ElementHilbertTransformer

Page 839: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 840: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure14.4TheHilbertTransformerIndicatorHastheCorrectPhaseandAmplitudeasShownbytheResponsetoaChirpedSineWaveWhosePeriodVariesfrom10Barsto40Bars

Page 841: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

I have included the

Page 842: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

EasyLanguage code tocompute the Hilberttransformer as a classictruncated FIR filter in CodeListing14-1becauseitcanbeuseful for comparing resultsto the modified Hilberttransformer I will derive.After declaring variables, thecodebeginsbycomputingtheroofing filter as acombination of a two-polehigh-pass filter and aSuperSmoother filter. The

Page 843: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

automaticgaincontrol(AGC)technique described inChapter5isusedtocomputethe normalized Real signal.ThevariableRealisbasicallythe same as the variable Filtexcept that it has anormalized amplitude. Theimaginary signal, calledImag, is computed from theFIR filtering of the variableReal.ThentheRealandImagsignals are plotted.Note thatthe plot for the imaginary

Page 844: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

signalisartificiallymovedtothe left by 11 bars tocompensate for the ladinduced by the FIR filter. Ifthe Real and Imag signalswere to be used for trading,Real would have to bedelayed by 11 bars to havethe correct relationship toImag.

CodeListing14-1.EasyLanguage

Page 845: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CodetoComputeaClassicHilbertTransformer

{ClassicHilbertTransformer©2013JohnF.Ehlers}

Vars:alpha1(0),HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),Real(0),Imag(0),IPeak(0);

//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48bars

Page 846: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

alpha1=(Cosine(.707*360/48)+Sine(.707*360/48)-1)/Cosine(.707*360/48);

HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*(1-alpha1)*HP[2];

//SmoothwithaSuperSmootherFilterfromequation3

a1=expvalue(-1.414*3.14159/10);

b1=2*a1*Cosine(1.414*180/10);

c2=b1;

c3=-a1*a1;

c1=1-c2-c3;Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

IPeak=.991*IPeak[1];

IfAbsvalue(Filt)>IPeakThenIPeak=AbsValue(Filt);Real=Filt/IPeak;

Page 847: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

//TruncatedHilbertTransformFIRfilterasatestImag=(.091*Real+.111*Real[2]+.143*Real[4]+.2*Real[6]+.333*Real[8]+Real[10]-Real[12]-.333*Real[14]-.2*Real[16]-.143*Real[18]-.111*Real[20]-.091*Real[22])/1.865;

Plot1(Real);

Plot2(0);

Plot6[11](Imag);

Page 848: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Computingthe HilbertTransformerThe Hilbert TransformIndicator is described withreference to theEasyLanguagecodeshowninCode List 14-2. Thecomputations begin with theroofing filter as with the

Page 849: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

classic Hilbert transformerexcept that thecriticalperiodof the SuperSmoother isprovided as a user-selectableinput.Thisgivestheindicatormore flexibility in providinggreaterorlessersmoothingasdesired.

CodeListing14-2.EasyLanguage

CodetoCompute

Page 850: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

theHilbertTransformer

{HilbertTransformer©2013JohnF.Ehlers}

Inputs:LPPeriod(20);

Vars:alpha1(0),HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),QFilt(0),Real(0),Imag(0),IPeak(0),

Page 851: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

QPeak(0);

//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48bars

alpha1=(Cosine(.707*360/48)+Sine(.707*360/48)-1)/Cosine(.707*360/48);

HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*(1-alpha1)*HP[2];

//SmoothwithaSuperSmootherFilterfromequation3

a1=expvalue(-1.414*3.14159/LPPeriod);

b1=2*a1*Cosine(1.414*180/LPPeriod);

c2=b1;

c3=-a1*a1;

c1=1-c2-c3;Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

IPeak=.991*IPeak[1];

Page 852: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

IfAbsvalue(Filt)>IPeakThenIPeak=AbsValue(Filt);Real=Filt/IPeak;

QFilt=(Real-Real[1]);

QPeak=.991*QPeak[1];

IfAbsvalue(QFilt)>QPeakThenQPeak=AbsValue(QFilt);Imag=QFilt/QPeak;

Plot1(Real);

Plot2(0);

Plot6(Imag);

The Real component iscomputedexactlyasitwasinthe classic Hilberttransformer, by normalizingFilttoitsrecentpeakvalueas

Page 853: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

determined by the AGCalgorithm.The imaginary component

calculation starts by takingthe one bar difference of theReal variable. This isanalogous to taking thederivative of a sine wave togenerate a cosine wave. Theone-bar differencecomputation provides thephasequadrature requiredforthe imaginary component.

Page 854: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The amplitude correction isprovided by a second AGCaction performed on theimaginary component alone.Having the phase quadratureandthenormalizedamplitudefulfills all the requirementsfortheimaginarycomponent.The lag of the Real and

Imag analytic signals is verysmall, and no compensationin the plotting routine isrequired. In other words, an

Page 855: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

indicator has been createdthat has a predictivecapability.The outstanding

performance of the Hilberttransformer is bestdemonstrated by its responsetoachirpedsinewavewhoseperiodcontinuously increasesfrom 10 bars to 40 bars.Throughout the entire range,the indicator maintains thecorrect phase and amplitude

Page 856: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

relationship between the realand imaginary components.This performance is vastlysuperior to thatof theclassicHilbert transformer using atruncatedFIRfilter.

Page 857: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ The HilbertTransformerIndicatorFigure 14.5 shows the realandimaginarycomponentsoftheHilberttransformerbelowthepricechart.Basically, thereal component moves withthe general direction of theprices, and the imaginary

Page 858: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

component is a predictiveindicator for the realcomponent in thesamesensethat a cosine wave is apredictor of a sine wave.Although the defaultLPPeriod input is set to 20bars in an attempt to smooththe indicator the imaginarycomponent is still too erratictobeuseful.

Figure14.5InitialApplicationoftheHilbert

Page 859: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

TransformertoDG

Page 860: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Code Listing 14-3 showsthe EasyLanguage code forthe Hilbert transformerindicator.Thecodeisexactlythe same as for the Hilberttransformer except that aSuperSmoother filter hasbeen added to smooth theimaginarycomponent.

CodeListing14-3.EasyLanguage

CodetoCompute

Page 861: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

theHilbertTransformerIndicator

{HilbertTransformerIndicator©2013JohnF.Ehlers}

Inputs:LPPeriod(20);

Vars:alpha1(0),HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),QFilt(0),Real(0),

Page 862: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Quadrature(0),IPeak(0),QPeak(0),Imag(0);

//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48bars

alpha1=(Cosine(.707*360/48)+Sine(.707*360/48)-1)/Cosine(.707*360/48);

HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*(1-alpha1)*HP[2];

//SmoothwithaSuperSmootherFilterfromequation3

a1=expvalue(-1.414*3.14159/LPPeriod);

b1=2*a1*Cosine(1.414*180/LPPeriod);

c2=b1;

c3=-a1*a1;

c1=1-c2-c3;Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

Page 863: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

IPeak=.991*IPeak[1];

IfAbsvalue(Filt)>IPeakThenIPeak=AbsValue(Filt);Real=Filt/IPeak;

Quadrature=(Real-Real[1]);

QPeak=.991*QPeak[1];

IfAbsvalue(Quadrature)>QPeakThenQPeak=AbsValue(Quadrature);Quadrature=Quadrature/QPeak;

a1=expvalue(-1.414*3.14159/10);

b1=2*a1*Cosine(1.414*180/10);

c2=b1;

c3=-a1*a1;

c1=1-c2-c3;Imag = c1*(Quadrature+Quadrature[1])/2+c2*Imag[1]+c3*Imag[2];

Plot1(Real);

Plot2(0);

Page 864: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Plot6(Imag);

The performance of theHilbert transformer indicatoris demonstrated in Figure14.6.Thesmoothingaffordedby the added SuperSmootherfilter destroys theorthogonality of theimaginary componentbecause it introduces severalbars of lag. However, theSuperSmoother made the

Page 865: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

imaginary component usefulby smoothing out its erraticbehavior. Now the predictedturningpoint to theupside iswhen the imaginarycomponent crosses over thereal component. This givesyoutimetoactuallyplacethetradebefore the turningpointhas occurred. Similarly, thepredicted turningpoint to thedownside is when theimaginarycomponentcrossesunder the real component.

Page 866: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

You have some control overthe indicator through theLPPeriodinputparameter.

Figure14.6TheImaginaryComponentoftheHilbertTransformerIndicatorPredictstheTurningPointsoftheRealComponent

Page 867: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The problem with

Page 868: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

predictingtheturningpointisthat it may not be a swingturningpointatall.Rather, itcan be the onset of a newtrend.Inthiscase,theturningpoint predictionwill be deadwrong. One way to mitigatean incorrect turning pointprediction is to first take thetrade in the predicteddirection, but then be quickandagiletoexitthetradeifitisnotconfirmedby theEvenBetterSinewaveIndicator.

Page 869: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Using theHilbertTransformerto Computethe DominantCycleI want to emphasize that theonlyreasonforincludingthis

Page 870: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

section is for completeness.Unless you are interested inresearch, I suggest you skipthis section entirely. Tofurther emphasize my point,do not use the code fortrading. A vastly superiorapproach to compute thedominant cycle in the pricedata is the autocorrelationperiodogram. The code isincluded because the readermay be able to capitalize onthealgorithmsinawaythatI

Page 871: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

donotsee.Allthealgorithmsencapsulated in the codeoperate reasonably well ontheoretical waveforms thathavenonoisecomponent.Myconjectureat this time is thatthe sample-to-sample noisesimply swamps thecomputation of the ratechange of phase, andtherefore the resultingcalculations to find thedominant cycle are basicallyworthless. The imaginary

Page 872: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

component of the Hilberttransformer cannot besmoothedaswasdone in theHilbert transformer indicatorbecause the smoothingdestroys the orthogonality oftheimaginarycomponent.

Page 873: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ DualDifferentiatorThe first algorithm tocompute the dominant cycleis called the dualdifferentiator.Inthiscase,thephaseangleiscomputedfromthe analytic signal as thearctangent of the ratio of theimaginary component to thereal component. Further, the

Page 874: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

angular frequency is definedas the rate change of phase.We can use these facts toderivethecycleperiod.Fromthe definition of thederivative of an arctangent,the mathematics of thisprocessare:

Page 875: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Simplifyingandsolvingforthe cycle period instead offrequency,weobtain:

Where: IP = In-phasecomponent(Real)

Q = Quadraturecomponent(Imag)IDot=RateofchangeofIPQDot = Rate of change

Page 876: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ofQThe code to compute the

dominantcycleusingthedualdifferentiatorisgiveninCodeListing14-4.

CodeListing14-4.EasyLanguage

CodetoComputetheDominantCycleUsingthe

Page 877: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

DualDifferentiatorMethod

{MeasuringtheDominantCycleusingtheDualDifferentiator©2013JohnF.Ehlers}

Inputs:LPPeriod(20);

Vars:alpha1(0),HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),QFilt(0),Real(0),Quad(0),Imag(0),

Page 878: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

IPeak(0),QPeak(0),IDot(0),QDot(0),Period(0),DomCycle(0);

//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48bars

alpha1=(Cosine(.707*360/48)+Sine(.707*360/48)-1)/Cosine(.707*360/48);

HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*(1-alpha1)*HP[2];

//SmoothwithaSuperSmootherFilterfromequation3

a1=expvalue(-1.414*3.14159/LPPeriod);

b1=2*a1*Cosine(1.414*180/LPPeriod);

c2=b1;

c3=-a1*a1;

c1=1-c2-c3;

Page 879: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

IPeak=.991*IPeak[1];

IfAbsvalue(Filt)>IPeakThenIPeak=AbsValue(Filt);

Real=Filt/IPeak;

Quad=(Real-Real[1]);

QPeak=.991*QPeak[1];

IfAbsvalue(Quad)>QPeakThenQPeak=AbsValue(Quad);Imag=Quad/QPeak;

IDot=Real-Real[1];

QDot=Imag-Imag[1];

If(Real*QDot-Imag*IDot)<>0ThenPeriod=6.28318*(Real*Real + Imag*Imag) / (-Real*QDot+Imag*IDot);

IfPeriod<8ThenPeriod=8;

IfPeriod>48ThenPeriod=48;DomCycle = c1*(Period+Period[1])/2+c2*DomCycle[1]+c3*DomCycle[2];

Page 880: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Plot1(DomCycle);

Page 881: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ PhaseAccumulationThe next algorithm tocompute the dominant cycleis the phase accumulationmethod. The phaseaccumulation method ofcomputing the dominantcycleisperhapstheeasiesttocomprehend. In thistechnique, we measure the

Page 882: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

phase at each sample bytaking the arctangent of theratio of the quadraturecomponent to the in-phasecomponent. A delta phase isgenerated by taking thedifference of the phasebetween successive samples.At each sample we can thenlook backwards, adding upthe delta phases. When thesum of the delta phasesreaches360degrees,wemusthave passed through one full

Page 883: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

cycle, on average. Theprocess is repeated for eachnewsample.The phase accumulation

methodofcyclemeasurementalways uses one full cycle'sworthof historical data.Thisis both an advantage and adisadvantage. The advantageis the lag in obtaining theanswer scales directly withthe cycle period. That is, themeasurementofashortcycle

Page 884: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

period has less lag than themeasurement of a longercycle period. However, thenumber of samples used inmaking the measurementmeanstheaveragingperiodisvariable with cycle period.Longeraveragingreducesthenoise level compared to thesignal. Therefore, shortercycle periods necessarilyhave a higher output signal-to-noiseratio.

Page 885: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The code to compute thedominant cycle using thephaseaccumulationmethodisgiveninCodeListing14-5.

CodeListing14-5.EasyLanguage

CodetoComputetheDominantCycleUsingthe

Phase

Page 886: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

AccumulationMethod

{MeasuringtheDominantCycleusingPhaseAccumulation©2013JohnF.Ehlers}

Inputs:LPPeriod(20);

Vars:alpha1(0),HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),QFilt(0),Real(0),Quad(0),Imag(0),

Page 887: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

IPeak(0),QPeak(0),Phase(0),DeltaPhase(0),InstPeriod(0),count(0),PhaseSum(0),DomCycle(0);

//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48bars

alpha1=(Cosine(.707*360/48)+Sine(.707*360/48)-1)/Cosine(.707*360/48);

HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*(1-alpha1)*HP[2];

//SmoothwithaSuperSmootherFilterfromequation3

a1=expvalue(-1.414*3.14159/LPPeriod);

b1=2*a1*Cosine(1.414*180/LPPeriod);

c2=b1;

c3=-a1*a1;

Page 888: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

c1=1-c2-c3;Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

IPeak=.991*IPeak[1];

IfAbsvalue(Filt)>IPeakThenIPeak=AbsValue(Filt);Real=Filt/IPeak;

Quad=(Real-Real[1]);

QPeak=.991*QPeak[1];

IfAbsvalue(Quad)>QPeakThenQPeak=AbsValue(Quad);Imag=Quad/QPeak;

//UseArcTangenttocomputethecurrentphaseIfAbsValue(Real)>0thenPhase=ArcTangent(AbsValue(Imag/Real));

//ResolvetheArcTangentambiguity

IfReal<0andImag>0thenPhase=180-Phase;

IfReal<0andImag<0thenPhase=180+Phase;

IfReal>0andImag<0thenPhase=360-Phase;

//Computeadifferentialphase,resolvephasewraparound,andlimitdeltaphaseerrors

Page 889: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

DeltaPhase=Phase[1]-Phase;

IfPhase[1]<90andPhase>270thenDeltaPhase=360+Phase[1]-Phase;

//LimitDeltaPhasetobewithintheboundsof10barand48barcycles}

IfDeltaPhase<10thenDeltaPhase=10;

IfDeltaPhase>48thenDeltaphase=48;

//SumDeltaPhasestoreach360degrees.Thesumistheinstantaneousperiod.

InstPeriod=0;

PhaseSum=0;

Forcount=0to40beginPhaseSum=PhaseSum+DeltaPhase[count];IfPhaseSum>360andInstPeriod=0thenbeginInstPeriod=count;End;End;

//ResolveInstantaneousPerioderrorsandsmooth

IfInstPeriod=0thenInstPeriod=InstPeriod[1];DomCycle = c1*(InstPeriod+InstPeriod[1])/2+c2*DomCycle[1]+c3*DomCycle[2];

Page 890: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Plot1(DomCycle);

Page 891: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■HomodyneThe third algorithm forcomputing the dominantcycle is the homodyneapproach. Homodyne meansthe signal is multiplied byitself. More precisely, wewanttomultiplythesignalofthe current bar with thecomplex value of the signalone bar ago. The complexconjugate is, by definition, a

Page 892: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

complex number whose signof the imaginary componenthasbeenreversed.Expressingthe signal in polarcoordinates,thearithmeticis:

The interesting result isthatwegetboththesquareofthe signal amplitude and theangular frequency (2π /Period) from the productbecausethedifferenceintimebetweensamples(tn−tn−1)is

Page 893: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

justonebar.Inprinciple,thismeans that we can get theinstantaneous cycle period injust two successive samples.The added benefit is that wealso get the square of thesignal amplitude. Thecalculations are carried outusing the in-phase andquadraturecomponentsratherthanconvertingthemtopolarcoordinates. Either way, theresultswillbethesame.

Page 894: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Since thedifferentialangleis small in radian measure,the angle, the tangent of theangle and the arctangent ofthe angle are allapproximately the same.Therefore,thedominantcycleis computed by dividing 2πby the ratio of the imaginarycomponent to the realcomponent.Ideally,theanglecannot be negative becausetime cannot run backwards.Frankly, the purpose of the

Page 895: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

smoothing filter is to covertheerraticcalculationscausedbynoise.The code to compute the

dominant cycle using thehomodynemethodisgiveninCodeListing14-6.

CodeListing14-6.EasyLanguage

CodetoComputetheDominant

Page 896: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CycleUsingtheHomodyneMethod

{MeasuringtheDominantCycleusingaHomoDyneDiscriminator©2013JohnF.Ehlers}

Inputs:LPPeriod(20);

Vars:alpha1(0),HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),QFilt(0),

Page 897: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Real(0),Quad(0),Imag(0),IPeak(0),QPeak(0),Re(0),Im(0),Period(0),DomCycle(0);

//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48bars

alpha1=(Cosine(.707*360/48)+Sine(.707*360/48)-1)/Cosine(.707*360/48);

HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*(1-alpha1)*HP[2];

//SmoothwithaSuperSmootherFilterfromequation3

a1=expvalue(-1.414*3.14159/LPPeriod);

b1=2*a1*Cosine(1.414*180/LPPeriod);

c2=b1;

Page 898: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

c3=-a1*a1;

c1=1-c2-c3;Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

IPeak=.991*IPeak[1];

IfAbsvalue(Filt)>IPeakThenIPeak=AbsValue(Filt);Real=Filt/IPeak;

Quad=(Real-Real[1]);

QPeak=.991*QPeak[1];

IfAbsvalue(Quad)>QPeakThenQPeak=AbsValue(Quad);Imag=Quad/QPeak;

Re=Real*Real[1]+Imag*Imag[1];

Im=Real[1]*Imag-Real*Imag[1];IfIm<>0andRe<>0ThenPeriod=6.28318/AbsValue((Im/Re));

IfPeriod<10ThenPeriod=10;

IfPeriod>48ThenPeriod=48;DomCycle = c1*(Period+Period[1])/2+c2*DomCycle[1]+c3*DomCycle[2];

Page 899: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Plot1(DomCycle);

Page 900: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Key PointstoRemember

1. The classic Hilberttransformer uses atruncatedFIRfilter.2. The classic Hilberttransformer cannot beused for tradingbecausethe FIR filter introducesa large amount of lag,and shortening the FIR

Page 901: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

filter introduces largeamplitude variationsacrossthepassband.3. A modified Hilberttransformer can becreated using a one-bardifference to establishphase quadrature andAGC to provideamplitudecompensation.4. The Hilberttransformer indicatorprovides predictive

Page 902: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

turning points for swingtrading. Thesepredictionscanbewrongif a new trend isestablished rather than anewswing.5. Using the Hilberttransformer to computethedominantcycleisthepricedataisnotadvised.

Page 903: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CHAPTER15

IndicatorTransforms

“Now I see,” said Tomblindly.

Page 904: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

An indicator transform is ameans to shape the indicatorto aid interpretation and useof the indicator itself. Otherthan shaping the display,these transforms have noimpact on the indicator. Forexample, they induce no lag.While relatively trivial toimplement, these transformshave a huge impact on theinterpretation and use of theindicators. There are

Page 905: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

primarily three indicators ofinterest to traders: the Fishertransform, the inverse Fishertransform, and the cubetransform. Each has itspreferred application, whichwedescribeinthischapter.

Page 906: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ FisherTransformAcommon fallacy in theuseof technical indicators is thattheir probability distributionfollows a normal, orGaussian, probabilitydistribution. That just is notso, as you can prove foryourself by analyzing areasonableamountofdata. If

Page 907: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

thedatadonothaveanormalprobability distribution, thenthe calculation of a standarddeviation is based on a falsepremise. The purpose of theFisher transform is to takeany indicator having anominally zero mean andbounded between the limitsof −1 to +1 and convert theamplitude so that thetransformed indicator has anapproximate normalprobabilitydistribution.

Page 908: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Plottinganindicatorscaledto a normal probabilitydistribution has a hugeadvantage on indicatorinterpretation. If thetransformed indicator has avalueof−1, ithasavalueofnegative one standarddeviation and therefore thereis a32percent chancepriceswill go lower. If thetransformed indicator has avalueof−2, ithasavalueofnegative two standard

Page 909: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

deviations, and thereforethere is only an 8 percentchance prices will go lower.This is a high-probabilitybuyingopportunity.Atalevelof−3,thenegative3standarddeviations means there isonlya2percentchanceoftheprices going lower. Thetransformed values aresymmetrical, so positivedeviations are high-probability indications toexita long position or to sell

Page 910: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

short.The equation for a Fisher

transformis

Since an input value ofunitycancausetheratiotogoto infinity, the inputmust belimited to 0.999, whichcorresponds to an output onthe order of three standarddeviations. Similarly, theargument of the natural

Page 911: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

logarithm cannot be allowedtogotozero,andsotheinputmust also be limited at−0.999.The transfer response of

theFishertransformisshownin Figure 15.1. The straightline shows the range ofinputs, and the curved lineshows the correspondingrange of outputs. When theinputs are less than anabsolute value of 0.5, the

Page 912: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

outputs are almost the sameas the inputs.However, thereis a greater and greatermagnification of the outputsas the inputs approach theabsolute value of 1. It is thisnonlinear magnification thatproduces the “long tails” inthe output probabilitydistribution, thuscreating theresulting normal probabilitydistribution.

Figure15.1Transfer

Page 913: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ResponseoftheFisherTransformShowsGreaterMagnificationoftheOutputsastheInputsApproachanAbsoluteValueof1

Page 914: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

To implement the Fisher

Page 915: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

transform on the adaptiveRSI, replace the plotstatements of Code Listing11-1with the followingcodefragment:

CodeListing15-1.EasyLanguage

CodeFragmenttoAddtheFisherTransformtotheAdaptiveRSI

Page 916: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

IndicatorVars:TranslatedRSI(0),AmplifiedRSI(0),Fish(0);

TranslatedRSI=2*(MyRSI-.5);

AmplifiedRSI=1.5*TranslatedRSI;

IfAmplifiedRSI>.999ThenAmplifiedRSI=.999;

IfAmplifiedRSI<-.999ThenAmplifiedRSI=-.999;

Fish=.5*Log((1+AmplifiedRSI)/(1-AmplifiedRSI));

Plot1(Fish);

Plot2(2);

Plot6(-2);

Page 917: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ThevariableMyRSIrangesbetween zero and one, andthereforetoaccommodatetheconditions for the Fishertransform, this variable mustbe translated and dilated torange between −1 and +1. IftheMyRSI variable does notrange fullybetweenzeroandone,youcanshorten theRSIlookback period to be lessthan half the measureddominant cycle, or you cansimply multiply it by a

Page 918: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

magnificationfactorasIhavedone in the code fragment.The amplifying factor wasselectedtomaketheindicatorrarely exceed the two sigmapoints in the output. TheamplifiedRSI is then limitedto be within the range of−0.999 to +0.999 to avoid acomputer crash, and then isused to compute the Fishertransform. The plus andminus twostandarddeviationlevels are included in the

Page 919: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

indicatordisplay.AnexampleoftheadaptiveRSIusingtheFisher transform is shown inFigure 15.2. The trend up isheralded by the Fisherizedindicator's falling below −2.Then, the trend down issignaled by the Fisherizedindicator rising above +2.These major turning pointsare relatively rare events andare perhaps best used inassociation with trendtrading.

Page 920: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure15.2AdaptiveRSIwithFisherTransformClearlyIdentifiesMajorTurningPoints

Page 921: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Since the Stochastic and

Page 922: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

commodity channel index(CCI) indicators measurerelativepositioninachannel,theytendtobeneartheupperor lower limitsduring trends.That means that they do nothaveazeromeanintheshortrun and therefore are notgood candidates on which toapplytheFishertransform.Aband-pass filter would be amuchbettercandidate,butthemajor cyclic turning pointsare already easy to identify

Page 923: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

and don't require a morecomplexstatisticalapproach.

Page 924: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ InverseFisherTransformWhereastheFishertransformexpands the base indicatornear the extremes, thepurposeof the inverseFishertransform is to compress theindicatorintheseregions.Bycompressing values near the

Page 925: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

extremes many extraneousand irrelevant wiggles areremoved from the indicator,making interpretation of therealmeaning of the indicatorbefarsimpler.Inasense,theinverse Fisher transform actsasasoftlimiter.The equation for the

inverseFishertransformis

The input may have as

Page 926: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

largeavalueasdesired.Iftheinput values are very large,then theexponential terms inboth the numerator anddenominator are very largecompared to one, and so theoutput is approximately 1. Ifthe input values are verylarge, but negative, then theexponential terms inboth thenumerator and denominatorare very small compare toone, with the result that theoutput is approximately −1.

Page 927: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

TheKintheexpressionisanoptional amplifying termbecause conventionalindicators already fallbetween the limits of−1 and+1,andsoamplifyingthemisnecessarytoreapthebenefitsof the soft limiting of theinverseFishertransform.The transfer response of

the inverse Fisher transformis shown inFigure15.3. Theinputvaluesareshownbythe

Page 928: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

straight line, and the outputvalues are shown by thecurved line. This graphicalrepresentation shows howlarger and larger absolutevalues of the input arecompressed to essentially beunity.

Figure15.3TransferResponseoftheInverseFisherTransformShowstheCompressionofLargerValuesoftheInput

Page 929: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

To implement the inverse

Page 930: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Fisher transform on anadaptive Stochastic indicator,replacetheplotstatementsofCode Listing 11-2 with thecode fragmentgiven inCodeListing15-2.Ihavechosentoamplify the adaptiveStochastic by a factor of 3when taking the inverseFishertransform.

CodeListing15-2.EasyLanguage

Page 931: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CodeFragmenttoImplementtheInverseFisher

TransformontheAdaptiveStochasticIndicator

Vars:IFish(0);

Value1 = 2*(AdaptiveStochastic-.5);IFish=(ExpValue(2*3*Value1)-1)/(ExpValue<(2*3*Value1)+1);

Page 932: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Plot1(IFish);

Plot4(.9*IFish[1]);

I have also included atrigger line,which is just theinverse Fisher transformdelayed by one bar andattenuated to90percent.Thecrossings of the inverseFisher transform line and thetrigger lineprovideclearandunequivocal indications forthe buy and sell points, as

Page 933: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

demonstrated in the exampleofFigure15.4.

Figure15.4TheInverseFisherTransformoftheAdaptiveStochasticIndicatorGivesClearandUnambiguousIndicationsoftheProperBuyandSellPoints

Page 934: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The use of the inverse

Page 935: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Fisher adaptive Stochasticindicator involves thecrossings of the inverseFisher line and the triggerline.WhentheinverseFisherline crosses over the triggerline, then buy. When theinverse Fisher line crossesunder the trigger line, thensell short, or if you choose,exitthelongposition.The inverse Fisher

transform should be one of

Page 936: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the biggest weapons in yourarsenal of trading indicatorsandstrategies.Itsuseasasoftlimiter is universal and canhelp remove many of thedistracting and irrelevantsquiggles in your indicators.Theonlyconstraintshouldbethat the original input has anearlyazeromean.Youmayneed to amplify the input toattain the desiredcompression at the output. Ifyou want a simple “digital”

Page 937: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

output, just amplify the inputbyalargeamount.

Page 938: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ CubeTransformThe purpose of the cubetransform is to compress thesignals near zero of anindicatorthatswingsbetweenthe limitsof−1and+1. Thisishandyforanindicatorsuchas the adaptive band-passfilter where you areconcerned only with the

Page 939: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

larger swings, and thesquiggles in the middle aremerely distractions. Thetransform consists of merelycubing the indicator values.Doingthis,thevaluesnear+1and−1arenearlyunchanged,but the smaller absolutevaluesareseverelyreducedinamplitude. Of course, thisonly works if the effects ofspectral dilation have beenremovedbyaroofingfilterorsome equivalent technique.

Page 940: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The cubing of the display isonly effective when theoriginal indicator has anominally zero mean. Thetransfer response of the cubetransform is shown in Figure15.5. In this figure, the inputvalues are shown by thestraight line and the outputvalues are shown by thecurvedline.

Figure15.5TheCubeTransformCompresses

Page 941: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

SmallerValuesoftheInput

Page 942: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The effect of the cubetransform is shown in Figure15.6, where the adaptiveband-pass filter is shown inthe first subgraph, and theadaptiveband-passfilterwiththe cube transform is shownin the second subgraph. Thepurposeofthecubetransformistoclarifythemajorswingsby compressing thedistractions of the smallerswingvalues.

Page 943: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Figure15.6TheCubeTransformClarifiesSwingingSignalsbyCompressingtheSmallerAmplitudeSwings

Page 944: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 945: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Key PointstoRemember

1. The purpose of atransformer is shape theindicator to aidinterpretationanduseoftheindicatoritself.2. Transformers do notinducelag.3.AFisher transformofan indicator swinging

Page 946: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

between−1and+1witha nominal zero meanplots that indicator interms of standarddeviations with a nearlynormal probabilitydistribution.4. An inverse Fishertransform acts as a softlimiter to removeextraneous wiggles inindicators have anominalzeromean.

Page 947: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

5. A cube transformcompresses the smallervalues of an indicatorswinging between −1and+1.

Page 948: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CHAPTER16

SwamiCharts“Now that's a hotdisplay,” said Tomcoolly.

Page 949: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Technical indicators fortrading are long on precisionbut short on accuracy. Forexample, you know exactlywhenarelativestrengthindex(RSI) crosses the 80 percentthreshold.Inmyopinion,thisprecision property ofindicators gives traders afalse sense of security andobscures the fact thatindicators are basicallydisplays of a statistical

Page 950: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

process.Further,mosttradersdon't have a clue regardingthe proper setting of theindicator lookback period.The end result is that theprecise indicator can showyouprettymuchanythingyouwant, dependingonhowyousettheparameters.Partofthesolution, as discussed inChapter 11, is to make theindicator adaptive to themeasuredcycleperiod.

Page 951: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

In this chapter, I describeanother completely differentperspective, which is toaccept that indicators areinherently inaccurate and abetter approach is to look atthat indicatorovera rangeoflookback periods and viewthe short-term movement inthecontextofthelonger-termindictor results. In a sense,the indicator isusedas fuzzylogic. This is the purpose ofSwamiCharts.

Page 952: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Almost any oscillator-typeindicator can be plotted as aSwamiChart. If you do this,youwillquicklyisolatethoseindicators that have the bestperformance. You will alsofind, as I did, that there aresome indicators that indicatenothing at all. As a quickvisual example, Figure 16.1shows a conventional RSIandaconventionalStochasticonthesamechart.Theyseemto be giving different

Page 953: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

information. Part of theanswer is that neither hasbeen compensated forSpectralDilation.The restofthe answer is that whenviewed in context, these twoindicatorsshowjustaboutthesamething.

Figure16.1RSIandStochasticIndicatorsSeemtoImpartDifferentInformation

Page 954: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 955: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■SwamiChartsOverviewSwamiCharts retain the corefunctionality of the technicalindicators with which you'realready familiar, whilepacking much moreinformation into an easy-to-interpretheatmapchart.With

Page 956: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

SwamiCharts, you nowvisualize each indicator overa range of lookback periodsto revealabetterviewof theindicator's truer meaning incontext.SwamiCharts provide a

better solution because youcan now visualize contextover a wide range oflookbackperiods.Trendsandcycles emerge moresuccinctly,whilecontinuation

Page 957: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

patternsandreversalsbecomeeasier to identify.SwamiCharts solves the datalookback problem byenabling you to viewmarketconditions at a glance, afeature that will dramaticallyfacilitateyourtrading.SwamiCharts condenses

muchmoreinformationabouteach indicator's truemeaninginto an easy-to-interpret heatmap chart. SwamiCharts

Page 958: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

indicators are created bycomputing the technicalindicator multiple times overa range of lookback periods.The vertical scale of theSwamiChart indicator is thatrange of those lookbackperiods.Foreachdatabarandfor each lookback period thevalue of the indicator iscomputedintheconventionalway. After the indicator iscomputed, a color value isassigned to the matrix

Page 959: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

location defined by the barlocation in the horizontalplaneandthelookbackperiodin the vertical plane. Thecomplete matrix looks like aheatmapwhen drawn belowthe price bars in a subgraph.Theresultingbasicdisplay iseasy to interpret. Greenmeans increasing values, redmean decreasing values, andyellow means intermediatevalues.That is, the heatmapis a so-called “stoplight”

Page 960: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

chart.

Page 961: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■SwamiChartsRSIThe RSI indicator wasdescribed in Chapter 11,wherewemade the indicatoradaptive to the measureddominant cycle. In this case,we compute multiple RSIsover the range of lookback

Page 962: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

periodsofinterestandplotallof them as a heat map. TheSwamiCharts RSI isdescribed with reference tothe EasyLanguage code inCodeListing16-1.

CodeListing16-1.EasyLanguage

CodetoComputetheSwamiCharts

RSI

Page 963: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

{SwamiChartsRSI©2013JohnF.Ehlers

}Vars:alpha1(0),HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),Lookback(0),ClosesUp(0),ClosesDn(0),count(0),Denom(0),Color1(0),Color2(0),Color3(0);

Arrays:Ratio[48,2](0),MyRSI[48,3](0);

//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48bars

Page 964: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

alpha1=(Cosine(.707*360/48)+Sine(.707*360/48)-1)/Cosine(.707*360/48);

HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*(1-alpha1)*HP[2];

//SmoothwithaSuperSmootherFilterfromequation3

a1=expvalue(-1.414*3.14159/10);

b1=2*a1*Cosine(1.414*180/10);

c2=b1;

c3=-a1*a1;

c1=1-c2-c3;Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

ForLookback=5to48Begin//rangeincludeshalftheshortestperiodofinterestRatio[Lookback,2]=Ratio[Lookback,1];MyRSI[Lookback,3]=MyRSI[Lookback,2];MyRSI[Lookback,2]=MyRSI[Lookback,1];ClosesUp=0;

Page 965: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ClosesDn=0;Forcount=0toLookback-1BeginIfFilt[count]>Filt[count+1]ThenClosesUp=ClosesUp+(Filt[count]-Filt[count+1]);IfFilt[count]<Filt[count+1]ThenClosesDn=ClosesDn+(Filt[count+1]-Filt[count]);End;Denom=ClosesUp+ClosesDn;IfDenom<>0ThenRatio[Lookback,1]=ClosesUp/Denom;//SmoothMyRSIwitha10barSuperSmoother MyRSI[Lookback, 1] = c1*(Ratio[Lookback,1]+Ratio[Lookback,2])/2+c2*MyRSI[Lookback,2]+c3*MyRSI[Lookback,3];//EnsureMyRSIdoesnotfalloutsidecolorlimitsIfMyRSI[Lookback,1]<0ThenMyRSI[Lookback,1]=0;IfMyRSI[Lookback,1]>1ThenMyRSI[Lookback,1]=1;End;

//PlotasaHeatmap

//Plottingdatamustrangebetween0and1

ForLookback=5to48Begin//StopLightColorsIfMyRSI[Lookback,1]>=.5ThenBegin Color1 = 255*(2-2*MyRSI[Lookback,1]);Color2=255;Color3=0;EndElseIfMyRSI[Lookback,1]<.5ThenBeginColor1=255;

Page 966: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Color2=255*2*MyRSI[Lookback,1];Color3=0;End;IfLookback=5ThenPlot5(5,“S10”,RGB(Color1,Color2,Color3),0,4);IfLookback=6ThenPlot6(6,“S10”,RGB(Color1,Color2,Color3),0,4);IfLookback=7ThenPlot7(7,“S10”,RGB(Color1,Color2,Color3),0,4);IfLookback=8ThenPlot8(8,“S10”,RGB(Color1,Color2,Color3),0,4);IfLookback=9ThenPlot9(9,“S10”,RGB(Color1,Color2,Color3),0,4);IfLookback=10ThenPlot10(10,“S10”,RGB(Color1,Color2,Color3),0,4);IfLookback=11ThenPlot11(11,“S11”,RGB(Color1,Color2,Color3),0,4);IfLookback=12ThenPlot12(12,“S12”,RGB(Color1,Color2,Color3),0,4);IfLookback=13ThenPlot13(13,“S13”,RGB(Color1,Color2,Color3),0,4);IfLookback=14ThenPlot14(14,“S14”,RGB(Color1,Color2,Color3),0,4);IfLookback=15ThenPlot15(15,“S15”,RGB(Color1,Color2,Color3),0,4);IfLookback=16ThenPlot16(16,“S16”,RGB(Color1,Color2,Color3),0,4);IfLookback=17ThenPlot17(17,“S17”,RGB(Color1,Color2,Color3),0,4);IfLookback=18ThenPlot18(18,“S18”,RGB(Color1,Color2,Color3),0,4);IfLookback=19ThenPlot19(19,“S19”,RGB(Color1,Color2,Color3),0,4);IfLookback=20ThenPlot20(20,“S20”,RGB(Color1,Color2,Color3),0,4);IfLookback=21ThenPlot21(21,“S21”,RGB(Color1,Color2,Color3),0,4);IfLookback=22ThenPlot22(22,“S22”,RGB(Color1,Color2,Color3),0,4);IfLookback=23ThenPlot23(23,“S23”,RGB(Color1,Color2,Color3),0,4);IfLookback=24ThenPlot24(24,“S24”,RGB(Color1,Color2,Color3),0,4);IfLookback=25ThenPlot25(25,“S25”,RGB(Color1,Color2,Color3),0,4);IfLookback=26ThenPlot26(26,“S26”,RGB(Color1,Color2,Color3),0,4);IfLookback=27ThenPlot27(27,“S27”,RGB(Color1,Color2,Color3),0,4);IfLookback=28ThenPlot28(28,“S28”,RGB(Color1,Color2,Color3),0,4);IfLookback=29ThenPlot29(29,“S29”,RGB(Color1,Color2,Color3),0,4);IfLookback=30ThenPlot30(30,“S30”,RGB(Color1,Color2,Color3),0,4);

Page 967: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

IfLookback=31ThenPlot31(31,“S31”,RGB(Color1,Color2,Color3),0,4);IfLookback=32ThenPlot32(32,“S32”,RGB(Color1,Color2,Color3),0,4);IfLookback=33ThenPlot33(33,“S33”,RGB(Color1,Color2,Color3),0,4);IfLookback=34ThenPlot34(34,“S34”,RGB(Color1,Color2,Color3),0,4);IfLookback=35ThenPlot35(35,“S35”,RGB(Color1,Color2,Color3),0,4);IfLookback=36ThenPlot36(36,“S36”,RGB(Color1,Color2,Color3),0,4);IfLookback=37ThenPlot37(37,“S37”,RGB(Color1,Color2,Color3),0,4);IfLookback=38ThenPlot38(38,“S38”,RGB(Color1,Color2,Color3),0,4);IfLookback=39ThenPlot39(39,“S39”,RGB(Color1,Color2,Color3),0,4);IfLookback=40ThenPlot40(40,“S40”,RGB(Color1,Color2,Color3),0,4);IfLookback=41ThenPlot41(41,“S41”,RGB(Color1,Color2,Color3),0,4);IfLookback=42ThenPlot42(42,“S42”,RGB(Color1,Color2,Color3),0,4);IfLookback=43ThenPlot43(43,“S43”,RGB(Color1,Color2,Color3),0,4);IfLookback=44ThenPlot44(44,“S44”,RGB(Color1,Color2,Color3),0,4);IfLookback=45ThenPlot45(45,“S45”,RGB(Color1,Color2,Color3),0,4);IfLookback=46ThenPlot46(46,“S46”,RGB(Color1,Color2,Color3),0,4);IfLookback=47ThenPlot47(47,“S47”,RGB(Color1,Color2,Color3),0,4);IfLookback=48ThenPlot48(48,“S48”,RGB(Color1,Color2,Color3),0,4);

End;

Since the MyRSI iscomputed for all values over

Page 968: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the range of lookbackperiods,itmustbeanarrayinEasyLanguage rather than avariable. The RSI iscomputed relative to theoutput of the roofing filterrather than price closes toeliminate the effects ofSpectral Dilation. After thecomputation of the ratio, theindicator is smoothed in aSuperSmoother filter, so wemust create the three mostrecent instances ourselves in

Page 969: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the code. This is becauseEasyLanguage retainshistoricalvalues forvariablesbut not for arrays. In fact,ratiomustbeanarrayalsoforthe same reasons. Thecoefficients for the 10-barSuperSmoother filter arecomputed and are the samefor all lookback periods, andso can be outside thelookback loop to make thecalculations a little moreefficient.

Page 970: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Now, let's see how theSwamiCharts RSI indicatorslook in Figure 16.2. Wow!Now you can see the entiremarket activity at a glance.Theshort-termdownturnsareshown in the context ofcaution to upside trends.When themarket turnsdownthe short-term red areasexpand into the longer-termdown market. Then, at theright-hand edge of the chart,you can see the short-term

Page 971: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

risingareaexpandingintothelonger-term cautionary areas.The RSI naturallyequivocates at the longerlookbackperiodsbecause thevalueoftheclosesupstarttoapproach the value of closesdown over the longeraverage.

Figure16.2SwamiChartsRSIContainsMuchMoreInformationthantheStandardRSI

Page 972: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 973: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■SwamiChartsStochasticThe Stochastic indicator wasalsodescribed inChapter11,wherewemade the indicatoradaptive to the measureddominant cycle. In this case,we compute multipleStochastics over the range of

Page 974: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

lookback periods of interestandplotallofthemasaheatmap. The SwamiChartsStochastic is described withreference to theEasyLanguage code in CodeListing16-2.

CodeListing16-2.EasyLanguage

CodetoComputetheSwamiCharts

Page 975: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Stochastic{SwamiChartsStochastic©2013JohnF.Ehlers)

Vars:alpha1(0),HP(0),a1(0),b1(0),c1(0),c2(0),c3(0),Filt(0),Lookback(0),count(0),HighestC(0),LowestC(0),Color1(0),Color2(0),Color3(0);

Arrays:Ratio[48,2](0),

Page 976: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Stoc[48,3](0);

//Highpassfiltercycliccomponentswhoseperiodsareshorterthan48bars

alpha1=(Cosine(.707*360/48)+Sine(.707*360/48)-1)/Cosine(.707*360/48);

HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close-2*Close[1]+Close[2])+2*(1-alpha1)*HP[1]-(1-alpha1)*(1-alpha1)*HP[2];

//SmoothwithaSuperSmootherFilterfromequation3

a1=expvalue(-1.414*3.14159/10);

b1=2*a1*Cosine(1.414*180/10);

c2=b1;

c3=-a1*a1;

c1=1-c2-c3;Filt = c1*(HP+HP[1])/2+c2*Filt[1]+c3*Filt[2];

//ComputeStochasticforeachlookbackperiod

Page 977: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ForLookback=5to48BeginRatio[Lookback,2]=Ratio[Lookback,1];Stoc[Lookback,3]=Stoc[Lookback,2];Stoc[Lookback,2]=Stoc[Lookback,1];HighestC=Filt;LowestC=Filt;Forcount=0toLookback-1BeginIfFilt[count]>HighestCthenHighestC=Filt[count];IfFilt[count]<LowestCthenLowestC=Filt[count];End;Ratio[Lookback,1]=(Filt-LowestC)/(HighestC-LowestC);//Smoothwitha10barSuperSmoother.Coefficientsarecomputedabove Stoc[Lookback, 1] = c1*(Ratio[Lookback,1]+Ratio[Lookback,2])/2+c2*Stoc[Lookback,2]+c3*Stoc[Lookback,3];//EnsureStoc[Lookback,1]doesnotexceedthe0to1limitsIfStoc[Lookback,1]<0ThenStoc[Lookback,1]=0;IfStoc[Lookback,1]>1ThenStoc[Lookback,1]=1;End;

//PlotasaHeatmap

ForLookback=5to48Begin//StopLightColorsIfStoc[Lookback,1]>=.5ThenBegin Color1 = 255*(2-2*Stoc[Lookback,1]);Color2=255;Color3=0;End

Page 978: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ElseIfStoc[Lookback,1]<.5ThenBeginColor1=255;Color2=255*2*Stoc[Lookback,1];Color3=0;End;IfLookback=5ThenPlot5(5,“S10”,RGB(Color1,Color2,Color3),0,4);IfLookback=6ThenPlot6(6,“S10”,RGB(Color1,Color2,Color3),0,4);IfLookback=7ThenPlot7(7,“S10”,RGB(Color1,Color2,Color3),0,4);IfLookback=8ThenPlot8(8,“S10”,RGB(Color1,Color2,Color3),0,4);IfLookback=9ThenPlot9(9,“S10”,RGB(Color1,Color2,Color3),0,4);IfLookback=10ThenPlot10(10,“S10”,RGB(Color1,Color2,Color3),0,4);IfLookback=11ThenPlot11(11,“S11”,RGB(Color1,Color2,Color3),0,4);IfLookback=12ThenPlot12(12,“S12”,RGB(Color1,Color2,Color3),0,4);IfLookback=13ThenPlot13(13,“S13”,RGB(Color1,Color2,Color3),0,4);IfLookback=14ThenPlot14(14,“S14”,RGB(Color1,Color2,Color3),0,4);IfLookback=15ThenPlot15(15,“S15”,RGB(Color1,Color2,Color3),0,4);IfLookback=16ThenPlot16(16,“S16”,RGB(Color1,Color2,Color3),0,4);IfLookback=17ThenPlot17(17,“S17”,RGB(Color1,Color2,Color3),0,4);IfLookback=18ThenPlot18(18,“S18”,RGB(Color1,Color2,Color3),0,4);IfLookback=19ThenPlot19(19,“S19”,RGB(Color1,Color2,Color3),0,4);IfLookback=20ThenPlot20(20,“S20”,RGB(Color1,Color2,Color3),0,4);IfLookback=21ThenPlot21(21,“S21”,RGB(Color1,Color2,Color3),0,4);IfLookback=22ThenPlot22(22,“S22”,RGB(Color1,Color2,Color3),0,4);IfLookback=23ThenPlot23(23,“S23”,RGB(Color1,Color2,Color3),0,4);IfLookback=24ThenPlot24(24,“S24”,RGB(Color1,Color2,Color3),0,4);IfLookback=25ThenPlot25(25,“S25”,RGB(Color1,Color2,Color3),0,4);IfLookback=26ThenPlot26(26,“S26”,RGB(Color1,Color2,Color3),0,4);IfLookback=27ThenPlot27(27,“S27”,RGB(Color1,Color2,Color3),0,4);IfLookback=28ThenPlot28(28,“S28”,RGB(Color1,Color2,Color3),0,4);

Page 979: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

IfLookback=29ThenPlot29(29,“S29”,RGB(Color1,Color2,Color3),0,4);IfLookback=30ThenPlot30(30,“S30”,RGB(Color1,Color2,Color3),0,4);IfLookback=31ThenPlot31(31,“S31”,RGB(Color1,Color2,Color3),0,4);IfLookback=32ThenPlot32(32,“S32”,RGB(Color1,Color2,Color3),0,4);IfLookback=33ThenPlot33(33,“S33”,RGB(Color1,Color2,Color3),0,4);IfLookback=34ThenPlot34(34,“S34”,RGB(Color1,Color2,Color3),0,4);IfLookback=35ThenPlot35(35,“S35”,RGB(Color1,Color2,Color3),0,4);IfLookback=36ThenPlot36(36,“S36”,RGB(Color1,Color2,Color3),0,4);IfLookback=37ThenPlot37(37,“S37”,RGB(Color1,Color2,Color3),0,4);IfLookback=38ThenPlot38(38,“S38”,RGB(Color1,Color2,Color3),0,4);IfLookback=39ThenPlot39(39,“S39”,RGB(Color1,Color2,Color3),0,4);IfLookback=41ThenPlot41(41,“S41”,RGB(Color1,Color2,Color3),0,4);IfLookback=42ThenPlot42(42,“S42”,RGB(Color1,Color2,Color3),0,4);IfLookback=43ThenPlot43(43,“S43”,RGB(Color1,Color2,Color3),0,4);IfLookback=44ThenPlot44(44,“S44”,RGB(Color1,Color2,Color3),0,4);IfLookback=45ThenPlot45(45,“S45”,RGB(Color1,Color2,Color3),0,4);IfLookback=46ThenPlot46(46,“S46”,RGB(Color1,Color2,Color3),0,4);IfLookback=47ThenPlot47(47,“S47”,RGB(Color1,Color2,Color3),0,4);IfLookback=48ThenPlot48(48,“S48”,RGB(Color1,Color2,Color3),0,4);

End;

SincetheStociscomputedfor all values over the range

Page 980: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

of lookback periods, it mustbeanarray inEasyLanguagerather than a variable. TheStochastic is computed usingtheoutputoftheroofingfilterrather than price closes toeliminate the effects ofSpectral Dilation. After thecomputation of the ratio, theindicator is smoothed in aSuperSmoother filter, and sowemustcreatethethreemostrecent instances ourselves inthe code. This is because

Page 981: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

EasyLanguage retainshistoricalvalues forvariablesbut not for arrays. In fact,ratiomustbeanarrayalsoforthe same reasons. Thecoefficients for the 10-barSuperSmoother filter arecomputed and are the samefor all lookback periods, andso can be outside thelookback loop to make thecalculations a little moreefficient.

Page 982: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The SwamiChartsstochastic is shown inFigure16.3.TheprimarydifferencesfromtheSwamiChartsRSIisthat the display of the short-term downturns are morevivid, and there ismuch lessyellowatthelongerlookbackperiods. Thus, there is lessequivocation regarding themarketcalls.

Figure16.3SwamiChartsStochasticEquivocatesLess

Page 983: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

thantheSwamiChartsRSIRegardingTrends

Page 984: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Reviewing Figure 16.4,

Page 985: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

where the SwamiCharts RSIand the SwamiChartsStochasticarecompared, it isapparent that both indicatorsare telling you pretty muchthe same thing about themarket. This consistency ofviewpoint is hardly apparentin Figure 16.1, where thestandard versions of theindicatorsarecompared.

Figure16.4SwamiChartsRSIandSwamiChartsStochastic

Page 986: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

BasicallyRevealtheSameInformationaboutMarketActivity

Page 987: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 988: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Roll YourOwnSwamiChartsYou can write your ownSwamiCharts customindicator if you create thearrays for all lookbackperiods, scale the indicatorvalues to fall between 0 and1, and use the heat map

Page 989: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

display code without anyfurther changes except forinserting the names of thearrays in the color convertersectionofthecode.Notethatthe heatmap plotting routineis exactly the same for allthree examples in thischapter.If you wanted to make a

SwamiCharts commoditychannel index (CCI), forexample, you would only

Page 990: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

needtoadd100totheresult.This would make theindicatorrangebetween0and200. Then, divide by 200,with the end result that theindicator ranges between 0and1.Even if you never really

use a SwamiCharts indicatorfor trading it will beworthwhile to program yourfavorite indicator in theSwamiCharts format. This

Page 991: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

will enable you to comparethat indicator to others andassess its effectiveness.Having programmed anumber of indicators asSwamiCharts, I can tell youthattherearemorethanafewindicators that don't indicateanything at all. If you visitwww.StockSpotter.com orwww.SwamiCharts.com, youwill get a sneak preview ofsome of the advancedindicators I have created

Page 992: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

using the SwamiChartsmodel.

Page 993: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Key PointstoRemember

1. SwamiCharts giveyou “the view from30,000 feet.” That is,yougetabird's-eyeviewofmarketactivityfromaSwamiChartindicator.2. Many indicatorsbasically tell you thesamethingaboutmarket

Page 994: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

activity.3. A SwamiChartsrendition of an indicatorwill quickly reveal itsvalueorlackthereof.

Page 995: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CHAPTER17

Swing-TradingStrategies

“Writing tradingstrategies is simple,”

Page 996: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Tomsaideasily.

Well, I think Tom reallymeant that trading systemsshouldbesimple,butwritingeffective ones is not easy.Trading systems should besimple to avoid curve fittingto the data set on which thesystem is developed. Forexample, if you used oneyear's worth of daily data todevelop a system and yoursystem was written as a

Page 997: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

polynomialoforder250,thenyou could have theoreticallymatched that polynomialexactlytothedata.However,applying that polynomial toanother year's data wouldmost likely have disastrousresults. Therefore, keeping atrading strategy simpleimproves the likelihood thatthe strategy will be robustacross multiple symbols andmultiple time frames. If youuse few parameters in your

Page 998: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

system, it is less likely thestrategy is customized to thedataset.Given that the strategy is

simple, the next criterion isthat the entry and exit rulesbe predictive. Most rule-based strategies depend onindicators,setups,orpatterns.Sadly,allof thesedependonhistorical data and are betterat documenting what hashappened rather than

Page 999: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

predicting what will happen.Additionally, setups andpatterns are often based onjust a few observations andare therefore anecdotal orheuristic.Thefact thatsetupsor patterns do not havesufficient instances to bestatistically significant isusually overlooked.Therefore, finding apredictive indicator isprobably the most difficultpart of developing a trading

Page 1000: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

strategy.The majority of this book

describesadvancedfiltersandindicators to help yourtrading. Ultimately, theindicators are used as an aidto making buy and selldecisions, whether thedecisions are based ondiscretion or on analgorithmic rule set.Indicators use parameters.For example, a moving

Page 1001: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

average uses length of theaverage as a parameter. Thepower of modern tradingplatformsenablesyoutovarythe parameters to maximizetrading performance over theselecteddataset.Theprocessis called optimization. I canassureyouthat theprocessisanything but optimum andcanlullyouintoafalsesenseof confidence in yourprospective strategy. Theprocess of optimization

Page 1002: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

should include a sensitivityanalysiswhereyouvaryeachparameter by itself and thenview the performance over afullrangeoftheparameter.Ifthe optimization does notprovide a gentle peak so theparameter is effective over arange of settings, then yourcandidate strategy isguaranteed not to be robust.When testing your strategy,you should produce enoughtrades so the results are

Page 1003: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

statistically significant. Onerule of thumb is that youshouldhaveatleast30tradesforeachparameterusedintheprospective strategy. Forexample, if you use fourparameters in your strategy,you should examine theresults over at least 120trades. Ipersonally think thiscountisonthelowside.Nobody wants to lose

money on a trade, and stop-

Page 1004: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

loss criteria are often builtinto the strategy tominimizelosses. Remember, the nameof theprocedure is stop loss,and half that name is loss.Therefore, stop-loss rulesshouldbeused sparinglyandnot be imbedded so that thestoplossisanintegralpartofthestrategy.Myprocedure isto develop the strategywithouttheuseofastop-lossrule. After the main part ofthe strategy is satisfactory, I

Page 1005: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

then examine the maximumadverse excursionsencountered,andtheninsertastop-loss rule that limitsonlythe maximum losses withoutinterfering much with thewinningtrades.Thefinalgeneralaspectof

strategy development thatcannotbeoverlookedis“out-of-sample” testing.Youhaveundoubtedly developed thestrategy on a given data set

Page 1006: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

that consists of one symbolover a selected period oftime. Out-of-sample testingmeans that you apply yourtrading strategy to the samesymbol over a different timerange or apply your tradingstrategy to multiple differentsymbols,allofwhichisdonewithoutchangingparameters.If you reoptimize, you aresimply cheating, and you areonly cheating yourselfbecause you are bound to be

Page 1007: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

disappointedwhenyouapplyyour strategy to real trading.However, if you getsatisfactoryresultsdoingthis,then your strategy is robustand you can trade it withgreaterconfidence.

Page 1008: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ConventionalWisdomBy analogy to gambling,trading strategy performanceis most easily characterizedbypercentwinningtradesandprofit factor. Profit factor istheratioofgrosswinningstogross losses, comparable to

Page 1009: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the payout on a wager.Percent winning trades isself-explanatory. There is nounique combination of thesecharacteristics that lead to asuccessfultradingstrategy,sothetradingstyleisoptional.Trend following usually

means trying to identify anentry opportunity and thenexit the trade quickly if thetrend does not develop. Thismeansonecanmakea lotof

Page 1010: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

money on a few trades, butthere will be many losingtrades along the way.Therefore, trading the trendmeansbeingwillingtoacceptarelativelylowpercentageofwinning trades to achieve arelatively high profit factor.Alternatively, a trend tradermay elect to hold a positionthrough adversity to profit inthe long run. Holding tradesthrough adversity usuallymeans accepting large

Page 1011: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

drawdowns. In my view,trend trading works becausethe general market isunboundedandhasanupsidebias due to economic growthand inflation. I assert thatthere are no predictiveindicators for trends, andtherefore this styleof tradingdoes not fit my preferredprocess.Predictive indicators are

moreapplicabletoshort-term

Page 1012: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

processes such as swing ormomentum trading because,like the weather, predictingthe future is fragile andevanescent. If the indicatorsare indeed predictive, short-term trading is characterizedby a higher percentage ofwinning trades. The profitfactor of short-term trades isgenerally smaller becausespectral dilation limits theswings of the short-termmarket movements. The

Page 1013: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

general class of indicatorsthat support short-termtradingarecalledoscillators.Asdescribed inChapter6,

we are dealing with randomvariables when trying todescribe the market.Additionally, tradersgenerallyprefer to err on thesideofcautionbecauselossesare painful. Theseconsiderations lead to atrading philosophy thatwaits

Page 1014: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

for confirmation of theturning point of an indicatorbeforesignalingatradeentry.For example, theconventional Stochasticindicator rule could be “waituntil the oscillator crossesabove 20 percent beforemakinga longposition trade,and wait until the oscillatorcrosses below 80 percentbefore reversing to a shortposition trade.” This rule setwaits until the Stochastic

Page 1015: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

indicator moves in thedirection of the desired tradebefore making the tradedecision. As an example,assume the market has amonthly cycle. We wouldthen want to set the lengthparameter of a stochasticindicator to 10 because thereare roughly 10 days up and10 days down in a monthlycycle. When we invoke theconventional Stochasticindicator rule using the two-

Page 1016: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

pole Stochastic indicator ofChapter 7, we obtain theequity curve of Figure 17.1when applied to 10 years oftheS&PFuturesdata.

Figure17.1UsingaConventionalStochasticIndicatorRuleIsNotProfitable

Page 1017: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

These trading results areawful! Just a little analysiscan show what went wrong.

Page 1018: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

First, the roofing filter has alagofabout twobars,almostliketheSuperSmootherfilter.There is basically no lagcomputingtheStochastic,andthen there is another two-barlag of the SuperSmootherfilter that smooths theStochastic calculation. Sothereisatotaloffourbarsoflag just to compute theindicator. We don't get asignalforabout25percentofthe move in time, or about

Page 1019: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

three bars, after the turningpoint of the indicator.Further, we cannot make atradeentryuntil thedayafterthe signals are given.Therefore, our trade entriesandreversalsareabout8barslate on a 10-bar move. Thismeans we are trading almostexactly opposite of the waythe market is moving in amonthly cycle. This is thepenalty for waiting forconfirmation.

Page 1020: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Anticipatingthe TurningPointI think the bestway to tradean oscillator is to anticipatethe turning point and rely onthe statistical return to themean as being predictive. Iwrote apaperon this subjectthat was awarded the 2008

Page 1021: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Runner-Up Winner of theMarket TechnicianAssociation'sCharlesH.DowAward.1 In contrast to theconventional wisdom, theStochastic indicatoranticipation of the turningpoint trading rule would be“make a long position tradewhen the oscillator crossesbelow20percent,andreversetoashortpositiontradewhenthe oscillator crosses above

Page 1022: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

80percent.” The anticipationrule enables us to get thetradingsignalnominallythreebars before the turning pointoftheindicator.Westillhavethe four bars ofcomputationallagandtheonebarlagofentryfollowingthesignal.Therefore,ournet lagin making the trade entry isonly two bars relative to thereal turningpoint inthedata.In otherwords, out timing isjust about right. Invoking the

Page 1023: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

anticipated trading rule usingthe two-pole Stochasticindicator of Chapter 7, weobtain the equity curve ofFigure 17.2 when applied to10 years of the S&P Futuresdata.The anticipation rule is

equally applicable to mostoscillators. Exampleoscillatorsinthisbookwouldbe the band-pass filter inChapter 5 and the two-pole

Page 1024: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

RSI in Chapter 7. Theanticipation rule using thetwo-pole Stochastic indicatoris not intended to be acomplete trading system. Forexample, the 10-bar periodwas selected fordemonstration purposes. Thecomputation period of theindicatorcanbeoptimizedforagivensymboltoproducethebest timing for the tradeentries and exits. Further, nostop-loss values have been

Page 1025: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

used.

Figure17.2UsingtheAnticipatedStochasticIndicatorTurningPointRuleIsGenerallyProfitable

Page 1026: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The purpose of describingthe conventional wisdom ofwaiting for confirmation as

Page 1027: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

contrasted with anticipatingthe turning points with noother changes of parametersor rules is to sensitizeyou tothe impacts of computationallag.

Page 1028: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Sine WaveUniquenessAccording to Fourieranalysis, any complexwaveformcanbesynthesizedusing a combination of sinewave components. Thatmakesasinewaveaprimitivefrom which all patterns canbe formed. It isbest touseaprimitive in trading in the

Page 1029: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

interest of robustness.Further, it is difficult enoughjust tomeasureoneprimitiveinthemarketdata,letaloneacomplex set that createsanecdotal patterns. With asufficiently small bandwidth,theband-passfiltercreatesanoutput that can becharacterized as a sine wavehaving a slowly varyingamplitude and phase. Armedwiththisinformation,wecanexamine the use of sine

Page 1030: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

waves in providing tradingsignals.A sine wave can be

generatedbytheprojectionofa rotating phasor on itsvertical axis,2 as depicted inFigure 17.3. As the phasorrotates, the sine wave risesfrom zero to its maximum,backtozero,toitsminimum,andthenbacktozeroagaintocomplete one full cycleperiod.Notethatthe“tail”of

Page 1031: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the phasor is pinned at theorigin.Ifthetailofthephasorwere offset from the origin,then the sinewavewould bedistortedandwouldnothavea zero mean. Since marketdatahaveSpectralDilation,itis crucial that the SpectralDilation effects be removed,as discussed in Chapter 5,before working with thefilteredsinewave.

Figure17.3ASineWaveCan

Page 1032: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

BeGeneratedbyaRotatingPhasorThatIsPinnedattheOrigin

The position of the phasorat any instant in time is thephaseangleofthesinewave.

Page 1033: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Thereisaspecialrelationshipif the phase angle betweentwophasorsis90degrees,ora quarter of a cycle. Asshown in Figure 17.4, aphasor leading the sinewavephasor by 90 degrees createsacosinewave.Thefactthatacosine wave leads a sinewave by 90 degrees isimportantbecause itgivesusa way to artificially advancethe turning point of a band-passfilteroutputbyaquarter

Page 1034: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

of a cycle.By advancing thewaveformaquarterofacyclewe can negate or reduce thecomputationallagrequiredbythefilter.

Figure17.4ACosineWaveLeadsaSineWaveby90Degrees(aquarterofacycle)

Page 1035: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Fromthecalculusweknowthat the rateofchangeof thesinewave isexactlyacosinewave whose amplitude ismodifiedby the argument.Aone-bardifferencecreatestherate of change of the sine

Page 1036: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

wave, so an amplitude-correctedcosinewavecanbecomputed in code as (usingEasyLanguagenotation):

Yes,itreallyisthatsimpleto create a leading tradingsignal using the output of aband-pass filter if you knowor estimate the period of thesinewave.The object of using the

cosinewaveistocreateabuy

Page 1037: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

signal when the cosine waveis at or near a trough and tocreate a sell signal when thecosine wave is at or near apeak. One way to do this isby noting that the sine wavecrosses below zero when thecosine wave is at its troughand the sine wave crossesover zero when the cosinewave is at its peak. In otherwords,wecancreatebuyandsell signals simply based onthezerocrossingsof thesine

Page 1038: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

wave.It is a little more

conservative to create atrigger signal that lags thecosinewavebyabaror two,as shown in Figure 17.5.Usingadelayedcosinewaveas a trigger means givingback a little of the lag wehavestruggletominimize.

Figure17.5BuyandSellSignalsCanBeCreatedbyCrossoverswithaCosine

Page 1039: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

WaveandtheCosineWaveDelayedbyaBarorTwo

Page 1040: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound
Page 1041: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Some whipsaw trades canbe eliminated by using thezero crossings of the sinewave as an entry signal onlywhen confirmed by thecrossover of the cosinewavewith itself delayed by onebar.

Page 1042: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■SafetyValveSince effective swing tradesrequire anticipation of theprice turning, it is inevitablethat therewillbecaseswhenthepricekeepsongoingandbasically becomes a newtrend movement. In thesecases, your anticipation putsyouonexactlythewrongsideof the trade. You thereforeneed a rule that closes out a

Page 1043: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

position when losing tradeslikethisareexperienced.Youbasicallyhave twooptions toexitthetrade:basetheexitonpriceoron time in the trade.As a practicalmatter, I havenot found setting a stop lossto be an effective method ofexitingalosingtradeintheseconditions because the stopvalue has to be set so tightthatone iswhipsawedoutofa trade that ultimately couldturnouttobeprofitable.

Page 1044: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

If theexit rule fora losingtrade is based on price, onecan rely on the fact that theswing trade is expecting areversion to the mean, andthereforethepricearevaryingwithin a channel. If theanticipated reversal does notoccur,thenitislikelythattheprices will have a channelbreakout. A simple channelcan be established using aSuperSmoother filter on thehighs and lows of the price

Page 1045: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

bars. The channel can bewidened, if desired, byadding a fraction of theaverage bar range to thesmoothed high prices andsubtracting it from thesmoothed low prices. If youare in a long position tradeandthepricefallsoutsidethelowerchannel, thenit is timeto exit the trade at a loss,perhaps reversing to a shortposition to capture thedowntrend that you did not

Page 1046: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

anticipate.If the safety valve is

operatingon a time line, youmust be sensitive to theperiodicity of the cycle youare trading. For example, amonthly cycle generallyconsistsofa10-barmoveupfollowed by a 10-bar movedown. Therefore, yourexpected time to be in anygiven trade is about 10 bars.If you are not in a profitable

Page 1047: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

position by the time you areabout halfway into theexpected trade duration, it isprobably time to bail out ofthe trade at a loss. Being alittle more aggressive, youcan also establish a “quickout” rule that basically saysthat if you are not profitablein the first bar or two of atrade, exit the trade andwaitforabetteropportunity.I rely on technology for

Page 1048: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

trading and therefore do notrely on psychology much,even though psychologycertain has a place indiscretionarytrading.Thereisone unmistakablepsychologicalsignal toexitatrade. That is, if you eventhink about hoping a tradewill turnaroundandmoveinyourfavor,thenexitthetradeimmediately. Hope has anegativevalueintrading.

Page 1049: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Exiting aTradeWhen trading futures, it iscommon to take both longand short positions. Using aswing-trading strategy in thiscase, the exit of a longpositioncanbecometheentryfor the next short position.Alternatively, when tradinglong-onlypositions, the short

Page 1050: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

entry signal can become theexitsignalforalongpositiontrade.Using a short entry signal

asanexitsignalwhentradingstocks is less than optimalbecause the stock prices donot move symmetrically.There is an upside bias tostock prices, and pricesgenerallymoveslower to theupside than to the downside.Therefore, anticipating a

Page 1051: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

downside move often willresultinanearlyexittowhatotherwise could have been averyprofitabletrade.Abetterexitstrategywhen

trading stocks follows thegeneralprincipleof“letyourprofits run.”A practicalwayof implementingsuchanexitwould be to smooth theclosing prices with aSuperSmoother filter, and ifthefilteroutputcrossesbelow

Page 1052: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the filter output delayed byseveral bars, then exit thetrade. The smoothed priceswill always be above thedelayedsmoothpricesaslongas the prices are moving totheupside.Thus,youwillbekept in a profitable longposition longer. Of course,youwillgiveupalittleoftheaccrued profit when theprices turn down, but that isthe price you must pay toavoidthewhipsawexit.

Page 1053: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■StopLossMy experience is that a stoploss will decimate therobustness of a tradingstrategy if it is built into thestrategy and becomes anintegral part of it. Rather, astoplossisbestleftonlyasaguardagainstextremelylargelosses.Using a stop loss thisway will maintain therobustness of the core

Page 1054: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

strategyyouhavebuilt.Therearealargenumberofwaystoimplement a stop loss rule.The simple rule that worksformeistoletthestopvaluejust be a percentage of theentryprice. InEasyLanguagenotation, the stop-loss rulesare:

Page 1055: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

The PctLoss is an inputthat can be establisheddifferently from tickersymbol to ticker symbol. Ifind that a value from2 to 5percent works for moststocks. Since leverage isinvolved with futures, thepercentage input probablyshouldbealittlesmaller.

Page 1056: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■Evaluating aTradingStrategyIt is common to evaluate atradingstrategybylookingatits historical track record inthe form of an equity curve.This can lead to anunwarranted enthusiasm forthe trading strategy or, less

Page 1057: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

likely, abandonment of aperfectly good strategy. Thereason is that there isconsiderablevariabilityintheequity curves produced by astrategy having the givencharacteristicsofprofitfactorandpercentwinningtrades.By determining whether a

trade is a winner or a loserusingthepercentagewinsanda random number generator,applying the payout

Page 1058: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

probability toeach trade,andsumming the randomlyselected trades, you canprovide realistic expectationsfor the equity growthproducedbythesystem.Onlyin this sense canrandomization be introducedto establish performance.Simply winning or losing isnota randomoccurrence.AnExcel spreadsheet can showthe randomized cumulativetrading profits. Just press F9

Page 1059: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

and the spreadsheet willrecompute 500 randomizedtrades. You canindependently input differentvalues of profit factor andpercent winning trades tovisually assess the impact ofthesevariables.The variability in equity

curves, even for exampleshaving relatively high profitfactors and percent winningtrades, indicates the wisdom

Page 1060: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

of diversification in yourportfolio.Ifallthesymbolsinyourportfolioarestatisticallyindependent, then thedeviation in the equity curveistheoreticallyreducedbythesquare root of two for eachdoubling in the number ofelements. For example, youwould halve the deviation ofthe equity curve if you usedonly four symbols. Youwould halve the deviationagain if you used eight

Page 1061: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

symbols. Therefore, youwould quickly reach a pointof diminishing returns byadding symbols. Continuingtheexample,itwouldtake16simultaneously tradedsymbols to halve thedeviation again. Further,findingalargesetofsymbolshaving statisticallyindependent trades isunlikely.The following are the

Page 1062: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

directions to recreate thespreadsheet.Weneed to firstinsert the two importantstatistics.IncellA1,type“%Winners” without quotationmarks, and in cell B1, type55. In cell A2, type “ProfitFactor” without quotationmarks and in cell B2, type1.5.Thevaluesof55and1.5areonlyinitialvaluesandarerepresentative of a goodsystem.Theentries intocellsB1 and B2 are system

Page 1063: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

statistics thatyoucanchangeto visualize their impact onequitygrowth.In row 4, insert headings

for five columns as“random,” “trade profit,”“cum profit,” “trade #,” and“cum avg profit.” Thequotation marks for theheadersareunnecessary.In cell A5, input

“=RAND()” withoutquotationmarks.Thiscreates

Page 1064: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

a random number having auniformprobabilitydensityinthe range between 0 and 1.This random number iscompared to the probabilityof a win by inserting“=IF(A4<$B$1/100,$B$2,−1)”without the quotation marksintocellB5.Thisconditionalstatement says that if therandom number falls withinthewinning probability, thenassign the payout probability(theprofitfactor)tothetrade;

Page 1065: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

otherwise, assign a value of−1 to the trade. This is theoutcome of the trade. In cellC5, input “=B5” withoutquotation marks because thefirst trade profit is the sameas the cumulative profit forthe first trade. Insert 1 intocell D5 as the first tradenumber.IncellE5, insert theequation “=D5*(($B$2+1)*$B$1/100 −1)”withoutthequotationmarks.

Page 1066: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Copyallofrow5intorow6.Thenchange cellC6 tobe

“=C4 + B5” without thequotation marks. This sumsthetradeprofitsincolumnC.Next, insert the equation“=D5+1”without quotationmarks in cell D6. Thisincrementsthetradenumber.Finally, copy all of row 6

and paste it into rows 7through 504. Now you have

Page 1067: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the data for your analysisover 500 trades.Make a lineplot of columns C and E tographtheMonteCarloequitygrowth and cumulativeaveragetradeprofittogether.JustpressF9 to recompute

the spreadsheet. You willcreate a new randomizedequity growth curve becauseall the randomnumbershavechanged. Repeat as often asyou desire to get a feeling

Page 1068: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

thatyouknowwhattoexpect.You can change the data incellsB1andB2toassess thesensitivityofsuccesstothesebasicparameters.

Page 1069: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■MonteCarloEvaluationMonte Carlo analysis is thebestwaytoevaluateatradingstrategy if you have theprogramming capability. Thecalculations are relativelystraightforward. Suppose youhave a sufficiently largenumber of trades that youhave confidence in the

Page 1070: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

strategy'sworkinginavarietyof conditions. If workingfutures, this could besomething like trading everytwo weeks on the averageover the past 10 years. Ifworkingstocks, thiscouldbeusing all the symbols in theS&P500 indexover thepastseveralyears.The computations start by

computing the profit per dayfor each of the trades in the

Page 1071: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

real trading history. Thenplacealltheseprofitsperdayin the proverbial hat. Next,drawaprofitperdayfromthehat, record its value, andreplace it in the hat. Repeatthe drawing 260 times tocreate a randomized year'sworth of trading. Note andrecordtherandomizedannualprofit in a “bin,” which is arelativesmall rangeofprofit.Then, repeat the annualizeddrawing 10,000 times and

Page 1072: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

place the annualized profitinto its correct bin. Doingthis, it is possible to havesomeyears thathavenothingbut losing trades and otheryears that have nothing butwinning trades. Of course,there is a wide range ofcombinations between thetwo extremes. The resultingnumberofcounts ineachbinwill have an approximatenormal(Gaussian)probabilitydistribution shape. An

Page 1073: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

example of a Monte Carloanalysis of trades can befound atwww.StockSpotter.com.3Since the Monte Carloanalysis results have theshapeofanormalprobabilitydistributionfunction,youcaneasily establish theexpectation (average profit)of the trading strategy.Additionally, you canestimate the standard

Page 1074: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

deviation in profitability, soyouwon't be surprisedwhenyour actual results don'tmatchyourexpectation.

Page 1075: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■StockSpotter.comIn this chapter, I haveoutlined the tips andtechniques to write aneffectiveshort-termorswing-trading strategy. Rather thangivingaspecificcodelisting,Ihavepainted the techniquestobeusedwithabroadbrushbecause there are so many

Page 1076: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

variables that writing atrading strategy is analogousto writing music. For fulldisclosure, I am thecofounder ofStockSpotter.com.StockSpotter contains anumberoffreeindicatorsthatuse the principles I havedescribed in this book. Theyeliminate the effects ofspectral dilation. Theyminimize lag. They areuncommonly smooth due to

Page 1077: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

multipole filtering.SwamiCharts are alsoincluded.StockSpotter isprimarily a

site for short-term trading,andhasallthenecessarytoolsto support this role.Data forover 4,000 U.S. stocks andexchange-traded funds isincluded. Screeners scan thedata every day to identifyunique situations conduciveto short term trading. Since

Page 1078: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

StockSpotter is a cloudcomputing service, there arefour customized watch liststhat you can modify andmonitor for trading signals.You can import other lists,such as the IBD Nifty Fifty,into the watch list to get adouble filtering opportunityforyourtradingsignals.My cofounder, Ric Way,

has implementeddata-miningtechniques to supplement the

Page 1079: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

tradingrulesproducedbytheindicators. This data miningincludes difficult-to-pinpointcharacteristics such astrendiness, cycle amplitude,volatility, and so on. All thetrading signals, both entryand exit, are given after themarket close for exercise atthemarketontheopenofthenext tradingday.That is, thetrading signals are given inadvance. Then these signalsare transparently tracked as

Page 1080: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

hypotheticaltrades.Youhavecompleteaccesstoalltradingresults, including trade-by-tradelistingandMonteCarloanalysis.Ifyourinterestisprimarily

in short-term trading ratherthan coding indicators orwriting trading strategies, Irecommend that you tryStockSpotter.com as yourtoolofchoice.

Page 1081: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

■ Key PointstoRemember

1. The roofing filter orits equivalent must beused with the indicatorsused to generate swing-trading signals toeliminate the distortionsintroduced by SpectralDilation. That is, theindicators used to create

Page 1082: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the signals must have azeromean.2. Effective swing-trading signals mustanticipate the priceturning points tomitigate the lagintroduced in computingthe indicators. Usingconventional oscillators,this is accomplished bycreating a long tradingsignalwhentheindicator

Page 1083: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

crosses under a lowerthreshold and creating ashort trading signalwhen the indictorcrosses over an upperthreshold.3. A sine wave is aunique primitive. It canbe created from pricedata using a relativelynarrow band-pass filterdescribedinChapter5.4.Acosinewavecanbe

Page 1084: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

created by taking theone-bar difference of asine wave. The cosinewave is an anticipatingsignal because it leadsthe sine wave by aquarterofacycle.Usinga cosine wave is asyntheticway to removelag.5. A leading long entrysignal can be generatedwhen a cosine wave

Page 1085: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

crosses over itselfdelayedbyabarortwo.A leading short entrysignal can be generatedwhen a cosine wavecrosses under itselfdelayedbyabarortwo.6. A less conservativemethodgenerates a longentry signal when thesinewave crosses underzero and generates ashort entry signal when

Page 1086: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

the sine wave crossesoverzero.7. Swing trades musthave a safety valve exitbecause the trades areenteredinanticipationofa price turning point.The safety valve can bebased on either time intrade or a price breakout.8. Swing-trade entrysignals indicate position

Page 1087: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

reversals for always-in-the-marketstrategies.9. Exit signals whentrading stocks to thelong side are bestaccomplished using aSuperSmoother filtercrossing under itselfdelayed by a few bars.This techniqueminimizeswhipsawsandunwarranted early tradeexits.

Page 1088: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

10. Stop-loss techniquesshould be used only tolimitmajorlosses.11.MonteCarloanalysisis the best and mostreliable way to assesstrading strategyperformance.

Page 1089: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

Notes1.www.stockspotter.com/In/TechnicalPapers.aspx

2.www.stockspotter.com/In/MesaIndicatorHelp.aspx

3.www.stockspotter.com/In/MonteCarloProfit.aspx

Page 1090: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

ABOUTTHEWEBSITE

This book includes acompanion website with theEasyLanguagecomputercodefound in the book. This willhelp you utilize the codewhile avoiding the

Page 1091: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

aggravation of keying it inyourself and debugging theerrors. All the code in thebook is fully functional andyou can either copy it fromthetextfilesandpaste it intoa new indicator you havecreated in TradeStation, oryou can import the *.ELDfilesdirectly.To access the site, go to

www.wiley.com/go/EhlersandenterthePINcodefound

Page 1092: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

at the back of this book. E-book readers will findadditional instructions forrequestingaPINcode.

Page 1093: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

INDEX

AAGCAliasingAlphaAnalyticSignalAnticipateAutocorrelationAutocorrelationPeriodogram

Page 1094: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

AutomaticGainControl

BBandPassfilterBandStopBandwidthButterworth

CCCICoefficientCompressConvolution

Page 1095: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

CorrelationCriticalperiodCube

DdBDecibelDecyclerDelayDFTDiffusionEquationDiscreteFourierTransformDispersion

Page 1096: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

DominantcycleDrunkard'swalkDualDifferentiatorDuration

EEMAEvenBetterSinewaveExponentialMovingAverage

FFilterFiniteImpulseResponse

Page 1097: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

FIRFisherFourierFractaldimensionFrequencyresponse

HHeatmapHighPassHilbertHomodyneHurstcoefficient

Page 1098: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

IIIRImaginaryInPhaseInfiniteImpulseResponseInputInstantaneoustrendlineIntradayInverseFisher

LLag

Page 1099: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

LowPass

MMedianFilterModified least-squaresquadraticsModified Simple MovingAverageMonteCarloMovingaverage

NNoise

Page 1100: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

NonrecursiveNormalize

OOrthogonalOscillatorOutput

PPearsonCorrelationPercentWinsPerformancePeriodmeasurement

Page 1101: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

PeriodogramPhaseAccumulationPhaseleadPhasorPowerPredictiveProbabilityDistributionProgramming

QQQuadratureQuantization

Page 1102: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

RRandomRandomwalkRealRecursiveReversalsRoofingfilterRSI

SSafetyValveSelectivity

Page 1103: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

SimpleMovingAverageSMASmoothingSpectralDensitySpectralDilationStochasticStopLossStrategySuperSmootherSwamiChartsSwerlingSyntheticprices

Page 1104: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

TTelegraphersEquationTradingsystemTransferresponseTransformTransformerTransientresponseTrendTurningpoint

WWave

Page 1105: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

WaveamplitudeWeightedMovingAverageWMAwww.StockSpotter.comwww.SwamiCharts.com

ZZerocrossingZeromean

Page 1106: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

EasyLanguageComputerCodefor

CycleAnalyticsforTraders

YourpurchaseofCycleAnalyticsforTradersincludesaccess

totheJohnEhlers'sEasyLanguagecomputer

code.Pleasevisit

www.wiley.com/go/ehlerstorequest

anaccesscodeandaccessthis

Page 1107: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

content.

JohnEhlersISBN:978-1-118-72841-3

(ePDF)978-1-118-72860-4(ePub)Fortechnicalsupport,please

visitwww.wiley.com.Fortelephonesupport,please

contactusat:1-800-762-2974(U.S.),1-

317-572-3994(International).

Page 1108: CYCLE A TRADERS - DropPDF1.droppdf.com/files/I17AO/cycle-analytics-for-traders-downloadable... · comprised the conventional wisdom for equity traders. However, there have been profound

WILEY