Sunday, December 29, 2013

when it pays to pay-to-roll

one of the premium seller's commandments liz and jny of tastytrade make is "never pay to roll an option." this is dubious advice, imho. in my experience, paying to roll a short option almost always improves your position's p&l. so i'd like to make the pro-argument in the pay-to-roll debate.

here's a hypothetical based on the real life equity CME:

one week back cme was riding high - made a new 3 year high. suppose we had decided to sell the 84 put expiring in january that week on dec 18. according to the thinkback we would have gotten $3.05 of credit to sell that put:

that was then, dec 18

were that so our cost-basis in the shares would be 80.95 (=84-3.05) and our broker would set aside $8095 per contract of buying power in a non-margin account to purchase the shares should we be assigned.

now flash-forward to today - cme paid a special dividend of 2.60 and sold off to  78.91:

this is now, dec 29

here's what one can do in this situation: buy back the jan puts and sell the feb 77.5 puts for $3.05 debit, giving back all the credit we took in on dec18. however, now our cost basis becomes 77.5 (+2 commissions), $3.45 lower than $80.95 we had before. moreover, we actually recover $345/contract of buying power (not lose $305/contract!) of buying power, since now we only have to set aside $7750/contract of buying power to buy the shares.

why wouldn't you do that!?

if we had simply bought the shares on dec 18 for 84.64 we would now be smoking hopium looking at a $5.77 loss and waiting for the $2.60 dividend payout to lessen the pain. while this special dividend situation is somewhat unusual it is not unusual to be able roll a short put diagonally down with a drop and recover more buying power than paid out while at the same time lowering cost basis.

Thursday, December 26, 2013

frisky dogs of the dow

one of the first investment strategies i took seriously was the venerable dogs of the dow strategy. in that strategy one buys equal dollar amounts of stock of the top-ten dividend payers in the dow. this is done at the beginning of the year which is why you might be hearing about it in the media once again. there is at least one variant of this strategy that i also once took seriously: the small dogs of the dow. in the small dogs of the dow one invests in only the 5 lowest priced dogs of the dow. to be sure, i borrowed the appellation for the title of this blog.

now, after being steeped in option selling techniques i would like to propose a new strategy of investing in dow stocks that is based on option metrics: frisky dogs of the dow. in the frisky dogs strategy i select the ten dow stocks with the highest implied volatility percent range (or iv percentile, or iv rank as it is variously known in the haunts i frequent.) iv%r tells you where in last 52 week range the current implied volatility lies. stocks with a high iv%r are more active and usually this is because they have recently sold off, thus they are dogs. 

here is the current list of frisky-dogs listed in small dog order:

my idea is that one should short puts on some or all of these stocks starting in january and roll them from month to month to take advantage of time-decay. at the end of 2014, a new list is generated indicating which stocks are to be added or removed from the portfolio. i would drop the smallest frisky-dog, csco, as it does not pay a good enough premium relative to my commission structure.

happy new year to all.

Saturday, December 21, 2013

how now dow?

every once in a while i trot out my dow/gold ratio chart to see where the economy has gotten to. here's the image:

this ratio purports to measure the value of the stock market in terms of what is considered to be a stable store of value: gold. economists like this sort of chart because it automatically corrects for inflationary effects. a side-effect is that it also corrects for distortions that flow from central bank monetary policies and political policies that fixed the price of gold (such as existed from FDR to Nixon administrations.) historically, this ratio tends toward a value of 20. in exceptionally bad times the number goes into the single digits, in exceptionally good times the number goes into the 30's and 40's. however, i can only produce a chart of the last 20 years in thinkorswim.

as it stands, the ratio has broken into the teenager range that existed prior to the 2008-9 bubble-burst. my expectations are that the ratio could spend some time in the 13-15 range. the probability is good that we will see multiple tests of the 15 level before breaking through. one might consider a pairs trade to short gold and buy the dow.

Saturday, November 30, 2013

how options give smalldog investors the bigdog advantage

one of the benefits of trading options is that they are levered products. in a stock replacement strategy the typical procedure is to buy a 70 delta call option in an expiration that is 90 or more days away. one typically pays less than 1/3 of the price of buying the shares with that method. the question is: how much leverage does that represent? the answer may surprise you but first i need to develop the concept of option leverage a little.

the key to understanding option leverage is thinking about delta in a different way. the definition of delta is that it describes the relationship between option price movement and the underlying equity's price movement. in a 70 delta option, a one dollar move in the equity leads to a 70 cent move in the option. however, an equally valid way to think about delta is that a 70 delta option gives you 100% of the performance of 70 shares of stock. so to figure the leverage of a 70 delta option one simply needs to compare the price of the option to the cost of purchasing 70 shares of stock or: 

delta * equity price / option price

thus, our 70 delta option purchased at 1/3 the price of the stock equals leverage of 2.1 (=.7*3)  - about the same leverage you get with a typical margin account where you put up 50% of the buying power (but without the sec looking over your shoulder!)

now, there is a special kind of margin account called a portfolio margin account that is only available to bigger dogs than me who can put together $100K in a non-retirement account. in a portfolio margin account one only puts-up buying power equal to 5% of the cost of the stock purchase, or leverage equal to about 20. so the question is can a smalldog stock-replacement trader achieve this same advantage?

