Trading Gaps with Stops
Author: rb101
Creation Date: 10/3/2009 5:05 PM
profile picture

rb101

#1
New to wealth lab. Would like to get some pratical advice on how to test a simple strategy I have to buy (at the open on any gap) using a protective stop. I'd liek to ste this going back 1 yr. Can anyone help me? Thanks Rob
profile picture

Cone

#2
Testing it is no problem, but automating a strategy to buy at the open based on the opening price has many complications; discussed here for Version 4: Generating an Alert with the "Opening Price" of the Entry Bar

Here's the test code, which you should run with intraday data (1-min is best) since you'll need to know the chronology of prices in order to know if the stop or profit target would have been hit first.

1. Install Community.Components as suggested in the comments.
2. Open a New Strategy Window and replace the code with the code belw.
3. Click the Compile button and Save the strategy
4. Click the symbol in the Data Panel to run the script. (You should set up a 1-min DataSet for your symbols of interest in the Data Manager first).

CODE:
Please log in to see this code.
profile picture

rb101

#3
Thanks Cone- will give this a try. All this progrm code is 'greek' to me. Can I call(email) on you if I have problems?
profile picture

Cone

#4
QUOTE:
Can I call(email) on you if I have problems?
No, sorry. Please see Our Support Policy.
profile picture

rb101

#5
Hi Cone- Thanks agin for such great detail. You mention to do the following (see the list below), but I have no clue how to. I am currently on the Wealth Lab Pro 505 site and I don't see "community" or "new strategy window" under the tool bar?? Can you assist me a bit further? (Sorry it has to be literal for me to understand)...thanks -Rob.

Install Community.Components as suggested in the comments.
2. Open a New Strategy Window and replace the code with the code belw.
3. Click the Compile button and Save the strategy
4. Click the symbol in the Data Panel to run the script. (You should set up a 1-min DataSet for your symbols of interest in the Data Manager first).
profile picture

Cone

#6
Here's the comment -

/* install Community.Components from Extensions > Get Extensions > Addins */

See Extensions in the menu above. Read about how to install extensions if you've never done it before. (Also in the User Guide.)
profile picture

rb101

#7
Hello Cone,

Due to you assistance, I was able to work through this and get loaded (and w/a bit of help of Fidelity wealth lab pro). Thanks again!

Got a quick question....where does the line of new code go if the only thing I wanted to change (from script you wrote for me above) is to buy at 1% below the open on gap downs?

Everything else remains the same.
Rob
profile picture

Cone

#8
I should have saw this one coming, so here's the rewrite with Strategy Parameters. Use the sliders to adjust the values (and you can optimize it now too).

CODE:
Please log in to see this code.
profile picture

Cone

#9
Something to try to make the script easily tradeable, and it may even give you better results, is to make this simple change:

CODE:
Please log in to see this code.
With that change, you'll be buying the open of the second bar. If you use a 1-minute chart, that essentially delays the entry into the market by 1-minute (plus a little more for order entry/ processing delays). Since the market is gapping down anyway, you might discover in backtesting that delaying your entry could help more often than not.
profile picture

rb101

#10
wonderful- thank you very much Cone...(do you ever sleep)?
Rob
profile picture

Cone

