Remain 100% invested

Hi,

I’m very new to AFL programming and am trying to figure out how to backtest always staying 100% invested in a portfolio strategy that will fluctuate from a maximum of 4 positions to 0 positions any given end of month signal. I’m only interested in monthly data and no other timeframe. How would I go about programming this?

As it stands I’m using the following code below. It works when I’m long 4 symbols but as soon as I drop to a holding of 1 to 3 symbols it still assigns position size of 25% (4 positions).

PosQty = Param( "Number of Positions", 4, 1, 4, 1) ; // Position Quantity: max number of positions
SetPositionSize( 100 / PosQty, spsPercentOfEquity );

Your help is much appreciated.

Chad

Corrected code:

// Position Quantity: max number of positions
PosQty = Param( "Number of Positions", 4, 1, 4, 1) ;

SetPositionSize( 100 / PosQty, spsPercentOfEquity );
SetOption("MaxOpenPositions", PosQty );

// the last one allows slightly shrinking pos size to accommodate for commissions.
// only required if you turned it off in the settings 
SetOption("AllowPositionShrinking", True );
Buy = 1; // buy and hold
Sell = 0;

Tomasz,

Sorry, I forgot to include the other code I had. Please see below. The portfolio still does not remain 100% invested when my holdings drop <4. Am I doing something wrong?

PosQty = Param( “Number of Positions”, 4, 1, 4, 1) ; // Position Quantity: max number of positions
SetOption( “CommissionAmount”, 0.00 );
SetOption( “InitialEquity”, 100000 );
SetOption( “MaxOpenshort”, 0 );
SetOption( “MaxOpenLong”, PosQty );
SetOption( “MaxOpenPositions”, PosQty );
SetOption( “WorstRankHeld”, PosQty );
SetOption( “AllowPositionShrinking”, True );
SetPositionSize( 100 / PosQty, spsPercentOfEquity );
SetTradeDelays( 0, 0, 0, 0 );

Basic mistake that users are making is NOT telling precisely and fully what they are doing in the first post.
After hours of message ping-pong it turns out that user had yet another setting somewhere.

There are dozens of constraints being applied like RoundLotSize for example.

AmiBroker JUST WORKS.
Run the code I gave you. It works.

If something does not work the way you think it should, it is because you told it to do different thing somewhere in the settings and/or elsewhere in the code. Your code has some mistakes, for example “worstrankheld” is only for rotational trading while trade delays only for regular backtest.

Switch report to “Detailed report” in the Settings and find out yourself - plenty of information there.

And finally: use [code] tags in your posts. I fixed your first post already, but won’t baby sit each and every one with every post.

Hi Tomasz,

Thanks for your suggestions and do apologize for not being more specific. Will add the code tags next time.

Chad

Chad, welcome to the AmiBroker community. There are many here willing to try to help fellow users and we look forward to the day that you too help others.

But to get useful help (and even not so useful help) it is important as TJ wrote
"users are making is NOT telling precisely and fully what they are doing
without your full code it is difficult to find all of the errors you may be making."

You initially wrote that you wanted “always staying 100% invested in a portfolio strategy that will fluctuate from a maximum of 4 positions to 0 positions”. Well if your strategy has the ability to go to 0 positions I can tell you that you will not be 100% invested, you do see that?

I assume you meant that if you have any positions (1, 2, 3, 4) you want to be 100% invested but are willing to go to 100% cash.

Also you have not told us anything about how you rebalance your portfolio? For example if you had four positions at 25% of portfolio each and then sold one position, obviously you will now have three positions at 25% and cash for 25% UNLESS you have rules in your code to rebalance using the newly available cash. Is this in your system? For example have you created a rotational system? Do you have more code for Buy and Sell rules? Do you have a section for re-balancing positions?

Good luck, and hope you take this post as constructive suggestions and not a criticism.

Hi Portfoliobuilder,

Thank you for the warm welcome and appreciate the constructive criticism. Your questions were spot on and you are correct, if I have any positions (1, 2, 3, 4) I want to be 100% invested but are willing to go 100% cash (Tbills instead). What I meant by always staying 100% invested was if I get a sell signal on 1 of the 4 positions, I’m left with 3 position but want the system to automatically rebalance the remaining capital (from the 1 position sold) to the remaining 3 positions. How would I code the rebalance?
I’ve posted below the full code I have to date. I only want the signals to happen on a monthly timeframe (I’ve selected this in the settings). Trades are at the end of the month close. The other missing piece is if I’m left with 0 positions, I’d like to allocate the capital to Tbills instead of cash. Appreciate your help.