yes! one can, but one needs to be a little less rigid about selection. here's the option chain on spy for the feb14 expiration (about 90days-to-expiration) with the mark (mid bid-ask) price and delta displayed:

the first strike (180) in-the-money, has a leverage of 21.6 (= .53 * 181 / 4.45 ) and the 2nd strike (179) itm  has a leverage of 20.4 (=.57*181/5.05). however, this 57 delta option is a little low for many stock replacement traders.

you see, another interpretation of delta is that it is approximately equal to the probability of expiring in-the-money and a 57% chance, though better than a coin flip, is playing a little too close to the edge. however, one can increase the delta by accepting fewer dte and still achieve 20x leverage. here's a look at the jan14 with 48 dte:

i calculate that the 175 strike call has a leverage of 20.2 (=.77*181/6.905) and is right smack in the middle of the 70 delta range coveted by stock replacement traders.

so who needs portfolio margin!?

Monday, November 25, 2013

thinkscript_included: sdi_ivpls - the popular iv rank (aka percentile) as a lower study

following on the succes of the popular iv rank, or percentile as it was originally called, there have been requests to show the graph of the indicator. simple enough, so here's the image of this new lower study called sdi_ivpls:

and here's the code:

# sdi_ivpls: Display Implied Volatility Percentile as a lower study
#hint: Displays the Implied Volatility Percentile as a chart lower study. sdi_ivpls rev: 1.0
# author: allen everhart
# date: 11/25/2013
# 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 period = AggregationPeriod.DAY ;
#hint period: time period to use for aggregating implied volatility. sdi_ivpls rev: 1.0
input length =252 ;
#hint length: #bars to use in implied volatility calculation.
def ivGapHi = if isnan(imp_volatility(period=period)) then 99999999999 else imp_volatility(period=period);
def ivGapLo = if isnan(imp_volatility(period=period)) then -99999999999 else imp_volatility(period=period);
def periodHigh = highest( ivGapLo,length=length);
def periodLow = lowest( ivGapHi, length=length);
def ivRange = periodHigh - periodLow ;
def ivp = round( 100*(imp_volatility(period=period) - periodLow)/ivRange, 0);
#plot labelColor = 0; # only to pull in color select widget
#labelColor.setHiding(1) ; #never want to show this
#AddLabel(1, Concat("IV%: ", ivp), labelColor.takeValueColor() );
plot ivpr=ivp;

Sunday, November 17, 2013

thinkscript included: release 1.2.0 of sdi_aispy

this version of my aispy strategy corrects the p&l of the for the effects of commissions. i do this by slipping the purchase prices by the round-trip cost of commissions per share.  here is a picture of this strategy in comparison to the passive strategies of buy 'n hold and dollar-cost-averaging:

aispy rev 1.2.0 ,10 year comparison with buy and hold

as always, the updated version is published on the original blog post which you can find here.

correcting for commissions this strategy is showing underperformance relative to buy 'n hold but a significant overperformance relative to dollar-cost-averaging. to my mind the comparison to dca is more appropriate and realistic. however, my question to you, the reader, is who really engages in buy 'n hold? doesn't that presume you are in possession of your entire life savings at an early age,  go all-in, and never add!?

Tuesday, October 22, 2013

thinkscript included: sdi_tde rev 1.1 release, add 0.5 to after-market releases to group before and after market releasors.

previously, sdi_tde assigned the same count of trading days to earnings to before and after market releasors. this complicated the task of finding the after-market today and the before-market tomorrow releasors. now sdi_tde adds 0.5 to the count of trading days to earnings of after-market releasors so that they group separately from the before-market releasors. here's a picture of the new custom watchlist column that i now call tde:
watchlist of equities with weekly options sorted in the order of upcoming earnings
in the above list a tde of 0.5 indicates an equity with an earnings release after market-close today and 1.0 indicates an equity with an earnings release before market-open tomorrow. tde numbers update when the cash-market opens at 9:30am eastern.

as always i maintain the source code on the blog of the original release, here.

Sunday, October 6, 2013

thinkscript included: customize your watchlist to sort in the order of upcoming earnings

with the pace of enhancements to the tos platform i guess i shouldn't be too surprised that i stumble on things i didn't know were there. however, i've long been frustrated by the fact that there wasn't a natural mechanism to sort a watch-list in the order of upcoming earnings. so, today i set about building a custom column to show something like days to earnings when i stumbled on the function, geteventoffset(). geteventoffset() returns the number of bars into the future of a corporate event. this was an easy button for creating the custom column i call bte (bars-til-earnings.) 

Equities with weekly options sorted in order of upcoming earnings
here's the thinkscript for this column:

# sdi_tde: trading days til earnings
#hint: displays the trading days til earnings. after-market earnings add 0.5 to the count. this code is meant to be pasted into a custom watchlist column. rev: 1.2
# author: allen everhart
# date: 08oct2013
# rev 1.2: 8mar2014 color code the after-market earnings.
# rev 1.1: 22oct2013 add 0.5 if earnings are after-market.
# 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.

input length=60;
def xx = -getEventOffset(Events.EARNINGS);
def yy = sum(HasEarnings(type = EarningTime.AFTER_MARKET),length)[-length +1] > 0;
plot x=xx+yy*.5;
x.assignValueColor( if yy!=0 then color.LIGHT_RED else color.DARK_GRAY);