#11
Not much, and last night even less. :(
profile picture

rb101

#12
Cone- didn't see your adder below....Thanks.

When I copy/paste this into the new script, where exactly do I add this and if I do, do I delete anything else at same time?
profile picture

Cone

#13
There's only one BuyAtMarket statement to change. That's the one.
profile picture

rb101

#14
What would you consider an excellent Wealth Lab Score?
How about Sharpe Ratio and Profit factor?
profile picture

Cone

#15
On wl4.wealth-lab.com we still rank the public ChartScripts (Strategies). Take a look at the Rankings by Wealth-Lab score by clicking Rankings in the main menu to get an idea. Anything over 2 is excellent for Sharpe and Profit Factor.
profile picture

rb101

#16
Mornin' Cone-

I noticed that the box for percentage slippage in the preference tab (equity slippage) is pre-set for .10, but the box for 'slippage for market at close and stop orders (will adversely adjust entry and exit prices)' is not auto-checked. When I do check it and run my script, it reduces my performance by almost 1/3. Do you recommend that? All I am using are mkt orders and no mkt at close orders. What's the diff between both slipage settings?

Thanks,
Rob
profile picture

Cone

#17
In backtesting, market order slippage always gives you a worse result, but in real life, slippage works both ways, i.e., you often get a better price due to delays in order transmission and execution. For a liquid market, slippage has little practical utility, but if you're trading illiquid equities, then it will probably be more realistic.

You can find the documentation quickly for anything that you're looking at by hitting F1. I don't have more to add than that.
profile picture

rb101

#18
Thanks- that's enough. I actually have been using F1 -answered many of my other questions- but it was unclear to me if I should consider both box selections and (will keep the .1 ) and negate the other. Good point about it working both ways is good w/liquid instuments...

Cone-quick question re modifified script you wrote me so I could optimaze (which i already have, so pretty cool stuff.....) Regarding the gap down percenatge range -is that from the previous days close, or that days' open price? Not sure how to interprete the progamming code.

I also found out that buyatmarket(open bar +2) gives me slightly better performance vs. (open bar +1)...

profile picture

rb101

#19
Much of a difference between Monte Carlo and Exhaustive- think it changes it more +1.5/2% on an APR basis? I ask bec its th diffence between 35 mins and 2 days(and I have a fast processor)!!!
profile picture

Cone

#20
QUOTE:
Regarding the gap down percenatge range -is that from the previous days close, or that days' open price?
It's today's open (Open[bar]) gapping below the previous close (Close[bar - 1] * pctGap).

QUOTE:
I also found out that buyatmarket(open bar +2)
Don't use BuyAtMarket + 2. It might work okay for backtesting, but trading signals should always be executed on the next bar (bar + 1). So, you should delay the trade one more bar in the code. This requires a little more logic than it sounds, so here's another version with a scalable delay you can use for testing / optimizing, but doesn't offer the possibility of testing buying on the market open. The script is tradable with any delay chosen.

CODE:
Please log in to see this code.

Re: Monte Carlo vs. Exhaustive
Of course this is expected. Do you know why?
profile picture

rb101

#21
yep- the later is absolute while the former is a sampling...makes sense. Was just wondering if Monte Carlo is close enough... hey -who has 2-3 days per back test!!!

Thanks for this new script above- how's the weather in Spain this time of year- sounds beautiful from what I hear...
profile picture

Cone

#22
Hot and humid - had to turn on my air conditioner for the first time this year this week.
profile picture

rb101

#23
better than cold and wet...are you near the sea?

Have a good weekend Robert!
Rob
profile picture

rb101

#24
Hi Cone,

If I wanted to change one thing about this entire strategy and that is to buy on the 2nd bar delay after a gap up at open (NOT a gap down), what would that line of code look like and where do I inject it?

Thanks,
Rob
profile picture

Cone

#25
Hi Rob, we've gone back and forth on the requirements here quite a bit. Give it shot yourself, please - nothing will explode, I promise! Even for someone that has never coded before, you must be able to follow the logic here, no?
profile picture

rb101

#26
Yep- your right. "Teach a man to fish...." You've been great Cone. My greatest fear is I may think I re-wrote it correctly and all the time I hava a flaw(junk in/junk out). I will give it a shot.

Can I at least run it by you in a few days after I have troubleshoot-re-wrote it Cone just to insure that I in fact have it right?

I won't "overextend my stay....."

Rob
profile picture

Cone

#27
Of course. I was just checking in to see what you had done :)
profile picture

rb101

#28
nothing yet- have been traveling for my 'other job'. Will work on over weekend...
profile picture

rb101

#29
Dear Cone-

Oh my God- I think I am ready to shoot myself!!! Been working on this on/off since the weekend. Even read up on some of the on-line manual/tips to no avail! In the end, I went back to the original script (void execute paragraph) and changed the - to +. Still won't compile.

The only thing I want different from your last script is to buy at market gap up (vs. market gap down). Delays and number of bars remains the same, so figured I'd do pluses? What am I doing wrong?

This is so frustrating(don't think my left side/right side of brain is wired for code)...but you're right it didn't blow up!!

Cone- you you help? Below is revised script...

Thanks,
Rob

---------

CODE:
Please log in to see this code.
profile picture

Cone

#30
Tip: Please click the CODE button before you paste code and paste the code between the CODE tags.

QUOTE:
are you near the sea?
About a 10 min walk. Gran Canaria is one of the Canary islands.

QUOTE:
I think I am ready to shoot myself
No, I meant to "give it a shot", not shoot yourself!

If I read you right, you need only to make these changes in the original code; the first of which, you did - congratulations! :)
CODE:
Please log in to see this code.


Make sense?
profile picture

rb101

#31
LOL......ok thanks Cone - I will try tonight, attempt to compile/run strategy and report back....Rob
profile picture

