Saturday, December 31, 2011

ThinkScript Included: Range Bar Projector

I am starting to look into range bars and was just re-listening to Ken Woods range bar talk in the TOS archive. The second time through I picked-up on something he mentions in passing - range bar projectors. That's a simple enough thing for me to "TOS" off so here's the results of this Saturday morning's fun:

 /TF with sdi_rbproj and sidelines.

Since range bars are fixed in their price size you can predict where the forming bar might close: either low + size or high - size.

My preference is to plot lines in the right expansion area for this but I realize that some people might not use the right-expansion capability so I have provided a way to realize the projection right at the forming bar as well:

 /TF with sdi_rbproj without sidelines

Here's the code:

#############################
# sdi_rbproj
#hint: RangeBarPROJector projects where the forming range-bar will close to the up and downside. Revision 1.0
http://www.smallDogInvestor.com
# author: allen everhart
# date: 12/31/2011
# Copyleft! This is free software. That means you are free
# to use or modify it for your own usage but not for resale.
# Help me get the word out about my blog by keeping this header
# in place.

input sideline = yes;
#hint sideline: Yes, plots the projections as lines in the right-expansion area, No plots the projections as up/down arrows on top/bottom of the forming bar.

def barSizes = high-low;
def bs=highestAll(barSizes);

rec rbHi =
if isnaN(close) && sideline then rbHi[1]
else if !isNaN(close) && isNan(close[-1]) then low+bs
else double.NaN;

rec rbLo =
if isnaN(close) && sideline then rbLo[1]
else if !isNaN(close) && isNan(close[-1]) then high-bs
else double.NaN;

plot phi = rbHi;
plot plo = rbLo;
phi.setPaintingStrategy(
if sideline then PaintingStrategy.LINE
else PaintingStrategy.ARROW_DOWN
);
plo.setPaintingStrategy(
if sideline then PaintingStrategy.LINE
else PaintingStrategy.ARROW_UP
);
phi.setStyle(Curve.MEDIUM_DASH);
plo.setStyle(Curve.MEDIUM_DASH);
phi.setDefaultColor(color.MAGENTA);
plo.setDefaultColor(color.MAGENTA);

###########################################

Wednesday, December 28, 2011

ThinkScript Included: Money Flow Index In A Chart Label

The Money Flow Index (MFI) is a momentum indicator illustrating the strength of money flowing into and out of a security measured on a 0-100 scale. It is also a good over-bought/sold indicator. MFI values over 80 are considered to be over-bought. Likewise, MFI values under 20 are considered to be over-sold. Great! But I don't want to do technical analysis on it and, thus, I wouldn't ordinarily have it on my chart because it consumes precious real-estate at the bottom of my chart, scrunching up the price bars. However, like Average True Range, I am mostly interested in the most recent value of the indicator, so I have written a chart-label study that presents a most-recent view of MFI in compactified form. Here's the picture of this study in action:

 SPY With Money Flow Label In Upper Left Corner
The chart label presents the current value of the Money Flow Index followed by my trend indicator. The trend indication is the last two characters, in this case, ^^ (two up-carrots.) What that means is that the MFI has had two successive moves up. If there had been a down move in the MFI two days ago then a v (alas, there is no down-carrot in ASCII) would have appeared in the first position. Also, the grey coloration of the label means that the indicator is in the midrange area. If the MFI is below 20 then the label turns red and green for overbought when the MFI is above 80. Finally, if MFI has just crossed above oversold or crossed below overbought then the chart label is colored Orange.

Here's a picture of an equity displaying this cross-over signal:

 FSLR with a Cross Above Oversold Event in the Money Flow label.

Here's the code:
###################################
# sdi_flow: Display Money Flow Index as chart label
#hint: Displays the MoneyFlowIndex as a color-coded chart label. Red=oversold, Grey=midrange, Green=overbought and Orange=crossover. rev: 1.0 http://www.smalldoginvestor.com/
# author: allen everhart
# date: 12DEC2011
# copylefts reserved. This is free software. That means you are free
# to use or modify it for your own usage but not for resale.
# Help me get the word out about my blog by keeping this header
# in place.
declare UPPER ;
input length = 14 ;
input overBought = 80 ;
input overSold = 20 ;

def bar = round(moneyFlowIndex(20,80,length,1),2) ;
def dir = bar-bar[1] ;

concat(concat(concat("FLO:", bar),
if dir[1]>0 then "^" else if dir[1]<0 then"v" else "="),
if dir>0 then "^" else if dir<0 then"v" else "="),
if bar>overBought then color.GREEN
else if bar<overSold then color.RED
else if bar[1]>overBought then color.ORANGE
else if bar[1]<oversold then color.ORANGE
else color.GRAY
);

#########################

Friday, December 23, 2011

Stealth Dip Confirmed On Dow/Gold Ratio

 DOW/Gold Ratio 12/23/2011

Wednesday, December 7, 2011

﻿
﻿ I heard Tom Sosnof of TastyTrade.com, a trader/entrepeneur I admire greatly, put on a bullish diagonal trade for Microsoft today. I believe his trade was -Jan25Put/+Feb24Put for a 30 cent or so credit. When I looked at the seasonality of MSFT I saw that Tom's trade was dubious. Since I need more negative delta in my portfolio anyway I felt compelled to compose and take a Bearish diagonal on MSFT, which I have shared on MyTrade. I bought the -Dec 25 Call/+Mar 26 Call diagonal for a debit of 34 cents. My max loss is \$1.34 if MSFT bucks its season and explodes to the upside in the next week and half, otherwise a strong seasonality takes over in MSFT in the first quarter that I think will take MSFT down to the neighborhood of its current 52 week low of \$23.65 by March. MSFT has a better than even chance, seasonally speaking, of going even lower but I have given Tom a benefit of a doubt by picking a higher probability target north of \$23.65.  MSFT has weekly options which I will avail myself of if they make sense when the time comes to roll next Thursday. I may be a little early since the Aroon indicator has not got to the overbought area but I am willing to suffer through a little end-of-year bullishness.

Sunday, December 4, 2011

﻿﻿
﻿
﻿ ﻿﻿Luca Giusti posted a seasonal pattern for AGU and this looked pretty good on my seasonal projection studies for a Nearly Naked Put Diagonal trade. So I am documenting here the why and how of this trade which I shared on MyTrade.

First of all I have 'splaining to do on my seasonal projection studies. That mess of blue, magenta and green extending into the future are my seasonal projections. These are a graphical digest of the last five to seven years of seasonal behavior that I find to be relevent to trading. To build these I take the fractional price changes of the underlying equity from the same anchor date in previous years and average them together and then multiply the average fractional move against the closing price of the anchor date. This is done repeatedly for each future date to build up a projection line of average seasonal performance.

The top edge of the green mess is 0.3 standard deviations below the average projection and is only displayed when it falls 2% or more higher than the flat line. This multiple of the standard deviation means that 62% of the individual season projections fall above the green mess - a better than even chance for where the future price will go when business is usual. Also, the fact that the green mess tracks so consistently close to the projection through April tells me that AGU is strongly seasonal. After April it falls away from the projection when I anticipate the season to end.