the only little gotcha is the minus sign. geteventoffset() returns negative numbers because in thinkscript a negative offset is a reference in the future time direction. 

here's how to get this custom column on your watch-list:

  1. right click on any column heading in your watch-list and select customize at the top of the pop-up list.
  2. scroll the available items list of the watchlist dialogue and click on the left-hand icon of one of the custom columns that you haven't already used.
  3. replace the default column name with bte in the column name text entry box of the custom quote formula dialogue.
  4. click on the thinkscript editor tab and replace the default formula with the thinkscript: -GetEventOffset( eventType = Events.EARNINGS)
  5. click ok
  6. click add item(s)>> button
  7. click move up or move down buttons to position the bte column to your preference.
  8. click ok

happy trading to you

Saturday, October 5, 2013

lessons of ai: trading underperforms a trending market

its been about 6 months since i published aiSpy (queue cheesy background music,) an artificial intelligence strategy for trading the etf spy. i was a little disappointed that the real-world testing of aiSpy was underperforming the passive investing techniques buy 'n hold and dollar-cost-averaging. i was expecting that when i ran the numbers i would see a reversion to randomness in the real-world numbers. that is to say i thought the numbers would revert to something like a coin-toss with a win/loss ratio very close to 1 and a risk/reward ratio a smidgeon less. instead the numbers worked out to 8 wins and 4 losses for win/loss of 2. the average dollars lost on a losing trade was 66.42 and the average dollars won on a winning trade was 60.33 (both corrected for commissions.) this gives a risk/reward ratio of 1.10 (=66.42/60.33) 

this fits my criteria for a winning strategy whereby:

win/loss > risk/reward

in fact these numbers are rather impressive for automated strategies. for the ones i've evaluated it is rare that an actual edge of this sort holds up and rarer still for the edge to be this large. usually i see something like 1.8 for win/loss and 1.7 for risk/reward.

so why the underperformance? 

i think this has to do with the real-world era under comparison. the last 6 months has been an upward trending period for the market. thus, trading underperforms a trending market. perhaps, this is a bit obvious but the market has just come through a decade long era of sideways action. if you are using aiSpy for trading you should think about how long the market might continue trending. if you believe this trend is not done then buy 'n hold is a better strategy otherwise aiSpy should outperform in the next 6 months. i leave it up to you.

Sunday, September 29, 2013

thinkscript included: sdi_seaproj - seasonal projection of price

sdi_seaproj is the latest incarnation of my seasonal projection study. i feel this is not only superior to my previous sdi_seapro5 but also to the seasonality chart mode provided by thinkorswim.  then again, every child is brilliant in the eyes of its parent. here's an image of the new seaproj:
sdi_seaproj of 10, year-long seasons anchored 20 weeks before current bar.
relative merits over tos seasonality:
  • plots on a regular chart - no need to switch to a special charting mode.
  • has choice of anchor date - tos seasonality chart mode is permanently anchored to january 1, whereas sdi_seaproj can anchor to a variable date trailing a parameter number of bars in the past or a fixed date of one's choosing. anchoring near the last bar of the chart plots the projection mostly into the right extension area leaving the main chart relatively uncluttered for technical analysis.
  • provides reliability indicator - tos seasonality provides no statistical measure of the distribution of seasonal data whereas sdi_seaproj provides a reliability indicator based on standard deviation to show when seasonality is reliable or not.
  • can skip an anomalous season - sdi_seaproj has a parameter one can specify to remove an anomalous season from the average. this was mentioned by larry williams (of williams %r fame) as being crucial to utilizing seasonality charting.
  • can explore subcycles - sdi_seapro has parameters one can specify to define the season length and number to average. this frees one to explore cycles in the chart data on any scale, whereas tos seasonality is limited to a season length of one year and season number defined by the chart duration.
relative merits over sdi_seapro5:
  • variable number of seasons -previously, sdi_seapro5 was limited to a fixed five-season average. now, in sdi_seaproj, i utilize the fold statement of thinkscript to process a user specified number of seasons. as a consequence sdi_seaproj cannot show individual season projections which require a separate, valid, plot object to be statically declared for each season. this turns out to be a minor detraction since there is a reliability indication in the sdi studies.
  • flat line color tied to projection average color. previously one had to change the color of both of these plots separately.
  • plot starts on anchor date close. previously, in sdi_seapro5, the plot of the average started on the bar after the anchor date. now, in sdi_seaproj, the plot starts on the close price of the anchor date to provide confidence in the correct date selection.
  • reliability indicator color chooser. previously, in sdi_seaproj5, the color of the reliability indicator was fixed to green/red, now, in sdi_seaproj, one can choose the up/down colors for ri.
  • simplified reliability indicator. previously, in sdi_seapro5, there were indicators that decorated the top edge of the reliability indicator that did not provide much in the way of actionable information. now, in sdi_seaproj, the reliability indicator is simplified to one job: showing where the standard deviation bands cross the flatline. there is a straightforward parameter called, ri factor, that determines the multiple of standard deviation to utilize in the reliability indicator.
here's the code: (how to install)
# sdi_seaproj: Season Seasonal Projection Of Price
#hint: Displays a seasonal projection of price based on the average percentage price move between the anchor date and same seasonal dates in the past. Also shows a reliability indicator to help discern which stocks have seasons reliable enough to trade. sdi_seaproj revision: 1.0 source:
# author: allen everhart
# rev 1.0 date: 28sep2013
# 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. 