rb101

#32
Hey Cone -

I think have my version of this strategy down pretty much where it's not going to get any better (from an optimization standpoint), and now want to marry it to an auto-trade platform. Curious, from all the strategies you've seen, from a scale of 1-10, 10 being the easiest to integrate, how would you rank this one, as far as how realistic the trade executions will be in real life?

The good news is all the buy orders go in after 9:32 AM, all are mkts orders and the sell orders are also mkt orders. Most of what I am trading have narrow spreads with good volume (a few are thin). There are only on avg 3-4 trades/day, so it's not like it'a rapid fire order execution....

If you where going to pick an area that you think I may run into problems, getting this integrated in automatic-order execution, where you envision this being?

Thanks Cone,
Rob
PS: The Canary Islands sound nice. Ironically, I am about a 10 min walk to the Atlantic, but here in New Hampshire, it's a bit chiller than your tepid climate(read am jealous....) About 40 deg F here today -chilly fall day...

profile picture

Cone

#33
QUOTE:
as far as how realistic the trade executions will be in real life?
Some executions will be better than you expect, some will be worse, some will be exact. In the end, the good and bad slippage will probably average out (but it's good to plan on a negative effect). If you want orders that execute with no slippage at the risk of missing the trade, you can use limit orders with the limit price derived from the Close of the last bar, which is likely to be 0.01 from the open of the next bar for liquid stocks.

QUOTE:
If you where going to pick an area that you think I may run into problems
The Strategy Monitor is currently buggy for Staging and Placing automated orders. Use Streaming charts and reduce your DataSet if required to keep it manageable.

Practice automated trading with a Paper account first.
profile picture

rb101

#34
Thank you Cone-

Stupid question but I'll ask it regardless....is slippage only something that relates to the real world? In other words, hypothetically, if I had the benefit of endless time and resources, if I ran two identical strategies....One with real monies and the other(idential w/same parameters) but did nothing more than backtested what I had just traded real time, would they over time(months/years) mirror each other within statistical insignificance- possibly less than 1/2-1%, or could the slippage/drift be greater?

Rob
profile picture

Cone

#35
I don't know. It would depend on your broker, trading delays, order types, the issues traded (spreads), EOD or intraday strategy, exchange practices, etc.

My experience with market orders is that sometimes I get precisely the open price, sometimes a better price, and sometimes a worse price - it averages out, and if you lose a few tenths of a percent, then it's the cost of doing business.
profile picture

rb101

#36
Hi Cone,

Good evening-

Are there any provisions in 5.5 to incorporate the Treynor or Jensen ratio in addition to currntly available Sharpe ratio?

Also, keep having system crashes on the 3-4th pass of running my script strategy forcinf me to close and re-boot- any idea where this may be coming from and how to fix it?

Thanks,
Rob
profile picture

Eugene

#37
QUOTE:
Also, keep having system crashes on the 3-4th pass of running my script strategy forcinf me to close and re-boot- any idea where this may be coming from and how to fix it?

Possible out of memory issue -> [LINK=http://www2.wealth-lab.com/WL5Wiki/kbFAQStrategy.ashx]
Out of memory problems[/LINK]. What's the exact message you get when it crashes?

QUOTE:
Are there any provisions in 5.5 to incorporate the Treynor or Jensen ratio in addition to currntly available Sharpe ratio?

Other ratios like these can be incorporated as performance visualizers e.g. this one: Performance Extras. Both Treynor and Jensen include Beta of the Portfolio in their calculation. If somebody is willing to guide me through how it should be calculated, I could take a look.
profile picture

rb101

#38
Eugene-

Here's what I came up with for the Treynor ratio from the web. Apparantely it is a measurement of the returns earned in excess of that which could have been earned on a riskless investment (i.e. Treasury Bill) (per each unit of market risk assumed).

The Treynor ratio (sometimes called reward-to-volatility ratio) relates excess return over the risk-free rate to the additional risk taken; however systematic risk instead of total risk is used. The higher the Treynor ratio, the better the performance under analysis.

where

Treynor ratio,
portfolio i's return,
risk free rate
portfolio i's beta

Like the Sharpe ratio, the Treynor ratio (T) does not quantify the value added, if any, of active portfolio management. It is a ranking criterion only. A ranking of portfolios based on the Treynor Ratio is only useful if the portfolios under consideration are sub-portfolios of a broader, fully diversified portfolio. If this is not the case, portfolios with identical systematic risk, but different total risk, will be rated the same. But the portfolio with a higher total risk is less diversified and therefore has a higher unsystematic risk which is not priced in the market.

An alternative method of ranking portfolio management is Jensen's alpha, which quantifies the added return as the excess return above the security market line in the capital asset pricing model. As the two both determine rankings based on systematic risk alone, they will both rank portfolios identically.

Does this help?
Rob
profile picture

rb101

#39
Jensen's alpha = Portfolio Return - [Risk Free Rate + Portfolio Beta * (Market Return - Risk Free Rate)]

Since Eugene Fama, many academics believe financial markets are too efficient to allow for repeatedly earning positive Alpha, unless by chance. To the contrary, empirical studies of mutual funds spearheaded by Russ Wermers usually confirm managers' stock-picking talent, finding positive Alpha. However, they also show that after fees and expenses are deducted, the effective Alpha for investors is negative. (These results also explain why passive investing is increasingly popular.[citation needed])Nevertheless, Alpha is still widely used to evaluate mutual fund and portfolio manager performance, often in conjunction with the Sharpe ratio and the Treynor ratio.

profile picture

rb101

#40
Thanks Eugene-

RE "Call Bars.Cache.Clear at the end of your strategy to explicitly clear the internal cache that stores DataSeries and free memory."

I looked, but could not see where to go to find this?

Thanks,
Rob

profile picture

Eugene

#41
Thanks, but it doesn't seem to have a clear-cut algorithm/formula for computing beta of a portfolio -- the prerequisite for doing any programming.

These links provide more insight...

http://answers.google.com/answers/threadview/id/572341.html
http://www.investorwords.com/tips/271/calculating-your-portfolios-beta.html
http://www.investopedia.com/articles/financial-theory/09/calculating-beta.asp

...BUT it looks like I'm still missing something. The way they describe the portfolio beta it seems as a data series that depends on weights of portfolio components. Which can, and will, be rebalanced. So we can have the number computed for the last bar (only). The beta changes on every rebalancing act.

If someone can step out and explain the point of this ratio or what I'm overlooking about this stuff, maybe it could help.
profile picture

Eugene

#42
You will find Bars.Cache.Clear in the QuickRef (under "The Bars object").
profile picture

rb101

#43
Below, this is the "example" I found under the quick ref...I am not a programmer, nor do I have any idea where to insert, or if i need to chane it(?).

The sript I am using is the one I and Cone came up with- see it listed under trading gaps by RB101...It's the last one he provided me w/mods...

Eugene - do I just copy past this example from quick ref at very end of the script?
Rob

Sorry - I seel pumps fora living so it'realyy all greek to me...
Thanks
----------------

Example
CODE:
Please log in to see this code.
profile picture

Eugene

#44
Normally, you could insert a single call to Bars.Cache.Clear just before the end of the Execute() method. Calling .Clear should help reduce memory consumption if a strategy creates custom series. Your script does not do that at all, so there's no point in doing that.

Before doing calling .Clear, there are other advices in the FAQ to try reduce memory consumption which I think are more appropriate in your case. After all, we're not even sure it's an out of memory problem. I couldn't find your error message text before the controlled "crash" that you can "stop and reboot""? In addition, can we have an idea about how many symbols, how many bars loaded, streaming/static data etc., enabled visualizers?
profile picture

rb101

#45
Thank you

Am running it on approx 35-45 ETFs...all 1 min ticks and am running it for YTD, 1 and 2 and 3 yrs. Static data(I think -how do I know?).

I will attempt to copy/paste/track the error messages going forward...
Appreciate the support-
profile picture

Eugene

#46
According to the Wiki FAQ formula, you're not pushing the limits of your system:

390 minute bars in a day * 250 days in a year * 40 instruments * 48 bytes [6 series * 8 bytes] * 1 year = gives us only 187 megabytes of required memory before PosSizers and Performance Visualizers. (Triple that amount for 3 yrs. backtest.)

So, unload unnecessary running applications and other memory-resident stuff, break up your backtest, switch some visualizers and it should work.
profile picture

rb101

#47
Eugene- How would one go about "breaking up my backtest" in order to free up memory?
Thanks
profile picture

Eugene

#48
Choosing a smaller data range and moving forward (in the manner of walk-forward optimization), splitting the dataset and taking only so much stocks in backtest that doesn't produce an out of memory error - you get the picture.

But try freeing your RAM first - uncheck visualizers, shut down other programs, start fresh, don't run the same backtest several times, check that your RAM is enough (how much, actually???).
profile picture

rb101

#49
Eugene,

Interesting....I just ran the exact same scripy/strategy- IDENTICAL in every way - one on my laptop and the other my desktop w/different results. Same symbols(ETFs). Most of them off 1-3%, but two of them(TNA) off a real lot $700 profit vs. 9000 profit. They are all very liquid.

Same period -1 yr...same 1 min tick -all from wealth lab- can't imagine why they are different? Any idea- ever hear of this- why would they not be identical to each other? I then removed the symbol and added it to the datase and re-ran it with same result???

Rob
profile picture

Eugene

#50
Probably there's some difference in the data on your 2 computers. It takes copying the exact same *.WL files from one to another, or refreshing the symbol history at the same time.

btw, removing the symbol from a DataSet doesn't clear it. It either takes reloading entire symbol history (right-click on the chart to see the option), or performing a provider update (w/ option "Delete data for Symbols that are not contained in DataSets" enabled).
profile picture

rb101

#51
Eugene- to the uninitaited(aka, village idiot...), of all th areas you propose, which one way would you recommend I implement(and can execute it easily-again, I sell pumps for a living so, this is all greek to me) to insure the data is 1) is the same w/each system 2) I am not looking at corrupt data? -which is my biggest concern.
Thank you-
Rob
profile picture

