A Simple TAA System

This is a simple tactical asset allocation system I wrote in Amibroker AFL as a framework for further development. There are still some bugs – some of the statistics don’t calculate properly for one – but it works more or less as intended.

When I get the time I’ll write about the difficulties of creating a system which is truly agnostic about future market behavior when all the building blocks are mired in the past and unavoidably riddled with assumptions.

Excuse the horrible WordPress reformatting, use some common sense to choose your own parameter values, and have fun!

//TAA ETF Moving Average System with trailing stops
//Fully invested regardless the number of open positions
//Trades once a month, but uses daily data and evaluates stops daily

//strategy parameters/////////////////////////////////////////////////
malen = Param(“ma length”,21,21,252,21);
//malen = Optimize(“ma length”,21,21,252,21);

//execution/trade management parameters///////////////////////////////////////////////
stopperc = Param(“stop %”,2,2,20,1);
//stopperc = Optimize(“stop %”,2,2,20,1);
redelay = Param(“rentry delay”,21,21,126,21);
//redelay = Optimize(“rentry delay”,21,21,126,21);
RoundLotSize = 1;
BuyPrice = C;
dom = Param(“day of month”,1,1,21,1);  //day of month to calculate scores
//dom = Optimize(“day of month”,1,1,21,1);
tradedelay = Param(“trade delay”,0,0,5,1);  //days to delay trading after calculation
//tradedelay = Optimize(“trade delay”,0,0,5,1);

//Portfolio parameters and options///////////////////////////////
Maxposition = Param(“max positions”,1,1,15,1);
//Maxposition = Optimize(“max positions”,1,1,15,1);
Mindiff = Param(“Min diff to rebalance”,.005,0,.10,.0025);
//mindiff = Optimize(“Min diff to rebalance”,.005,0,.10,.0025);
SetOption(“InitialEquity”, 100000);
SetPositionSize(100/Maxposition, spsPercentOfEquity);
SetOption(“UsePrevBarEquityForPosSizing”, True);

//Determine trading day//////////////////////////////////////////////
MonthChange = Month() != Ref( Month(), -1 );
Rebalance = IIf(BarsSince(MonthChange==1)==dom,1,0);

//Rotational trading parameters////////////////////////////////////
PositionScore = IIf (C>MA(C,MAlen), C/MA(C,MAlen), 0);  //If above moving average, rank by % above the moving average
AddToComposite( IIf(PositionScore !=0,1,0) , “~TAAPosCount”, “X”, atcFlagDefaults = 15);  //create artificial security to track number of positive scores
RawCount = Ref(Foreign(“~TAAPosCount”,”C”),-tradedelay);  //Must use count from calculation day to get proper results
PosCount = IIf(RawCount>Maxposition,Maxposition,RawCount); //Final count used for position sizing

//Custom Backtest Procedure/////////////////////////////////////////////////
SetOption(“UseCustomBacktestProc”, True);
if (Status(“action”) == actionPortfolio)
bo = GetBacktesterObject();
bo.PreProcess(); // Initialize backtester
for (bar=0; bar < BarCount; bar++)  //loop through all bars
bo.handlestops(bar);  //For daily stops this is outside the day of month loop
if (rebalance[bar]==1)  // test for day of month to trade
CurEquity = bo.Equity;
if (poscount[bar] !=0)
PositionSize = 1/PosCount[bar] * CurEquity;
for (pos = bo.GetFirstOpenPos(); pos; pos = bo.GetNextOpenPos()) //loop through open postions and rebalance to remain fully invested
posval = pos.GetPositionValue();
diff = posval – PositionSize;
price = pos.GetPrice(bar, “C”);
if (abs(diff[bar])>Mindiff*posval AND abs(diff[bar]) > price AND diff[bar]>0) // do scale outs first
bo.ScaleTrade(bar, pos.symbol, False, price, abs(diff[bar]));
if (abs(diff[bar])>Mindiff*posval AND abs(diff[bar]) > price AND diff[bar]<0)  // do scale ins
bo.ScaleTrade(bar, pos.symbol, True, price, abs(diff[bar]));
} //for scale in/out loop
} //for trading day loop
} //for bar loop
bo.PostProcess(); // Finalize backtester

Pseudo Random News and Comment

You may have noticed many of the links are now on Twitter. I’m not thrilled with the change but with the demise of Google Reader it’s easier to put most of the short comment links there.

Transplant experts challenge assumption, describe pathway that leads to organ rejection  It’s about time. It’s been pretty obvious something is missing from current treatments, and what do you know? It’s those damn dendritic cells again.

Predicting risky sexual behavior Scripts get the blame in large part. Makes sense. Everyone knows you go wild in college, as well as drink and do drugs, so it’s no surprise it’s rampant there.

Overspending Has Become a Modern Form of Mating Deception’ The modern potlatch, signaling what you really don’t have and are then committed to trying to maintain. Not high odds of long-term success.