input trailAnchor = 0; #hint trailAnchor: Sets Moving anchor date to n-bars ago. FixedAnchorDate takes precedence over trailAnchor. The plot of the seasonal average always starts on the close of the anchorDate bar. sdi_seaproj revision: 1.0 source:
input fixedAnchorDate = 0; #hint fixedAnchorDate: Sets an anchor date that does not move. Format: YYYYMMDD. FixedAnchorDate takes precedence over trailAnchor. The plot of the seasonal average always starts on the close of the anchorDate bar.
input numSeasons = 5 ; #hint numSeasons: Number of seasons to average.<br><br>note: On the shorter chart durations (1-5 years) thinkscript can access data beyond the scope of the chart. If the projection is not displaying then select fewer seasons and/or increase the chart duration.
input lenSeason = 52 ; #hint lenSeason: Sets number of bars in a season. <br><br>note: There are about 252 trading days per year for US stocks and about 260/year for futures and forex.
input skipSeason = 0 ; #hint skipSeason: Suppress an anomalous season from the average. Skipping a season causes the average to look back an extra season so as to preserve the numSeasons in the average.
input riFactor = 0.3 ; #hint riFactor:multiple of standard deviation to use for ri (reliability indicator.) the ri shows when there might be a reliable trade based on seasonality. the up-ri shows when the lower band line (riFactor*stdev) tracks above the flat line. the down-ri shows when the upper band line tracks below the flat line. <br><br>note: 54% of the individual year projections are above the 0.1*stdev band, 62% above 0.3*stdev, 73% above 0.6*stdev and 84% above 1.0*stdev.  

def anchorDate =
  if fixedAnchorDate > 0 then
  else if trailAnchor > 0 && !IsNaN(close[-trailAnchor]) && IsNaN(close[-trailAnchor - 1]) then
  else if trailAnchor > 0 && anchorDate[1] > 0 then # 1.5.2 added [1] to originDate
#plot od = originDate;

### pn tells us how many bars we are past the originDate
def pn =
  if !pn[1] && GetYYYYMMDD()[1] == anchorDate then
  else if !pn[1] && IsNaN(close) && !IsNaN(close[1]) then
  else if pn[1] > 0 then
    pn[1] + 1
#plot p=pn;

#number of seasons we are skipping
def skipNum = if skipSeason > 0 && skipSeason <= numSeasons then 1 else 0 ;

def avgPctMove =
  if pn > 0 then
    fold sn = 1 to numSeasons + skipNum + 1 with psum=0 do
        if sn != skipSeason then
            psum + ((GetValue(close, sn * lenSeason) / GetValue(close, sn * lenSeason + pn)) / numSeasons)
  else 0

def flatLine =
  if pn[-1] == 1 then close
  else if pn >= 1 then flatLine[1]
  else 0;

plot pa =
    if pn[-1] == 1 then close
    else if pn > 0 then avgPctMove * flatLine
    else Double.NaN ;

plot fl = if pn[-1] > 0 then flatLine else Double.NaN; # flat line
fl.SetStyle(Curve.SHORT_DASH) ;

def variance =
  if pn > 0 then
    fold ssn = 1 to numSeasons + skipNum + 1 with pvar=0 do
        if ssn != skipSeason then
            pvar + (Sqr(GetValue(close, ssn * lenSeason) - pa) / numSeasons)
  else 0
def pstd = Sqrt(variance);

def hpul =  pa + (riFactor * pstd);
def hpll =  pa - (riFactor * pstd);
#plot ul = hpul ;
#plot ll = hpll ;
plot ri = # High Probability indicator
  if riFactor == 0.0 then
  else if pn > 0 && hpll > flatLine then
  else if pn > 0 && hpul < flatLine then
ri.DefineColor("Up", Color.UPTICK);
ri.DefineColor("Down", Color.DOWNTICK);
AddCloud( ri, fl, ri.Color("Up"), ri.Color("Down") );

Sunday, September 22, 2013

lessons of ai: aiSpy 6 months later ...

last spring, i unveiled a study called aiSpy that i had created (with a good deal of effort mind you) that implemented a form of artificial intelligence called a feed-forward network. this feed-forward network was static, that is it didn't modify itself but was the end result of an extensive genetic training program. ffn's are used to do complex pattern recognition for speech-to-text and handwriting recognition and many other human-interface applications you may be familiar with in your cell phone.  if there were patterns to the complicated dance of the market then they ought to have ended up encoded in the ffn, which at the time of release was outperforming buy and hold over 2, 5 and 10 year periods.

so how did aiSpy do in the real world? here's a picture of the performance over the last 6 months, post-training:
last 6 month performance of aiSpy.

the p&l for aiSpy, trading $10,000 per trade, is circled, 497.08, and contrasted to the growth of $10,000 bought 6 months ago and held (bnh, green number in square)  and the growth of $10,000 invested in 6 increments (dca, blue number in square.) bnh is the winner with a $967 gain, dca came in 2nd with a $545 gain and aiSpy third with a $497 gain. i should note that the aiSpy p&l does not include the impact of commissions, which at the standard thinkorswim rate amounts to $10 per round-trip, or $120 over the last 6 months for 12 twelve trades. the aiSpy result is an even more distant 3rd. while this is a lack-luster result, at least it is positive. what went wrong? i think i know and this knowledge is helping me improve my trading and i will share this in a series of posts called lessons of ai.