Moreover, my seasonal projections help to indicate whether business is usual or not. In the roadmap above I show two seasonal projections: the blue line (a seven season projection) is anchored 10 trading days back and the magenta line (a five season projection) is anchored on the most recent day. The fact that these two projections converge and move together into the future is a strong indication to me that business is usual for AGU, otherwise any recent trader knowlege of unusual business in AGU would show its existance by separating the seasonal projections because AGU would be off-track wrt the earlier projection.

This all suggests to me a bullish trade in my preferred style: the NND (Nearly Naked Diagonal.) In my formulation of the bullish diagonal, I sell a put in the front month at the first strike ITM and I use this value as a budget to shop for a backmonth strike to buy (usually a goodly number of months back, like 5 or 6, so we have plenty of roll opportunities.) I like to outlay between \$1 and \$2 for these trades or whatever I feel I can cover in the first roll of the short option. The April 62.5 Put fits the bill and I can put this -Dec70P/+Apr62.5P trade on for a debit of about \$1.50 as of Friday prices. This would set my max loss to \$9, which is well within my small-acceptable-loss tolerance but keep in mind that this max loss would only be realized if AGU were to go "Lehman" in the next two weeks. Barring that unlikely extreme event I will roll the short option for a credit and thus whittle-down the max loss exposure.

The roadmap says that AGU could rally up to the descending trend line of a symetrical pattern by the first week of January, where it might then fall back to the ascending trendline before finding support for a larger breakout. If I do see precisely this kind of behavior it may pay to buy back the short option that first week of January and complete the roll by selling February closer to the Jan expiration. However, it is of little concern if I don't see precisely this kind of behavior due to the power of the roll as there is wide latitude in the underlying equity price for which a short option can be rolled profitably. NND's are very forgiving in this respect.

Well that's the plan and I will keep you posted as to how reality measures up.

Best.
-Allen

Saturday, December 3, 2011

ThinkScript Included - My TTM_Squeeze Scanner For The CNBC Stock Challenge

The CNBC Million Dollar Stock Challenge has concluded. I did not win but one of my portfolios (Schnauzer, I named them after small dog breeds) that I was active with scored a 99.78% game rank percentile:
milliondollar.cnbc.com
Allen Everhart ranks 1,497 on the CNBC.com Million Dollar Portfolio Challenge Top Traders Board
This result was achieved by investing in the few leveraged ETF's that were permitted and by shorting GBP/USD and a good deal of neglect. (Note: a portfolio that I made no investments with, only improving by bonus question money, scored 96.44% game rank percentile.)

Before the challenge started I developed a custom scanner in the ThinkDesktop platform but I did not use it all that much after I found out that leveraged ETFs were permitted investments. However, I do think active traders might find some merit (at least in the education of custom scanner construction) to this scanner.

Here is an image of the scanner loaded into the scan-tab:
 My CNBC Scanner
﻿﻿﻿
Last Minimum 2 and Market Cap Minimum 500M were CNBC contest criteria that I could match with the standard fundamental filters.

Sizzle Index Minimum 0.5 is a filter I chose because it finds stocks that have options and that are seeing somewhat elevated option activity.  The sizzle index is a measure of option volume and the minimum of 0.5 means I am looking at stocks with 50% greater than average volume.

The last CNBC contest criteria was that volume averged over 100 days be greater than 50,000. For this, one needs to resort to a custom study filter:
1. Click the Add Study Filter button on the upper right. This will append the AdxCrossover filter to the list (the list may scroll up hiding the Last Minimum 2 fundamental filter but it is still there.)
2. Click the small triangle on the lower right of the AdxCrossover filter to drop down the list of standard study filters and select Custom, the last menu entry.
3. In the Scanner Custom Filter dialogue, select the inspector button and highlight AdxCrossover() to replace that text:
4.  Type the letters si and then select SimpleMovingAvg from the suggestion drop down list. Be sure to append () and then the syntax error will clear allowing the inspector box to appear.
5. In the inspector box select VOLUME in the price type input box and set length to 100.
6. Finally append >= 50000 to the text.
(Note: custom filters are boolean ThinkScript expressions. They must evaluate to true or false - you cannot just cut and paste any ThinkScript code from a chart study.)
This completed filter should look like:
7. Click ok and you have created, perhaps, your first custom filter.

The last two filters are some special custom code for which you can repeat the above steps, more or less, to add:

(1.333333 * stdev(close, 20) / averageTrueRange(ATRLength = 20) >= 1) && (1.333333 * stdev(close, 20)[1] / averageTrueRange(ATRLength = 20)[1] < 1)

and
Inertia(close - ((Highest(high, 20) + Lowest(low, 20)) / 2 + ExpAverage(close, 20)) / 2, 20) > 0

These last two filters are the criteria that John Carter of Trade The Markets uses to indicate when to take a Bullish trade. You can verify this by bringing any of the stocks found in the scan and inspecting the charts with the TTM_Squeeze and TTM_wave studies. For example:

﻿
 ANSS with a Bullish Squeeze Breakout
﻿ I hope that was helpful to you all.

Best.
-Allen

Friday, December 2, 2011

Stealth-Dip Update

 Dow/Gold Dec 2, 2011
The above chart plots the track of the Dow/Gold ratio. This literally prices the Dow in terms of Troy Ounces of Gold. Usually economists look at this ratio to compare historical values of the Dow over eras of highly variable inflation and monetary policy. My thesis is that the much anticipated second dip in the broad market has already occurred but was disguised by the two rounds of quantitative easing. The chart above is consistent with my stealth-dip thesis: the low in August occured when S&P downgraded the US debt and is lower than the March 2009 low in the ratio. The D/G has touched above the March 2009 low-level but I don't consider the thesis confirmed yet. Confirmation would come when the market tests the 7.2 level as support which may happen sometime in Spring of 2012.  You heard it here first.

Best.
-Allen

Thursday, December 1, 2011

Final 2011 Presidential Cycle Update

﻿
 Final 2011 Presidential Cycle Update
﻿The year prior to a presidential election year is usually a very bullish year. Presumably this is due to incumbents working the levers of government to make the economy as rosey as possible. What we got was a big divergence from the norm (blue line) to the downside. The blue oval is 1 ATR high and centered on the intersection of the cycle projection anchored on Dec 1 and the year-end. We may yet squeak out a gain for the year but it is somewhat doubtful and I give it something like a 20% chance.

Best.
-Allen

Saturday, November 26, 2011

ThinkScript Included - Growth Of 10K

At the bottom I have provided the ThinkScript source for the classic growth of \$10,000 study that funds use to pitch investments to retail customers. I was surprised that this did not exist in the standard studies in the ThinkDesk trading platform so I am providing it, gratis. Here are some images of this study in action:

﻿﻿
 AAPL 10 Year Growth, 1 Month Candle

﻿﻿
 SPY 10 Year Growth, 1 Month Candles