The Killer Robot War Is Coming   Coming up with legal restraints. I’m not sure that property rights aren’t the right approach, as long as they’re strictly enforced – which they rarely are. But if one set of laws can’t be adequately enforced there’s no reason to assume another set will fare any better, particularly when they are aimed at the law enforcers.

Is Google a rat? The curious timing of the Mt Gox bitcoin exchange shutdown and the Gmailing money announcement has me wondering. There’s no way in hell the bank ratted on itself since they have a long history of laundering billions for drug dealers and others. There’s also the question of why ICE is handling FINCEN in the first place, but mission expansion and empire building always seem to be job #1 at homeland security.

Pseudo Random News and Comment

Why Is It So Hard to Keep the IRS Out of Politics? A: Because it’s so damn politically useful. I especially love this bit: “If I were Obama, I’d ask Eric Holder to appoint a special prosecutor…” Eric Holder. Ummm……

Is Psychiatry Dishonest?  Are its lips moving? Good piece on the emperor’s new clothes.

Let’s Cut Through the Bitcoin Hype: A Hacker-Entrepreneur’s Take The best thing I’ve read about bitcoin recently, maybe ever.

Our Algorithms Can Predict Future Disasters — Now What?  Knowledge is power, but also questions and confusion. Too many false alarms will quickly be ignored.

Living close to major road may impair kidney function. At least in stroke patients.

How to quickly spot signs of a stroke. Maybe. I had a hemorrhagic stroke and had none of these signs.

Did FBI Counterterrorism Agent Reveal That Feds Now Record All Phone Calls?  Of course! An obvious attempt to prove we’re getting our money’s worth with the million acres of server farms. They can’t fill up that much hardware with only employee porn stashes.

Exercise-related changes in estrogen metabolism may lower breast cancer risk. Get up, stand up, stand up for your breasts. If that gets used in a PSA I want some money.

Secular Bull or Bear? Excellent summary. Secular bears are no stranger to new highs, which makes diagnosis difficult. But if it was obvious which, it would have already happened.

Investment Risk Re-imagined Excellent rethinking of risk.

Study links diet with daytime sleepiness and alertness in healthy adults.  Fat puts you to sleep. Carbs do the opposite, Protein does neither.

Antibiotics could cure 40% of chronic back pain patients I had to check the calendar to make sure it wasn’t April 1st. It’s not. Backaches could be contagious.

Pseudo Random News and Comment

Four Basic Traits of Successful Investors I think #5 should be they’re boring.

Porn, rape, and a ‘natural experiment’  Read ‘em and weep anti-porn zealots. Leaves unaddressed what Dad’s sock drawer is doing to stay relevant when free porn is readily available elsewhere.

How to spot liars in official interviews Police interviews that is. When interviewing actual officials the old fallback of “when their lips are moving” is far more accurate than the 68% this increased cognitive load method identified.

Money Buys Happiness and You Can Never Have Too Much, New Research Says  Really the study highlights the difficulties of studying happiness, since this is measuring satisfaction rather than happiness. It’s possible to be quite satisfied with how things have turned out but not happy. I think generally satisfaction is based more on objective measures of outcomes. Happiness really doesn’t care…

Meet Mr. Money Mustache, the man who retired at 30 (via Crossingwallstreet) Naturally, I’m 9 for 9 on his tips.

Does Working From Home Work? As I’ve long suspected, if you read between the lines it’s better for the employer than the employee. Anyone have that Yahoo’s email?

Study Finds Women Most Aroused By Men With Intermediate Level of Beardedness. Most disturbing – because I didn’t find it first. This explains my unconscious avoidance of shaving more than once a week.

But I think this one tops the last one: Antibiotic Protects Men from Being Too Trusting of Attractive Women  A new meaning to “using protection.”  Normally used to treat acne, this means they made themselves more attractive to the attractive women but then didn’t trust them. Life can be so cruel.

Sperm cell release can be triggered by tightening the grip around the delivery organ  Pretty much says it all.

Why Still So Few Use Condoms. Because they suck. But Bill Gates is going to lend a hand.

Baby knows best: Fetuses emit hormone crucial to preventing preeclampsia  So manipulative they can’t even wait until they’re born to start working you.

Are Doctors Diagnosing Too Many Kids with ADHD?  “Data suggest, however, that a bright dividing line does not exist.” Exactly, any cutoff imposed on the distribution is arbitrary, and imposes drastic changes in how everyone will treat them.

Seven simple lifestyle steps may decrease risk of blood clots  Boils down to taking good care of yourself, which doesn’t make it easier.

Wall Street Is A Rentier Rip-Off: Index Funds Beat 99.6% Of Managers Over Ten Years  Even worse than I thought.

Pseudo Random News and Comment

Gene controls three different diseases  Just the sort of pathological cheapness on the part of nature that will make genetic cures for disease difficult. Multiple uses needn’t be all good or all bad. Fixing one thing may often break something else.