Wednesday, September 18, 2013

thinkscript included: sdi_ivp revision 1.2 - choose your color

i am thrilled that tastytrade has incorporated my sdi_ivp chart label into their on-air charting. it is wonderful to give back to this community. however, i am seeing that not everyone is thrilled with my choice of plum for the color of the label (too close to yahoo-logo color?) the 1.2 revision enables you to choose your own color without having to edit the code.

here's how the color chooser works:

goto edit studies by clicking on the beaker icon on the top bar of the chart and rightclick on the sdi_ivp study. this gives:

the labelColor plot only exists to pull in the color chooser widget that comes with plot objects, all visible manifestations of it are hidden.

click on the color box and you get the color chooser drop down:
click on one of the 9 standard colors then click ok/ok. when i click on dark blue the label color changes:

or click on the select button in the color chooser to choose a color from a broad palette of colors or input the explicit rgb values if you know them:

as always i maintain the revised source code in the original post for sdi_ivp

Friday, September 13, 2013

thinkscript included: sdi_ivp version 1.1 released.

previously sdi_ivp would print N/A on equities that contained gaps in the data feed for implied volatility. most notably this applied to aapl, which did not have implied volatility data for 8/7 and 8/8/2013. in the 1.1 version sdi_ivp ignores the data gaps in implied volatility and produces the same implied volatility percentile number that you get on the trade tab. this has been checked for the s&p 100.

here is aapl with the 1.1 version of sdi_ivp:

the code source for 1.1 is on the original release post for sdi_ivp

Sunday, September 1, 2013

follow the money ... trade bear put diagonals

deep throat: follow the money.
bob woodward: what do you mean? where?
deep throat: oh, i can't tell you that.
bob woodward: but you could tell me that.
deep throat: no, i have to do this my way. you tell me what you know, and i'll confirm. i'll keep you in the right direction if i can, but that's all. just... follow the money.
-all the president's men (1976)
spy put diagonal, time unit-cost is  .48/week (3.35/7)
i am in the calendar vending business. selling a calendar is what happens when one rolls a shorted option from one expiration period to the next. this nets a credit because, in the option world, time-is-money and the same strike option with more dte (days-to-expiration) is generally worth more money.

the problem is that markets move. the price of the underlying can move far from the strike of my short option and this reduces what i can collect on the roll when the time comes. so it behooves me to heed deep-throat's advice and follow-the-money so as to be rolling shorted options that are as close as possible to the underlying's price as expiration draws nigh.

the bear-put-diagonal helps with this problem because it is such a flexible trade. when time has run down on the shorted option, the bear put diagonal can almost always be adjusted in such a way that the shorted option ends up closer to the money yet the adjustment still nets a credit.

i initiate my bear-put-diagonals on the eve of earnings reports. this is when implied volatility will be inverted - the near term options price way higher than the remaining time warrants due to event risk. i prefer equities with weekly options because there are always soon-to-expire options available when earnings come due for reporting. often-times my bear-put diagonals are profitable the next day because of the crush in implied volatility that occurs post-event.

to initiate the trade i sell the first otm strike in the weekly options and purchase the first itm strike in an expiration that is 90 or so days away. the near-term option should price something like 50% of the far-term option. the reason for the 90 days is that that purchases time in bulk. the option market naturally discounts bulk purchases of time in proportion to the square root of remaining time. this makes it possible to sell time in smaller chunks in the form of week-to-week calendars, via roll transactions, that add up to more than the bulk purchase. one can think of this as a wholesale/retail business except the product being vended is time.

higher priced stocks are more efficient, commission-wise. i generally prefer stocks above 30 for bear-put diagonals since i am paying two commissions per diagonal and these higher priced stocks tend to be better quality companies anyway.
i always purchase the put diagonal in multiples of 3 or higher because, if need be, this facilitates morphing the trade into a backratio. this is how i adjust the trade for a stock that gaps-up big.

the risk of the bear-put diagonal is limited to the purchase price of the trade. the trade may post a loss initially on gapping behavior but after following through with adjustments and rolls it is hard to envision a situation that would lock-in a full loss for a 90 day duration. still, i size my trades so that the full loss is a small acceptable portion of my account.

after acquisition i rest a gtc limit order to sell at 25% gain. this is the goal. also, i make note of the unit-cost of time by dividing the cost of the diagonal by the number of roll opportunities. the next day, after the vol-crush, if the trade is profitable but the gtc order has not filled then i close the position at market. otherwise i manage the trade for the long haul and this means dealing with gapping behavior after earnings.

if the underlying has gapped up then when the shorted puts are nearly worthless i buy them back and sell the next week's options usually at a higher strike closer to the money. one can always morph the bear diagonal into a calendar, with no additional risk, by selling the same strike as the far-term put. selling strikes higher than the far-term put is possible too but increases the risk in the trade in proportion to the difference in the strike prices. when chasing the money two or more strikes above the far-term put's strike price i sell one fewer option than i bought-back. this morphs the trade into a backratio. if the market subsequently sucker-punches me with a sharp reversal then i have the extra long-put that will at least ease my pain if not drive the trade to profitability, depending on how vol expands. the rolls of two atm short puts more than pays for three long puts.