Eugene

#52
Rob,

I propose reloading the data for the symbol that is under question and could be different (i.e. TNA) due to correction applied, data not up to date etc.

In addition, if your Trades tab indicate trades not being taken for there's not enough capital (note what its status strip says), and at the same time you're not using Priority in your script (or in Preferences > Backtest settings > [] Use Worst Trades in Portfolio Simulation)
), you might be getting different results on each run and this can be an explanation for this discrepancy too:

Every time I run a Strategy I get a different result. What am I missing?
profile picture

rb101

#53
Thanks - when you suggest I "reload the data for the symbol that is under question and could be different (i.e. TNA) due to correction applied, data not up to date etc."...do I simply create a NEW dataset with those 6 symbols? and delete the previous dataset?
profile picture

Eugene

#54
QUOTE:
do I simply create a NEW dataset with those 6 symbols? and delete the previous dataset?

Just the opposite: re-read my message from 11/2/2009 3:42 AM, it's all explained there. Right-click a chart of TNA and select "Reload Chart History" if just a handful of symbols are problematic, otherwise... it's all in that message, 2nd paragraph.
profile picture

rb101

#55
Done- thanks.

On another matter- word from others in the community is there is/may be a problem w/autotrading a script (using strategy monitor, I think)?

My script when backtested involves only mkt orders and only 2-4/trades per day, mostly at open 2nd bar- do you see a problem w/this? Someone from Fidelity I thought seem to think it may be a Reuters issue?