The solid green line represents the monthly growth of a \$10,000 investment purchased once 10 years ago (BNH -Buy -N- Hold), while the dashed blue line represents the monthly growth of a \$10,000 investment divided into 120 purchases, once a month for 10 years  (DCA - Dollar Cost Averaging) with \$5 commissions and 0.2 APR interest paid on the idle portion of the 10K.

While it is awe-inspiring to see that \$10,000 invested in AAPL 10 years ago is now worth \$345,000, the SPY picture is an average performance that can't be ignored: \$10,000 invested in SPY 10 years ago is worth only \$10,232. (Note: The TOS data feeds for ETF's do not provide dividend information, so your actual performance would have been on the order 2-3%/year better. However, the sdi_passive study does model dividend reinvestment when the data is available.) There must be many more poor/average investments out there than a cherry-picked-with-hindsight high-flier like AAPL. (Note: that IPO purchasers of AAPL did not make money for the first 18 years.)

In my opinion, this means that it is dreadfully hard to find these high-fliers that you can buy and forget. There must be so much crash 'n burn out there that it would just not be practical for most of us small-dogs to just sit on investments. Be vigilent and work the time-advantaged strategies.

#########################
# sdi_passive - plot results of buy-and-hold and dollar-cost-averaging
#hint: shows the growth of \$10,000 (configurable invested by the two basic passive-investment strategies: buy-and-hold (bnh) and dollar-cost-averaging (dca). dividend reinvestment is accounted for if the data is available(alas, etf's generally do not have this data available.) for dca the \$10,000 is invested in equal periodic investments over the duration of the chart as determined by dcaFrequency. commissions are accounted for. idle money accrues interest, compounded per bar, but accrued interest is not invested. rev:1.2.0 http://www.smalldoginvestor.com
# author: allen everhart
# date: Oct 1, 2011
# rev. 1.2.0 17aug2013 -
#    added dcaFrequency to produce more realistic results on aggregationPeriod.DAY
#    start the study on barnumber() 3 to avoid a thinkScript bug.
#    added chart labels to break down the dividends and interest earned.
# copylefts reserved. This is free software. That means you are free
# to use or modify it for your own usage but not for resale.
# Help me get the word out about my blog by keeping this header
# in place.

declare lower;
input totalInvestment = 10000;
input commission = 5.0;
#hint buyAt: Other calculators may differ on this so choice is provided here for comparison purposes.
input buyAt = { default open, close} ;
#hint APR: annual percentage rate applied to idle money.
input APR=0.2;
def purchasePrice =
close
else
open;
#plot pp = purchasePrice;
input dcaFrequency = 21 ;
#hint dcaFrequency: number of bars per purchase for dollar cost averaging. there are about 21 trading days per calendar month.
def aggFact = getAggregationPeriod()/(12*AggregationPeriod.MONTH);
def intRate = (APR/100) * aggFact;
#plot af = aggFact ; #diagnostic
def startBar = 3 ;
def barn =
if isNaN(close) then 0
else if barnumber() < startBar then 0
else barNumber()-startBar+1; #bar numbers origin to 1

def divy =
if isNaN(getDividend()) then 0
else getDividend() ;
def dripSharesPerShare =
divy[1]/purchasePrice
divy/purchasePrice
else
0 ;
#plot dss = dripSharesPerShare ;
def numberOfPurchases = floor(0.5+highestAll(barn)/dcaFrequency);
def periodicInvestment = totalInvestment/numberOfPurchases;
def moneyInvested =
if barn == 0 then 0
else if barn == 1 then periodicInvestment
else if barn>1 && barn % dcaFrequency == 0 then
periodicInvestment + moneyInvested[1]
else
moneyInvested[1]
;
#plot mi=moneyInvested ; #diag
################ BNH ####################

def bnhshrs =
if barn == 0 then 0
else if barn == 1 then
(totalInvestment-commission)/purchasePrice
else
bnhshrs[1]*(1+dripSharesPerShare)
;
def bnhdiv =
if barn == 1 then 0
else if barn > 1 && divy[1] then bnhdiv[1]+divy[1]*bnhshrs
else bnhdiv[1];
#plot bd= bnhdiv; #diagnostic
plot bnh = if barn>0 then bnhshrs*close else double.NaN;
bnh.setDefaultColor(color.DARK_GREEN);
########################### DCA ############################
def dcashrs =
if barn == 0 then 0
else if barn == 1 then
((periodicInvestment-commission)/purchasePrice)
else if barn>1 && barn%dcaFrequency == 0 then
((periodicInvestment-commission)/purchasePrice)+(dcashrs[1]*(1+dripSharesPerShare))
else
dcashrs[1]*(1+dripSharesPerShare)
;
#plot ds=dcashrs ; #diagnostic
# if we buy at open then maybe exclude a periodicInvestment from interest calc
def idleMoney =
if barn==0 then 0
(totalInvestment-periodicInvestment)*(1+intRate)
(totalInvestment*(1+intRate)) - periodicInvestment
(idleMoney[1]-periodicInvestment)*(1+intrate)
(idleMoney[1]*(1+intRate)) - periodicInvestment
else
idleMoney[1]*(1+intRate)
;
plot dca = if barn>0 then (dcashrs*close) + idleMoney else double.NaN;
dca.setDefaultColor(color.BLUE);
dca.setstyle(curve.MEDIUM_DASH);
addlabel( 1, Concat("dcaint:", round(idleMoney,2)), color.BLUE );
if barn == 1 then 0
else if barn > 1 && divy[1] then dcadiv[1]+divy[1]*dcashrs

############################################

Sunday, November 20, 2011

Mo' MA

Mastercard (MA) is shaping up to be a very nice example of a rare bullish trade in this messy market. So here's the pretty picture:

Previously, we were looking at a seasonal projection down to the 345 level, a broken resistance. Instead we got a bounce at 355, a more recent broken resistance, and some supporting action there into the November expiry. I'm not a big fan of Elliot Waves but the fact we did not test back down to 345 coupled with the seasonal projection to new 52 week highs just looks very much like an Elliot Wave, so I've labeled the "waves." Of course, we would need to see a close above 3 soon to confirm 3 and 4.

Currently, I am trading this using my Nearly Naked Diagonal (NND) methodology: Short  NovWk4 355 Puts and long Jan 290 Puts. I prefer this method because it makes a weekly process of taking profits. Also, I am long Dec 385 Calls, a paid for remnant of a similar bearish NND for which I closed the short side into the November expiry. This Call I am keeping as a lottery ticket on the off-chance that MA makes a bigger move to the upside than I am anticipating.

Keep on Rolling!

Sunday, November 6, 2011

MA: Even An Old Blind Small Dog Investor Gets A Bone Once In A While.

I don't share many forecasts, so when I do and they work out right ... well, I feel I need to toot my own horn a little (somebody has to do it!)

So here's the forecast I put up on Oct 23:
 Oct 23 Forecast for Mastercard

The oval near the red timeline is where I thought Mastercard had decent chance of meeting or exceeding.