if the underlying has gapped down on earnings then there is usually some way to roll the whole position down for a net credit. re-establishing an atm bear-put diagonal is preferable but, if that fails to generate a credit, then i consider morphing into a calendar, a bull-put diagonal or a backratio. shifting the long put down more strikes than the short put is a powerful engine to generate credit especially because this works in the direction of volatility (ie lower prices in the underlying increase implied volatility.)

it has been my experience that equities tend to stabilize after gapping on earnings. so after the post-earnings adjustment the trade management typically devolves into the business of rolling options. my bear-put-diagonal-earnings trades have moved the meter on my account and have become my go-to trade. i plan to share a few of them on mytrade in the near future.

happy trading to you.


Saturday, August 24, 2013

sdi_passive revision 1.2.0 released.

sdi_passive is a study that shows the growth of a $10,000 investment using two basic passive strategies, bnh (buy-and-hold) and dca (dollar-cost-averaging.) previously my dca (dollar-cost-averaging) simulated a purchase on every bar of a chart. this presented an unrealistically negative view of dca when displaying on day charts because of the impact of commissions. now dca simulates a purchase on a configurable frequency which defaults to 21 (average number of trading days per month.) this allows one to accurately  model both dca and bnh on a day chart.

additionally sdi_passive has been enhanced to display chart labels containing the accumulation of dividends for bnh/dca and the accumulation of interest on idle money for dca.

here is how this new sdi_passive looks:

thinkScript for sdi_passive maintained on original page here.

Saturday, August 10, 2013

thinkscript included: sdi_altbuy - altucher buy signal scanner.

i see that my altucher strategy posts are at the top of my best bones. the best bones are elected by pageviews thus i owe it to my readers to do more of that. so what i've decided to share with you today is a chart script that displays altucher buy signals (i.e. when 4 or more consecutively down days have occurred.)

here's an image of this study on a chart:
chart with sdi_altbuy

here is the study:
# sdi_altbuy:
#hint:Display a buy signal when the threshold number of consecutive down days has occurred. rev:1.0.0
# author: allen everhart
# date: 10aug2013
# 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.
input threshold = 4 ;
#hint threshold: Altucher's criterion for the buy signal is 4.
def dncnt = if close < close[1] then dncnt[1] + 1 else 0;
plot buy = dncnt >= threshold;


the real benefit of such a script is that it can be used in the scan tab to create a custom scan for altucher signals. this is because it has only one plot. studies with more than one plot statement are not permitted for custom study scans.

instructions for the custom scan for thinkorswim (note: you must have a funded account to create custom scans):
1. install the above chart script by the copy and paste method (or click on my how to tab to find out how to purchase the import files for my suite of scripts.)
2. click the scan tab
3. click the stock hacker button.
4. click the reset button.
5. delete the three fundamental criteria buy clicking on the x's on the right side of the screen.
6. click add study filter.
7. click the triangle to drop down the selection list and select custom. this should look like: the scanner custom filter dialogue click the edit button. the edit condition dialogue click the blue triangle and select the study category from the drop down list.
10. scroll the dropdown list of studies and select sdi_altbuy. this should look like:

11. click save then ok and then ok on the warning then scan. this should look something like:

Saturday, July 27, 2013

sdi_aispy revision 1.0.1 released

due to a recent update in the tos platform the scripts for sdi_aispy strategy and the sdi_aispymind chart study failed. there has been a decrease in the number of digits to 15 that thinkscript will accept. consequently, i went back through these two scripts and rounded off the network weightings accordingly. this script performs as well as before - an interesting experiment that demonstrates that there is not an extremely high degree of tuning in these numbers.

this result leads me to ask, what resolution of weights is sufficient? having such a large degree of resolution in the weighting creates a huge solution space. to see this, imagine the weights of this network are limited to take on only 10 different values and there are only 2 weights in the nn. the solution space is the number of possible configurations. there 10 possibilites for the first weight and 10 possibilities for the second weight. thus there are 10*10 or 100 possible solutions. the aispy nn has 51 weights, so constraining the weighting to 10 possibilities would have 10^51 solutions, a big number but not nearly as big as the solution space now stands. the floating point number scheme in java is represented by 64 bits. this gives 16 places past the decimal. the genetic algorithm favors searching weights in the low single digits, between -3 and +3, say.  so as things stand that solution space is verry big ~ 6*10^16^51. this is a stupendously large number 6*10^816 or many hundreds of orders of magnitude greater than a googol (10^100.) on one hand, it is testament to the power of the evolutionary process that it can find any profitable solution in such a huge space. on the other hand, this big a solution space is overkill and i think is a situation whereby more might be done with less. i think i will have to revisit this problem with a reduced solution space.

Monday, July 22, 2013

thinkscript included: sdi_ivp - iv percentile in a chart label

i have been following tastytrade's usage of iv percentile but it is a little awkward to use. usually you have to go the trade tab then open up the option statistics and wait for all that to populate. i think i have a better solution - just put that number in a chart label and keep it handy on the chart. here's my solution:

sdi_ivp on netflix - not a trade recommendation
this is a short and sweet solution. there is just one caveat - if you change the aggregation period higher than day then the tos platform will complain and the chart label will disappear.

here's the code: (how to install)
release 1.3 description here.