// --- detect watchlist ---
wlnumber       = GetOption( "FilterIncludeWatchlist" );
watchlist      = GetCategorySymbols( categoryWatchlist, wlnumber );
numberOfAssets = StrCount( watchlist, "," ) + 1;
N              = numberOfAssets;

// --- backtester settings --- 
PosQty = Param( "Number of Positions", 4, 1, N, 1) ; // Position Quantity: max number of positions
SetOption( "CommissionAmount", 0.00 );
SetOption( "InitialEquity", 100000 );
SetOption( "MaxOpenshort", 0 );
SetOption( "MaxOpenLong", PosQty );
SetOption( "MaxOpenPositions", PosQty );
SetOption( "AllowPositionShrinking", True );
SetPositionSize( 100 / PosQty, spsPercentOfEquity );
SetTradeDelays( 0, 0, 0, 0 );

 
MAValue = 10;
MA_Monthly = MA (C, MAValue);
 
HighValue = 3;
Highest_Monthly = Ref(HHV(C, HighValue), -1);
 
MABuy = C > MA_Monthly;
MASell = C < MA_Monthly;
HighBuy = C > Highest_Monthly;
 
Buy = MABuy AND HighBuy;
Sell = MASell;
 
Buy = ExRem ( Buy, Sell);
Sell = ExRem ( Sell, Buy);

One clarification. What I mean by:

is to rebalance the full portfolio capital to the 3 positions that are still in a buy signal at the end of the month. i.e. If the total Portfolio value is $125,000 after I sell 1 position and the remaining 3 positions are still in a buy signal, allocate $125,000 evenly across the 3 positions. Hope this makes sense.

Chad

1 Like

To possibly use T-Bill’s instead of cash you can consider the ETF’s that hold T-bill’s and short term fixed income, (U.S. exchanges) SHY or BIL. If those ETF’s are in your trading watch list then you can use them if less than 4 securities meet your buy criteria.

I think you will likely need to use the Custom Backtest Interface (often referred to as the CBT) for your re-balancing code. It should really be used by moderately advanced users, and you did mention being new to AmiBroker. So there are some examples in these links below.

Most of the codes that I have seen/coded for rebalancing were as part of momentum based rotational systems. I can point you in the direction of some (or a lot) of reading and possible code solutions. I am familiar with momentum based rotational portfolio’s which seem similar to what you are attempting.

Official Knowledge Base article on rebalancing in the context of a rotational strategy, http://www.amibroker.com/kb/index.php?s=rebalance

Rotational trading code from Official Knowledge Base,
http://www.amibroker.com/kb/2016/04/17/long-only-rotational-back-test/

A couple of threads on the old forum that had several posts about rebalancing worth reviewing,
https://groups.yahoo.com/neo/groups/amibroker/conversations/topics/191308

https://groups.yahoo.com/neo/groups/amibroker/conversations/topics/158253

https://groups.yahoo.com/neo/groups/amibroker/conversations/topics/178982

A blogger that primarily builds rotational models using AmiBroker,

A blog post on building a rotational system using AmiBroker,

A trend following system using Bollinger band breakout,

A completely unrelated strategy (mean reversion) but with examples of scaling in code in afl. This is in the user’s library which is codes created by users. It may be worth spending some time browsing other codes in the library as you may find something similar to what you are attempting. This one is not but it is an interesting example of scaling up code
http://www.amibroker.com/members/library/detail.php?id=1380

After reading and experimenting with those codes it may still be worth your while getting a more advanced user to help with the code writing (if it is a system you believe is worth seriously exploring then that is what I would do).

7 Likes

Thanks for the resources portfoliobuilder. I will start digging in to see if I can find the solution.

Cheers,
Chad

Hi Chad, Just wondering if you got the answer to this question. I would be interested in knowing if you did as I am trying to do the same thing. Many Thanks, Oliver

Likewise, I am looking for an example strategy that remains 100% invested in let's say all the stocks in a watchlist that have an ROC of less than 20.

I don't have a concise example to share, but this should just be a small variation on writing your own rotational logic in the CBT. The primary difference is that the number of positions varies on each rotation date.