So here's the picture of MA today, with the same studies, red timeline and the same Oct 23 target oval (more or less, I have obviously not redrawn it precisely the same as before as I am constantly adjusting my personal forecasts) :﻿ ﻿
 New MA Forecast

﻿MA shot up on earnings straight into my target oval and encountered resistance. This is probably just luck but the direction is right and MA is getting squirrely up here where I thought it might start retreating.

The current seasonal forecast calls for MA to retreat back down to the 345'ish level by the Nov expiration. This same retreat is imprinted on many stocks and averages so I find it credible. The new target oval is 1 week wide, 1 ATR high, is nestled in front of the seasonal dip and just touching the red high probability area.

Full disclosure: I am currently in a bearish diagonal on MA.

Sunday, October 30, 2011

The Stealth-Dip Hypothesis

﻿
The Dow/Gold ratio measures the price of the Dow in terms of how much gold, in Troy ounces, it takes to purchase the Dow. Normally, economists look at this ratio to compare market valuations over large periods of time for which inflation is in play, (e.g. to compare valuations in the 1920's to today.) I have begun to look at the Dow/Gold pricing for a different reason: to get a view of the market that is independent of central bank monetary policy. The thinking here is that quantitative easements have the effect of artificially pushing down the valuation of the dollar, thus, the stock market is exhibiting artificially high prices and is masking the much awaited second dip in the market.

 Dow/Gold on 10/29/2011
In the above PairRatio study I plot the dow futures (/YM) divided by gold futures (/GC) (Note: In order to get the plot of the ratio it is necessary to enter the difference between the two futures so I've hidden the main-chart plot and just show the PairRatio study.) I've drawn in the level of the infamous Mar 6, 2009 low of the ratio and as you can see the market dipped that level in August during the S&P downgrade fiasco. However, the market has since touched above the 09 low-level which, so far, is supporting my hypothesis of a stealth 2nd dip.

﻿﻿﻿﻿﻿﻿﻿

Saturday, October 29, 2011

Presidential Cycle Update

The year before the presidential election year is well-known for its bullishness. This can be seen in charts of data going back a hundred years or more (as the people at SeasonalCharts can show you.) My SeaPro5 study can show the average trend of a four year cycle going back 20 years (5 election seasons) on a weekly chart, projected from an anchor date. So once a month I like to post an update of where we stand wrt this larger time frame:
 Seasonal Projection 4 Year Presidential Cycle
The last four weeks have been strongly bullish. The 1227 resistance level was overcome two weeks back after some challenges from bears resulting in the bar with a long lower tail. Then, last week we punched up through the year flat-line (dashed blue line at 1257.54) with what techicians call an "energy" bar, signifying that bears are licking some wounds. I am somewhat surprised that the year flat-line did not turn out to be a resistance level since it was a confirmed support level and broken by a similar energy bar (which just goes to show that TA is not a hard science.) The current projection has the market finishing the year up 100 points or so in the neighborhood of 1350.

Tuesday, October 25, 2011

XOM Wisdom?

My pup has 10 shares of XOM from Nonny and calls for advice. "Should I sell it now or wait?"  Here's my chart on XOM:

﻿
 XOM with Seasonal Projections.
﻿ My advice: you might get another dollar or two if you sell tomorrow afternoon - into the final pre-earnings hours - and maybe as much as 5 dollars if you wait for December but if you really need the money (and he does) then sell now and don't look back. With those dogi's setting up we could easily be trading down \$2 tomorrow.

Sunday, October 23, 2011

My MA

I recently shared a bullish diagonal trade on MA claiming strong seasonality, so I wanted to show you what I am seeing:

 MA with Seasonal Projection
The purple line is the projection of seasonal performance averaged over the last 5 yearly seasons for MA as produced by my SeaPro5 study. The green shaded area represents an area of high probability for a trade and is bounded on the upper side by .3 x standard deviation of the seasonal data (you math wiz's should prove to yourself that 62% of the seasonal data lies above this bound.) The close proximity of this upper bound to the seasonal track indicates that MA has decent seasonal behaviour. So I see an excellent chance that MA will be challenging at least the 52 week high by earnings and a very good chance of a really nice move into the 380-390 area before post-earnings profit taking knocks it down.

I play this with a diagonal because, at this point, I want to be a seller of expensive earnings premium. I plan to roll weekly and possibly diagonally upwards depending on circumstances. If MA pops decently into earnings I plan to put on a bearish diagonal to leg into a double diagonal position in order to capture the backwash from profit taking.

Friday, October 21, 2011

Double Dip - Over and Done

The much anticipated double-dip is over and done. You say you didn't hear the market crashing back down to 666!!? Well, it did but it was disguised by monetary policy. If you price the market in terms of a currency that is impervious to central bank interventions then you will see this. The currency I'm talking about is gold of course. The way to see this is to plot the ratio of the dow divided by the price of gold. Here's the plot I'm keeping watch on:
 Dow/Gold Ratio
In the above PairRatio study I plot the dow futures (/YM) divided by gold futures (/GC) Note: In order to get the plot of the ratio it is necessary to enter the difference between the two futures so I've hidden the main-chart plot and just show the PairRatio study. I've drawn in the level of the infamous Mar 6, 2009 low of the ratio and as you can see the market dipped that level in August during the S&P downgrade fiasco. However, just today the market has recovered above the 09 low-level which is what has instigated me to declare the dip as over and done.

The channel is a linear regression channel that I drew from Sep 30 back to the 5.7 low and then extended to the right. The market has been respecting this channel remarkably well, wouldn't you say?

_

Wednesday, October 19, 2011

Analyzing The Unlikely Calendar

One of the points I assert about rolling short options is that an option with more time on it almost always trades for a higher price, thus, you can almost always roll-out almost any short option for a credit. To see that this must be so you can consider the implications of the opposite: the front month trading for a higher price than the back month. I claim that this is the equivalent of the market giving away riskless trades in the form of credit-calendars (i.e. selling a front month option and purchasing the same strike option with more time to expiration.) The Analyze tab of the ThinkDesktop trading platform gives one a way to visualize this by plotting the profit/loss graph for such a trade:

So here I contemplate an unlikely calender: selling the SPY Nov 123 Call while simultaneously buying the SPY Dec 123 Call for a credit of 10 cents. This trade always produces a profit even when the underlying price moves very far away from the current price (~122.25) Notice that if SPY closes anywhere in the 68% probability range (light blue shaded area) on expiration you will realize some nice gains whereby a \$10 credit increases to a profit from \$50 to \$350 (red line.) Such situations will quickly be traded out of existance by electronic arbitrageurs, and probably the market maker will lose his job because these only ever come about by error.

Sunday, October 2, 2011

Bull Sign: Dow/Gold Ratio Recovery

Today's exercise on the ThinkDesktop is to create a ratio chart for the dow/gold ratio. Start with a simple chart with no studies. Then in the symbol input field type /YM - /GC. That will bring up a chart that displays the difference between the dow and the gold futures. Now click the Edit Studies button (leftmost button on the chart tool bar at top) and add the study called PairRatio. Select Yes in the reverse box, then click Apply and Ok. We are not interested in the price graph of the /ym-/gc difference so click Style/Settings and uncheck Show Price Subgraph, then click Ok . You should be left with a chart that looks like this:

﻿﻿﻿
 Dow/Gold Ratio Now - 30Sep2011
﻿﻿﻿ This is the Dow/Gold ratio, a widely watched metric that purports to indicate the health and direction of the economy. Save this chart as a grid so you can refer back to it later. This ratio is literally how much gold it takes, in troy ounces, to buy the dow: 6.6431. Economy watchers like to watch this ratio because it is independent of monetary policy. A high value was set at 43.7 in 1999, 27.9 in 1966 and 18.4 in 1929 (according to Fred's Intelligent Bear Site) and it has gotten down to 1 in 1980, although other low points occured in the 2-4 range)

Most significantly the d/g ratio is lifting off a low of 5.7 after breaking below the 6Mar09 low of 7.1:

 Dow/Gold ratio circa: 6Mar09
So we may already have had our double dip and most traders haven't woken up to the fact because it didn't repeat the numerical values in 2009 owing to monetary policy changes.

You might say a stealth double-dip.

-

Saturday, October 1, 2011

Pre-Presidential Cycle Update

The year before the presidential election year is well-known for its bullishness. This can be seen in charts of data going back a hundred years or more (as the people at SeasonalCharts can show you.) My SeaPro5 study can show the average trend of a four year cycle going back 20 years (5 election seasons) on a weekly chart, projected from an anchor date. So once a month I like to post an update of where we stand wrt this larger time frame:

﻿
﻿﻿﻿ ﻿ The market has diverged significantly from the seasonal projection anchored on the first of the year. My smallDog interpretation of the technicals is that I expect the market to bounce around between confirmed support and resistance areas for a while until one of those levels is broken for more than a week. A "while" could mean for a year or so, maybe through the Nov 2012 elections. While some people might see a Head & Shoulders pattern setting up, I urge extreme caution with that pattern which has been broken several times in recent years with short interest badly punished.

Thursday, September 29, 2011

nearly naked diagonals

Me: Mom, the rolls are gravy!
Mom: Well, which is it, dear. Rolls or gravy?
Me: No, no, the rolls are gravy!
Mom: (sigh)
Back in June I wrote about a strategy I call the nearly naked put - a vertical spread with the twist that the long option is purchased WOTM (way out of the money,) a measure that conserves buying power. This is an effective strategy for a non-margin account (but not limited to) where you want to sell a naked-put but want to reduce the allocation of buying power to be more in line with a margin account.

So, now I evolve this strategy a little - I purchase more time on the long option than the short option. See, I want to repeat the NNP on the next cycle but that would mean purchasing yet another WOTM option and while they are cheap enough out there, the repeated commissions and purchase price do reduce profitability a bit. The evolutionary idea here is that by purchasing the WOTM option a couple or three expiration cycles out I get a kind of two-fer, I pay 1/2 to 1/3 the commissions on it and I get the bulk-rate discount on time according to the well-known mathematics of option pricing (whereby price is proportional to the square-root of remaining time e.g. one can buy 4x time for only 2x price.) I call this strategy the nearly naked diagonal or NND.
The Rolls Are Gravy
The goal of the NND is to use time as an edge to produce reliable profits, even (nay, especially) in very difficult trading conditions. This is accomplished as time is winding down on the short options in a trade called a calendar roll. As I discussed previously (in the twilight zone roll) the calendar roll almost always generates a credit due to the mathematics of pricing time into options. The NND goes on for a small credit or debit but then every roll is pure gravy.

Tell that to your Mom at dinner.

(tbc...)

_

Sunday, September 11, 2011

The Twilight Zone Roll

Heaven? Whatever gave you the idea that you were in heaven, Mr. Valentine? This IS 'the other place!!
There's a famous episode of the Twilight Zone (A Nice Place To Visit, season 1, episode 28) in which a gambler, who thinks he has died and gone to heaven, walks into a casino and can't lose. Every time he plays a hand of blackjack he's a winner, every time he pulls the handle on the slots he hits the jackpot and every time he plays roulette the ball lands on his number.

Now imagine that you walk into the Twilight Zone Casino and put a Benjamin on number 19, say, on the roulette wheel and the ball lands on 22. You feel a momentary pang of loss for having played a sucker's game, maybe even a little duped by having watched too much late-night TV .... but then the Twilight Zone Casino croupier offers you a deal: "I'll give you your Benjamin back from the previous spin plus an extra buck or two for your trouble if you play your number again.

Well, this very deal plays out every week in options trading and its why I'm changing my trading style. The analogous transaction to the Twilight Zone croupier's deal is called a calendar roll. In a calendar roll you buy back the near term short option and sell a longer term option at the same strike price, in a single transaction. Due to the fact of option pricing, in which options with more time are more highly valued, this roll transaction is certain to generate a credit (well, almost certain)* - no matter how badly the position has gone against you prior to expiration. Moreover, you can perpetually roll that loser short option to generate a credit every cycle.

To be eligible for this Twilight Zone Roll you must enter your position by short selling or "writing" an option. You can sell a put option or a call option or both even, it doesn't much matter. Then you wait.

There are four possible outcomes, three of which can always be handled positively and the fourth almost always positively:
1. Your short option is out of the money at expiration. You buy back your short option for pennies on the dollar, you win the maximum gain.
2. Your short option is slightly in the money at expiration but worth less than what you sold it for. You buy back your option for a relatively modest gain, you win.
3. Your short option is deep-in-the money at expiration and is worth a lot more than what you sold it for. You buy back your option and sell next months option at the same strike price for even more money, you win. This is the Twilight Zone Roll. You were losing but you still win.
4. Your option is exercised early and you now have an equity position. This is low probability and I will address this at length below but can be handled analogously to #3 - immediately close the equity position put to you and sell the same option option again -or- the same option in the next expiration cycle. I will argue that this almost always results in the same positive outcome as #3. You still win.
So firstly, you must convince yourself that options with more time to expiration must command a higher price than nearer term options, given the same strike price. I argue that this is true by virtue of the fact that if you ever find it not to be true then you can create a riskless calendar trade - selling the nearer term option for more money than you purchase the later term option - which is certain to net at least as much money as the net credit going into the trade and possibly much more. There are electronic arbitrageurs that constantly scan option-chains for these rare occurances and it is unlikely that a smallDogInvestor would ever encounter one.

Even knowing this, it has taken me some years of option trading experience to really be convinced that this TZR "out" can't be magically taken away at expiration like Lucy holding the football for Linus to kick. This is because when a short option position is running against you, its just unnerving to eyeball the red ink. One must resist the temptation to pre-empt the trade by closing it out and walking away. Hold it and roll it. Then roll it, til you make it.

As for the early exercise scenario, #4, the incentives for the option owner are against early exercise. This is because the exerciser of an option is foregoing the time-value of the option that he would have gained by simply selling the option. Furthermore, the time value of the cash obtained by exercising a put is almost nil these days because of the low interest rate environment we are in (least to mention you give up 3 days of interest clearing the trade.) The possible exception to this observation is for a dividend paying stock. A call option owner might decide to exercise on the last day of the dividend period (1 trading day prior to the ex-div date) in order to capture a dividend payment. Even still, said dividend must be larger than the time-value on the option (+trading fees) to make the exercise a profitable proposition. However, it is not difficult for the option obligee to evaluate this and roll early.

On the other side of the exercise, the option obligee gains this time-value in the event of an exercise because the contract ended early without him having to pay-up the time value that he would have otherwise had to pay to be released early from the contract. This time-value at the time of exercise provides monetary leeway for the obligee to dispose of the equity position, if desired. Immediately selling the same month's or next month's option will realize this time-value back to your account.

Now, the only real gotcha in this strategy is a total Lehman-like crash and burn, where a respectable \$50 stock suddenly and permanently stops trading over the weekend. In the case of Lehman, put obligees that were not exercised, would not have been able to roll perpetually because the option makers stopped creating new options for Lehman. While this is an ever-present risk for the premium seller, it is never-the-less extremely rare. For this reason, and other motivations, I do engage in protective option buying in a strategy called a diagonal that would limit the downside of such an adverse event. However, the existance of a reliable Twilight Zone Roll has redirected my trading focus. This is a fact-based strategy so I know I am not in that other place.

*Since I wrote this blog entry I have actually encountered a situation where I was quoted a small debit on a calendar roll. I believe this to be the work of dividends. In the particular case, the roll to the nearest next weekly option on SPY from SEP4 to SEP5 on the 134 strike puts was quoted as a debit of 5 cents or so. This time period spanned the ex-dividend date of SPY. However, I was able to roll to the OCT monthly expiration for a credit.

Thursday, September 8, 2011

sdi_yesterrange - overlay yesterday's price range on today's intraday chart

The high and low of the previous day are often reversal levels. The trading action tends to be choppy when price action stays inside of yesterdays range; outside the tendancy is toward's trending. sdi_yesterrange helps the intraday trader stay vigilent about yesterday's high and low by displaying a clouded range representing yesterdays price action on the intraday chart as shown below:

﻿﻿
 SPY with sdi_yesterrange.
﻿﻿By enabling the sideline parameter the range cloud can be thrown off to the right-extension area where it won't crowd your chart drawings. Also, the range cloud will automatically hide when you increase your aggregation period to DAY or larger.

Here's the code:
#########################
# sdi_yesterRange -
#hint: Display yesterdays range as a clouded area. rev: 1.0.0
# source: smallDogInvestor.blogspot.com
# author: allen everhart
# date: Sep 8, 2011
# copylefts reserved. This is free software. That means you are free
# to use or modify it for your own usage but not for resale.
# Help me get the word out about my blog by keeping this header
# in place.

declare upper;
#hint sideline: Set to Yes to display the range cloud in right extension area; No to display range cloud overlaying main chart.
input sideline = no ;

def _ph = high(period="DAY")[1];
plot ph =
if isNaN(close) && !sideline then
double.NaN
else if !isnan(close) && sideline then
double.NaN
else
_ph
;
def _pl = low(period="DAY")[1];
plot pl =
if isNaN(close) && !sideline then
double.NaN
else if !isNaN(close)&& sideline then
double.NaN
else
_pl
;
ph.setdefaultColor(color.RED);
pl.setdefaultColor(color.RED);
ph.setStyle(curve.lonG_DASH);
pl.setstyle(curve.LONG_DASH);

def agHide =  if getAggregationPeriod() >= aggregationPeriod.DAY then
yes
else
no
;
ph.sethiding(aghide);
pl.sethiding(aghide);
#########################################

Friday, September 2, 2011

Pre-Presidential Update

Here's a chart on the pre-presidential cycle update. The blue line is the projection from the beginning of the year, the magenta line is the projection from the current week. The oval is the range of divergence for the end of year time-frame that existed last month.

 SPX weekly with Pre-Presidential cycle projection.
This is uncharacteristically bearish for a pre-presidential year. The year open price has become a broken support. This level should then become a resistance level. In my opinion this bodes ill for an up-year, unless the market can break above with some energy.

Wednesday, August 31, 2011

sdi_openrange - display the open range on an intraday chart

The range exhibited during the cash-market opening is important to some intraday traders. Very often the high and low of the opening range are reversal levels. The sdi_openrange study will help you stay vigilant about these levels by displaying the opening range overlaying the main chart or on the sidebar. Also, this intraday study is smart enough to know when to get out of the way - if you reset your aggregation size (the duration of each chart bar) larger than the opening period sdi_openrange will hide so you don't have to fiddle with the chart settings to get a clean chart. Enabling the sideline parameter will throw the range cloud over to the right-extension area where it won't interfere with your chart drawings.

Here's the image and code:
﻿﻿
 SPX with sdi_openrange.
#########################
# sdi_openrange
#hint: Show the high and low range of the opening period. Rev:1.0.1
#rev 1.0.1 8sep2011 - refactor sidebar to sideline
# source: smalldoginvestor.blogspot.com
# author: allen everhart
# date: 31Aug2011
# copylefts reserved. This is free software. That means you are free
# to use or modify it for your own usage but not for resale.
# Help me get the word out about my blog by keeping this header
# in place.

declare upper ;
#hint openTime: Time of the cash-market open in your locality. Format:HHMM
input openTime = 0930 ;
#hint openMinutes: The duration of the opening period.
input openMinutes = 30 ;
#hint displayMinutes: Determines the number of bars to extend the open range cloud when displayed overlaying the main chart.
input displayMinutes = 120 ;
#hint sideline: Yes to display the open range on the right-extension area.
input sideline = no;

def minPerAg = getAggregationPeriod() / aggregationPeriod.MIN;
def elapseSecs = secondsFromTime(openTime);
rec startHi =
if elapseSecs == 0 then
high
else if between(elapseSecs, 0, (openMinutes * 60) - 1) then
Max(high, startHi[1])
else
startHi[1]
;
rec startLo =
if elapseSecs == 0 then
low
else if between(elapseSecs, 1, (openMinutes * 60) - 1) && startLo[1] == 0 then #rev2
low  #rev2
else if between(elapseSecs, 0, (openMinutes * 60) - 1) then
Min(low, startLo[1])
else
startLo[1]
;
plot sh =
if !sideline && between(elapseSecs, 0, (openMinutes + displayMinutes) * 60)  then
startHi
else if sideline && isnaN(close) then
startHi
else
double.NaN
;
plot sl =
if !sideline && between(elapseSecs, 0, (openMinutes + displayMinutes) * 60)  then
startLo
else if sideline && isnaN(close) then
startLo
else
double.NaN
;
sh.SetDefaultColor(color.YELLOW);
sl.SetDefaultColor(color.YELLOW);
def aghide =
if getAggregationPeriod() > openMinutes * aggregationPeriod.MIN then
yes
else
no
;
sl.setHiding(aghide);
sh.setHiding(aghide);
#################################

Monday, August 29, 2011

sdi_hivol - decorate volume moving average when volume exceeds threshold percent

One of the indicators that is used in the InvesTools method is volume moving average. In particular, a significant trading opportunity may be indicated when volume exceeds the volume moving average by 50%. Sometimes this is easy to eyeball, other times it is a close call for which you will need to do the math. In the spirit of keeping things simple I have created a study that decorates the volume moving average with triangles when the volume exceeds the percentage threshold. Here's the image and code:

﻿
 SPY with sdi_hivol indicating volume days exceeding 50% above volume moving average.
#############################
# sdi_hivol
#hint: Decorates the volume moving average with triangles when the volume exceeds a specified threshold percent.
# source: smallDogInvestor.blogspot.com
# author: allen everhart
# date: 29Aug2011
# Copyleft! This is free software. That means you are free
# to use or modify it for your own usage but not for resale.
# Help me get the word out about my blog by keeping this header
# in place.

declare upper ;

#hint type: Type of the volume moving average: simple or exponential
input type = { default SMP, EXP } ;
#hint length: Number of bars to use for volume moving average.
input length = 20 ;
#hint hotPct: Percent over volume moving average to trigger decorations.
input hotPct = 50.0 ;

def ma =
if type == type.SMP then
simpleMovingAvg(Volume, length)
else
movAvgExponential(vOlume, length)
;

plot hv =
if 100 * ((volume / ma) - 1) >= hotPct then
ma
else
double.NaN
;

hv.SetDefaultColor( color.CYAN);
hv.SetLineWeight(1) ;
hv.setPaintingStrategy( PaintingStrategy.LINE_VS_TRIANGLES);

###############################
﻿

Friday, August 26, 2011

sdi_open - display open price level of cash market

The sdi_open study displays the open price level of the "cash market" on an intraday chart.  For those of you who do not trade products like futures and currency spots, this distinction may seem a little odd. Futures and spots typically have an official opening time in the early evening hours, US Eastern time, which is not usually a time that creates a price level that you want to watch intraday. Rather, you are more interested in the print created when the US or European stock (or cash) markets open. In any case, sdi_open allows you to specify the open time that is of interest to you, in your locality, but it defaults to 9:30, the open of the US cash market, Eastern US time. As with many of these intraday price level studies that I write, sdi_open can be configured to show the level in the right-extension area by enabling the sideline parameter. Also, the sdi_open level will hide when the aggregation period of the chart is set to DAY or larger. Here is the image and code:

﻿﻿
 SPX with sdi_open price for 9:30 bar.
#########################
# sdi_open
#hint: Shows the opening price as a dotted price level on an intraday chart. rev:1.0.1
#rev 1.0.1 8sep2011 refactored sidebar to sideline
# source: smallDogInvestor.blogspot.com
# author: allen everhart
# date: 27Aug2011
# copylefts reserved. This is free software. That means you are free
# to use or modify it for your own usage but not for resale.
# Help me get the word out about my blog by keeping this header
# in place.

declare upper ;
#hint openTime: Time of the cash market open in your locality. Format:HHMM.
input openTime = 0930 ;
#hint sideline: Yes to show open price level in right extension area. No to show open price level overlaying main chart.
input sideline = no;

def elapseSecs = secondsFromTime(openTime);
def aggSecs = getAggregationPeriod()/1000;

rec openPrice =
if elapseSecs<0 && -elapseSecs < aggsecs  then
open
else if elapseSecs == 0 then
open
else
openPrice[1]
;
#plot es = elapseSecs ;

def agHide =  if getAggregationPeriod() >= aggregationPeriod.DAY then
yes
else
no
;

plot op =
if sideline && !IsNaN(close) then
double.NaN
else if !sideline && isnaN(close) then
double.NaN
else if openprice == 0 then
double.NaN
else
openPrice ;

Op.SetStyle(curve.POINTS);
op.setDefaultColor(color.dARK_ORANGE);
op.setHiding(aghide);

Monday, August 22, 2011

sdi_yearClose - Display Last Year's Closing Price

This study is an off-shoot of my study sdi_yesterClose. It started as an enhancement to yesterClose but, due to limitations in ThinkScript (no support for the aggregation period: YEAR), it was just cleaner and easier to put this out as its own study. Like many of my scripts you can choose whether you want to see the level overlaying the main chart or on the right-extension area via the sideline parameter. Here's the image and code:

 SPX with sdi_yearClose study.
############################################
# sdi_yearClose: Display Last Year's Closing Price
#hint: Displays last year's closing price. rev 1.0.2 http://www.smallDogInvestor.com
# author: allen everhart
# date: 21AUG2011
# rev:1.0.2 15july2013 corrected incompatibility with a tos update that produced a java stack overflow.
# rev:1.0.1 8sep2011 refactored sidebar to sideline
# copylefts reserved. This is free software. That means you are free
# to use or modify it for your own usage but not for resale.
# Help me get the word out about my blog by keeping this header
# in place.

#hint sideline: Where to show the yesterClose. If yes then yesterClose only displays in the right extension area of the chart otherwise yesterClose displays in the regular chart area.
input sideline = no;

plot yr =
if isNaN(close) && !sideline then
double.NaN
else if !isNaN(close) && sideline then
double.Nan
else
getvalue( close( period=aggregationPeriod.MONTH), getMonth())
;

yr.setDefaultColor(color.BLUE);
yr.setStyle(curve.POINTS);
##########

Sunday, August 21, 2011

sdi_yesterClose - Display Yesterday's Closing Price On Today's Intraday Chart

If you are an intraday trader then you know it is vitally important to be vigilent about yesterday's closing price because it is often the case that this is where price movement is challenged. The sdi_yesterClose study will help you stay vigilent by plotting yesterday's closing price on your intraday chart. Also, it has the hooks to display the previous close of a variety of aggregation periods such as last week or month. As an added convenience, you may set it to display only in the right extension area (sideline.)  Moreover, this study will hide if you increase your chart's aggregation period up to a level where it does not make sense to display (e.g. you change from intraday to daily.)  Here's an image of the study followed by source code:

﻿
 SPX intraday plot with yesterday's closing price.

############################################
# sdi_yesterClose: Display A Previous Closing Price
#hint: Displays yesterday's closing price. rev 1.2.2 http://www.smallDogInvestor.com
# author: allen everhart
# date: 21AUG2011
# rev:
#   1.2.2 13jul2013- corrected incompatibility with new tos.
#   1.2.1 8sep2011- refactor sidebar to sideline
#   1.2 21aug2011- was not extending value to right on sideline
#   1.1 21AUG2011- fixed bug with 2 DAYS, 3 DAYS selections
# copylefts reserved. This is free software. That means you are free
# to use or modify it for your own usage but not for resale.
# Help me get the word out about my blog by keeping this header
# in place.
declare upper ;
#hint yesterPeriod: The aggregation period from which to select the previous closing price. When you adjust the chart aggregation period equal to or greater than yesterPeriod then the yesterClose will automatically hide.
input yesterPeriod = aggregationPeriod.DAY;
#hint sideline: Where to show the yesterClose. If yes then yesterClose only displays in the right extension area of the chart otherwise yesterClose displays in the regular chart area.
input sideline = no;

#plot prox = proximity;
plot yc =
if !sideline && IsNaN(close) then
double.NaN
else if sideline && !isnaN(close) then
double.NaN
else
close(period = yesterPeriod)[1] ;

def agHide =  if getAggregationPeriod() >= yesterPeriod then
yes
else
no
;

def hidePc =   if agHide then
yes
else
no
;
yc.setHiding( hidePc );
yc.SetStyle(curve.POINTS);
yc.setDefaultColor(color.RED);

#

Thursday, August 18, 2011

sdi_atr - Average True Range In Chart Label

ATR (Average True Range) is a calculation that shows how much you might expect the given equity to move during the course of the next chart bar. Most chart packages will display ATR as a subgraph study. Now, to my mind, that's a lot of screen real estate to invest in a calculation for which I am mostly interested in the current value. In other words, I have little need to do technical analysis on ATR. So my ATR simply plots as a chart label in the upper left hand corner. Sometimes it is interesting to know if ATR is rising, flat or falling so I color code the label green, orange or red, respectively. Here is an image:

﻿﻿
 SPY with ATR in a label on upper left
﻿ ##########################################################
# sdi_atr: Display Average True Range as a label
#hint: Displays the AverageTrueRange as a color-coded chart label. Red=decreasing, Orange=level, Green=increasing. Version:1.0
# source:http://www.smallDogInvestor.com
# author: allen everhart
# date: 10Mar2011
# copylefts reserved. This is free software. That means you are free
# to use or modify it for your own usage but not for resale.
# Help me get the word out about my blog by keeping this header
# in place.
declare UPPER ;
input length = 14 ;
def bar = avgTrueRange(high,close,low,length);
if bar>bar[1] then
color.GREEN
else if bar== bar[1] then
color.ORANGE
else
color.RED
);

#################

Sunday, August 7, 2011

sdi_ma - moving average with my own kung-fu.

One might not think that there is much innovation left in the basic moving average study but I, hereby,  challenge you to think again. In the moving average study presented below I introduce several innovations that I have not seen elsewhere:

﻿
 CAT with sdi_ma
﻿

Firstly, I introduce the idea of a linear extension. I take the change between the last two bars of the moving average study and project that as a straight line into the future. This is the dashed red line that eminates from the 30 day exponential moving average like a laser-beam from the head of a snake.

Secondly, I introduce the idea of color coding to help illuminate trending vs. flat behavior. Where the moving average is orange is where the moving average is within 5% of the moving average value 30 (configurable) bars prior. Where the moving average is red is where the moving average value has moved more than 5% away from the moving average value 30 bars prior. Because of the distortions introduced by modern charting techniques it is not always readily apparent when the squiggles in the moving average really amount to much percentage-wise. Also, if you are a follower of the InvesTools method this will help you discern when to apply the volume rule to a trading signal.

An alternative criteria is used for the color-coding switch on less volatile stocks. If the moving average has moved up or down 30 (config.) consecutive bars without moving more than 5% then the color also changes to red to indicate a quietly trending stock.

Lastly, I introduce the concept of decorating the moving average to show when the underlying price has moved significantly far away, percentage-wise, from the average. In the above chart above of CAT we see that the last two bars of the moving average are decorated with pink triangles. These are configured to display when the price is more than 10% away from the moving average. CAT has been beat up by the anticipated downgrade of US debt which has resulted in a rapid price decline and CAT might be oversold here.

Here is the code for the study:

#########################
# sdi_ma: Small Dog Investor Moving Average
#
#hint: Displays a moving average with some additional signals. In the default configuration, when the MA is trending, as defined by 30 consecutive up/down moves, OR the MA is more than 5% away from the MA 30 bars prior then the MA appears in red. When the moving average is nontrending and within 5% of the value 30 bars prior then the MA appears in orange. When price is more than 10% away from the MA, the MA line is decorated with hot pink triangles. In the right extension we show a straight line projection taken from the last two bars. Version: 1.1
#
# source: smalldoginvestor.blogspot.com
# author: allen everhart 8/4/2011
# revised: 8/21/2011 added price data series selection.
#
# copylefts reserved. This is free software. That means you are free
# to use or modify it for your own usage but not for resale.
# Help me get the word out about my blog by keeping this header
# in place.

#hint price: Choose data series to average over.
input price = close;
#def price = close;
#hint type: Choose between Simple and Exponential Moving Average.
input type = { default EXP, SMP } ;
#hint length: Number of bars in moving average.
input length = 30 ;
#hint flatPct: Main criteria for color-coded trend changes.
input flatPct = 5.0 ;
#hint compLength: Number of consecutive up/down bars to use as the secondary criteria for color-coded trend changes.
input compLength = 30 ;
#hint hotPct: Criteria for the hot decoration.
input hotPct = 10.0 ;

def ma =
if type == type.SMP then
simpleMovingAvg(price, length)
else
movAvgExponential(price, length)
;
rec maUpBars =
if ma > ma[1] then
maUpBars[1] + 1
else if ma == ma[1] then
maUpBars[1]
else
0
;
#plot up = maUpBars ; # diagnostics
if ma < ma[1] then
else if ma == ma[1] then
else
0
;
#plot dn = maDnBars ; # diagnostics
plot steep =
if AbsValue(100 * ((ma / ma[compLength]) - 1)) >= flatPct then
ma
else if maUpBars >= compLength then
ma
else if maDnBars >= compLength then
ma
else
double.NaN
;
steep.SetDefaultColor( color.RED);
steep.SetLineWeight(2) ;
plot flat =
if AbsValue(100 * ((ma / ma[compLength]) - 1)) < flatPct then
ma
else if maUpBars < compLength then
ma
else if maDnBars < compLength then
ma
else
double.NaN
;
flat.SetDefaultColor( color.ORANGE);
flat.SetLineWeight(2) ;

#plot pct =100 * ((ma / ma[compLength]) - 1);
#plot bkma =  ma[compLength] ;
plot hot =
if AbsValue( 100 * ((price / ma) - 1) ) > hotPct then
ma
else
double.NaN
;
hot.setDefaultColor( color.MAGENTA);
hot.setPaintingStrategy(paintingStrategy.LINE_VS_TRIANGLES);
rec slope =
if isnaN(close) and !isnaN(close[1]) then
ma[1]-ma[2]
else if isnaN(close) and isnaN(close[1]) then
slope[1]
else
double.NaN
;
rec extrec =
if !isnaN(slope) and isnaN(slope[1]) then
ma[1]+slope
else if !isnaN(slope) then
extrec[1]+ slope
else
double.NaN
;
plot ext = extrec ;
ext.setDefaultColor(color.RED);
ext.setStyle( curve.SHORT_DASH);

#