input period = AggregationPeriod.DAY ;
# sdi_ivp: Display Implied Volatility Percent Range as a label
#hint: Displays the Implied Volatility Percent Range (aka rank, aka pecentile) as a chart label and as a chart indicator. the chart indicator plots as color-coded dots along the chart high and indicates when the iv%r was high/mid/low in the past. the chart label shows the curent numerical value and has the same color coding as the indicator. sdi_ivp rev: 1.31
# author: allen everhart
# date: 19jul2013
# revision 1.3.1 3/9/2014
#    a. eliminate use of takeValueColor which doesn't seem to be reliable.
# revision 1.3 3/2/2014
#    a. ivr indicator enhancement to show when the ivp was high/mid/low in the past
#    b. tie the label color to the ivr color
#    c. made label text an input parameter.
#    d. use double.POSITIVE_INFINITY AND double.NEGATIVE_INFINITY for gap filtering instead of +/-999999999 (just for code correctness)
# revision 1.2 9/18/2013
#    enhancement to permit user to select label color
# revision 1.1 9/13/2013
#    previously sdi_ivp printed N/A if there were gaps in the imp_volatility data. now gaps are ignored.
# 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 period: time period to use for aggregating implied volatility. sdi_ivp rev: 1.31
input length =252 ;
#hint length: #bars used to determine the high/low range of implied volatility
input highPct = 50 ;
#hint highPct: threshold for changing ivr indicator to high color.
input lowPct = 50 ;
#hint lowPct: threshold for changing ivr indicator to low color. note: if lowPct >= highPct then midrange color is suppressed.
input ivprPlacement = {default chartHigh, chartLow};
#hint ivprPlacement: macro control of ivr indicator placement.
input ivprOffsetFactor = .02;
#hint ivprOffsetFactor: fine control of ivr indicator placement.
input labelText = "IV%R";
#hint labelText: default text means: implied volatility percent range.

def ivGapHi = if isnan(imp_volatility(period=period)) then double.POSITIVE_INFINITY else imp_volatility(period=period);
def ivGapLo = if isnan(imp_volatility(period=period)) then double.NEGATIVE_INFINITY else imp_volatility(period=period);
def periodHigh = highest( ivGapLo,length=length);
def periodLow = lowest( ivGapHi, length=length);
def ivRange = periodHigh - periodLow ;
def ivp = round( 100*(imp_volatility(period=period) - periodLow)/ivRange, 0);