Whats' your take on this?
profile picture

Cone

#56
QUOTE:
On another matter
rb101, it's time to start a new thread.
profile picture

rb101

#57
Hello Cone,

You mention above "Don't use BuyAtMarket + 2. It might work okay for backtesting, but trading signals should always be executed on the next bar (bar + 1). So, you should delay the trade one more bar in the code. This requires a little more logic than it sounds, so here's another version with a scalable delay you can use for testing / optimizing, but doesn't offer the possibility of testing buying on the market open. The script is tradable with any delay chosen."

When I Monte Carlo'd the various strategies, I set the delay for a possible range of 1-5. Some were giving me a final optimization of 4, some 1 or 2...Then, I re-read your comment and I am confused....You mention not to use anything but 1 delay(ok for backtesting but can be promblematic when tradeable). But in your last sentence, you mention it can be tradeable with any delay??? When I finally get around to beginning to auto-trade my script, should I always go for just one delay or trust the optimization and set it up for what it gives me 2 thru 5?

Thanks,
Rob
profile picture

Cone

#58
You are confused. :) The script I offered is properly written for any delay - as you can see the trading signals are executing on bar + 1. Of course you'll see all the possibilities pop up in an optimization, that's what optimizations do.

QUOTE:
trust the optimization
If you don't know how to interpret an optimization, which could be crap, you better not trade it!
profile picture

rb101

#59
OK- got it know. This stuff does not always come easy to us who don't use it often, or don't have that background. Nevertheless, I must learn, ask and perserve. My script is pretty simple/straight forward- I should be ok. I will trade very small for some time to insure I am on correct path....Thanks
This website uses cookies to improve your experience. We'll assume you're ok with that, but you can opt-out if you wish (Read more).