Build Your Own Neutra Home!  They still look modern a generation later.

What Martial Arts Have to Do With Atheism  Interesting interview with Sam Harris.

Sexually explicit material affects behavior in young people less than thought I always wonder how you find a control group of males who haven’t watched porn. In this study 88% said they had. 88% of the other 12% were lying. So the lack of statistical difference isn’t surprising.

Autism risk spotted at birth in abnormal placentas  This raises an interesting question of who is doing what to whom.

Pleasure and pain: the effect of (almost) having an orgasm on genital and nongenital sensitivity. I’m going to go way out on a limb and guess that subjects who perform in these conditions may not quite represent the norm, thought the results seem reasonable.

Thought Prenda Was Dead? No, It’s Up To Its Old Tricks… And More  Amazingly limitless depravity.

The Gold Medal Gold Model, Tarnished?  A fundamental model for gold. For the patient it seems to be holding up quite well.

Why Sleep Deprivation Eases Depression  Glial cells strike again.

Judge says giving up your password may be a violation of 5th Amendment. Forcing you to divulge evidence against yourself “may” be a violation of the 5th Amendment. Ya think? Totally gutless.

Calm Down … You Are Much More Likely to Be Killed By Boring, Mundane Things than Terrorism  I love numbers about relative risks. “You are 8 times more likely to be killed by a police officer than a terrorist.”

Pseudo Random News and Comment

Consciousness After Death: Strange Tales From the Frontiers of Resuscitation Medicine  I think he’s let a desire to believe something outrun the science to support it. He also seems to assume consciousness resides only in the brain rather than being an emergent property of a complex system involving the entire body as well as the brain.

The Most Stressful Places to Live  The least stressful state is, of course, Hawaii.

I’m on the drug that killed Paul Erdős  Smart drugs are coming to a workplace near you, and some day they may even do what is hoped. Keep in mind you can’t turn a donkey into a racehorse, and more isn’t always better.

Two days of staging as effective as four for high-altitude climbs  The short-term adaptations are quite rapid so there’s no point in diddling around any longer.

After Boston: Don’t Get Fooled Again by the ‘War on Terror’ Hawks  Nice dissection and prophylaxis.

Low-dose aspirin stymies proliferation of two breast cancer lines, study finds  More benefits from lowly, old aspirin.

Flu shots boosted by exercise  In moderation – prolonged intensive exercise is an immunosuppressant.

IRS Says It Will Change Its Policy On Looking At Emails Without A Warrant… At Some Point  Never assume you have any privacy. Perhaps at the end of a long trail, under a waterfall, whispering into the ear of someone is safe, but only perhaps, only if you’re not already under surveillance, and only for a very limited period of time.

My answer to John Hussman  Good example of the importance of knowing your time frame and goals. In 1995 when I first had the epiphany that we would be repeating the market action of the 1970’s on a grander scale I had intended to trade the swings like a madman. Instead, my time frame changed and I’ve mostly done nothing. Either way can be right (and it’s possible to do both at the same time).

An example:  Broadening the Window – Aligning Indicators with Correct Holding Periods

Virus kills melanoma in animal model, spares normal cells  Edging just a little closer to the immortality virus.

Decision making in scientific peer review unravelled with mathematical modelling  With all the fraud going on, is there any doubt this bit of reverse engineering will be abused?

Random Thoughts on Apple  Nice summary. The biggest risk to me is a very large percent of revenue is from the latest products so it wouldn’t take more than a couple bad quarters for Apple to lose a significant chunk of their revenue….and Samsung Galaxy is doing quite well in China.

Pseudo Random News and Comment

What will the neighbors think? Tinshed / Raffaello Rosselli

Kidneys grown in lab become functional in rats Still a long way to go but it’s progress.

Dr Michele Ferrari is using his free time to take on Osymetric Chainrings. If you ask me the trials have suspiciously low variability. However, the results do match my experience, and not allowing for muscular adaptation should give the most favorable results.

Circumcision alters penis bacteria  Refining the improved hygiene theory for reduced risk of HIV

FDA Lets Drugs Approved on Fraudulent Research Stay on the Market  Money talks everywhere in the halls of power.

New Zealand legalises same-sex marriage  Continuing to make their bid for most civilized English-speaking country. Probably because they’re small enough everyone still knows where the politicians live.

“Markets Are Debates Between People Who Are Speaking With Money”  Great way of looking at it. These days I just don’t care to get involved in very many debates.

Tacrolimus Inhibits the Revascularization of Isolated Pancreatic Islets  Another reason to pat myself on the back.

The ‘learning curve’ of living with Asperger’s  The difficulties of learning to fake it through every social interaction.

Does Brain Training Work?  A resounding kinda, sorta, maybe. Plasticity certainly argues that benefits should be possible but, like every other form of physical training, specificity trumps all, and what brain training exercise can truly be specific to broad, general intelligence?

Super-volcanoes in the Ancient World  If you are running short of disasters to worry about, this is a great one.