plot ivpr;
switch(ivprPlacement) {
    case chartHigh:
        ivpr = if isnan(close) then double.NaN else highestAll(high)*(1+ivprOffsetFactor);
    case chartLow:
        ivpr= if isnan(close) then double.NaN else lowestAll(low)*(1-ivprOffsetFactor);
ivpr.defineColor("high", color.GREEN);
ivpr.defineColor("mid", color.YELLOW);
ivpr.defineColor("low", color.RED);
  if ivp>=highPct then ivpr.color("high")
  else if lowPct<highPct && ivp>lowPct then ivpr.color("mid")
  else ivpr.color("low")
AddLabel(1, Concat(labelText,Concat(": ", ivp)),
  if ivp>=highPct then ivpr.color("high")
  else if lowPct<highPct && ivp>lowPct then ivpr.color("mid")
  else ivpr.color("low")

Monday, July 15, 2013

sdi_yearClose revision 1.0.2 released

previously the yearClose script produced a java stack overflow. this probably was the result of an incompatibility with a thinkorswim platform update - the original script certainly was not released in that condition. now, this is corrected.


Sunday, July 14, 2013

sdi_yesterClose 1.2.2 released

the yesterclose script has been updated to correct for an incompatibility with recent changes to the thinkorswim platform. previously, yesterclose would result in a java stackoverflow. this was certainly not the case when i first published the script so something has happened on the thinkorswim platform that didn't like this script. release 1.2.2 corrects this problem.


Saturday, June 29, 2013

aapl mini-puts under pressure but cost basis is reduced.

because of the beating aapl took recently my aapl mini-calendar manufacturing biz experienced some pressure.  previously, i had been rolling short mini-puts at the 435 strike every week for a credit. my records show that the previous calendar sale only reduced cost basis by 20 cents.  prior to friday, june 28, my cost basis in the 30 aapl shares represented by the short puts had been eased down to 425.35 (including commissions.) that means if i had been exercised early i would own 30 shares of aapl for a net cost of 425.85 (the $15 exercise fee adds 50cents/share.)

because of the decline my short puts at the 435 strike due to expire on july 5 were in danger of an early exercise. the danger signs were that the delta on those options had reached -1 and the extrinsic value had declined to 1.5 cents.

the corrective action i took was to buy back the 435 puts and sell the jul 405 puts for a debit of 24.75. this relieves the pressure of early exercise, adjusts the short strike into a sweeter area for premium sales and  reduces cost basis. this last bit is important to understand if you engage in these sorts of trades. i reduced the exercise price by $30 for a cost of $24.75 and the difference of $5.25 reduced my cost basis to $420.10. this came about because the jul 405 puts had about $5.25 of time-value. to be sure, my trade realized a loss $24.75/share but letting the options get exericised would have realized a larger loss of $29.32/share (=425.85-396.53) and now i can more quickly recover this smaller loss by further sales of near-the-money calendars. furthermore, aapl is now within sight of the july earnings date which tends to elevate premium and maybe price as well.

in any case, the cost basis keeps reducing!

Thursday, June 27, 2013

thinkscript included: sdi_gma - geometric moving average

the geometric average is an alternate way that mathematicians define average. it is defined as the nth root of the product of the data points or:
this was mentioned by the tastytrade geek as his preferred method of calculating averages.

my interest in the geometric mean is mainly that it is a challenge to expand my knowledge of thinkscript because the calculation necessitates the use of the fold statement.

to compute this average for any number of data points it is necessary to transform the definition of the geometric average by use of algebra which i do by applying the associative rule for exponents:
(a*b)^n = a^n * b^n
 thus the working definition for the algorithm becomes:
x1^(1/n) * x2^(1/n) ... *xn^(1/n)
performing the calculation this way keeps the intermediate results of the product from overflowing the numerical limits of thinkScript variables.

here is the thinkscript:
# sdi_gma: geometric moving average
#hint: Displays the geometric moving average. rev: 1.0
# author: allen everhart
# date: 6/26/2013
# 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.
input price = close;
input length = 9;
plot gma = (fold n = 0 to length with s=1 do s*power(getValue(price, n),1/length));


the fold statement is the thinkscript equivalent of a for loop in other general purpose languages. in my use of the fold statement above, the loop repeats length times and the intermediate value of the loop counter is stored in the variable, n. the variable, s, is intermediate storage for the do expression which implicitly assigns the result of the expression to s on each iteration of the loop. it is necessary to use the getvalue function because thinkscript does not allow variables to be used in subscripting (the standard method of historical reference denoted by square brackets [].)

to demonstrate why this script is only a programming exercise just take a look at this chart which compares the 50 period simpleMovingAverage(green solid line) to a 50 period plot of sdi_gma(red dashed line):

the geometric average is always a smidgen less than the arithmetic average. there might be a larger difference for prices that dip below 1 because the geometric average overweights numbers between 0 and 1. in the extreme case where a price is zero the geometric moving average would plot as a horizontal line at value zero.

there are several uses of the fold statement i have in mind, one of which is a rewrite of my seapro study to allow the selection of the number of seasons to average.


Saturday, June 22, 2013

thinkscript included: percent change from open on watchlist

my daytrader friends asked me to write this custom column thinkscript:
# sdi_pctChgFromOpen: plots the percentage change from the opening price in a way that is appropriate for a watchlist custom column.
#hint: plots the percentage change from the opening price in a way that is appropriate for a watchlist custom column. rev: 1.0 
# author: allen everhart
# date: 22june2013
# 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.
plot x=round(100*((close/open)-1),1);
x.assignValueColor( if x < 0 then color.RED else color.Dark_GREEN);


here's what this custom column looks like on a watchlist:
percent change from open custom column

here's how to install a custom column:
  1. right click on the heading of the watchlist and select Customize
  2. scroll down the Available Items list and double left-click on the scroll icon of any Custom column
  3. in the Custom Quote Formula dialogue, select the ThinkScript Editor tab
  4. in the editor textbox replace SimpleMovingAvg() with a cut-n-paste of the thinkscript above. 
  5. in the Column Name entry box select a reasonable column name such as "%ochg" (not too many characters)
  6. click ok
  7. select the "%ochg" column from the Available Items list and click the Add Item button
  8. click ok

Monday, June 3, 2013

should i wait or should i roll ... slw?

earlier i shorted a jun put on slw at the $22 strike, collecting a 70 cent credit. time and price have conspired to reduce the value of that put to 20 cents for a 50 cent gain. so the question is should i wait for more time to elapse, reducing the value of this put further or buy it back and sell the july 22 put? the thinkorswim analyze tab can help with this decision:

slw roll analysis
in this analysis the red line shows the credit of the roll wrt the underlying's price at june expiration and the white line shows how this credit will vary with today's price movement. in this view, more negative values represent greater roll-credit. as time elapses the white line will merge with the red line. if the current price of slw holds level through expiration then time decay will worsen the roll-credit so i have elected to roll now. my cost of manufacture of this calendar is merely the commissions i pay to my broker to buy and sell the options or 3 cents, wrt the option price. i got filled at 33 for a net gain of 30cents.  if i were assigned today my cost of ownership of 100 shares of slw would be $21.17(=22 -.70 - .33 + .045 + .15) including commissions and assignment fee.

after this positive experience with slw i have also decided that a business this good should be expanded. to that end, i bought three jan14 puts at the $15 strike for 50 cents and sold 2 more july puts at the $22 strike. the effect of this is to convert my cash covered put trade into a wide diagonal. the $15 strike was chosen because that is about 2/3 of 22 and this keeps the buying power allocated to this trade level with the initial position. there are 6 monthly rolls between july and and january with which to amortize the 50 cents paid for the $15 strike puts which adds 9 cents to the cost of rolling for a total of 12 cents of manufacturing cost for these monthly calendars.

Sunday, June 2, 2013

dow/gold is a tweener

the dow/gold has lifted above 10. economists look at this ratio to subtract inflation from chart comparisons over decades of history. during good economic times this ratio sits around 20. it is now 10.8 after recovering from 5.9 during the s&p downgrade:

this break into the tweener (10-12) range came on the first test courtesy of cypress.

is ben bernanke looking at this and thinking, "glass half full" ?