Australian (ASX) Stock Market Forum

Amibroker FAQ

Yep. Answered my own question I think. The following finds the first trading day of the week.

DayOfWeek() < Ref( DayOfWeek(), -1 );
 
Yep. Answered my own question I think. The following finds the first trading day of the week.

DayOfWeek() < Ref( DayOfWeek(), -1 );

Here is another tip.
If you have multiple calls of the same array function then store it to a variable. That way it is called just one time.
This is especially recommended if your code(s) become multiple hundreds or thousands of lines long.
I have seen dozens of AFLs were functions (having same settings) are called hundreds of times over and over again. That's ridiculous.

So using your upper basic example do like so, for example

Code:
dow = DayOfWeek();

startofweek = dow  < Ref( dow, -1 );

It's like learning to drive bicycle the first time, either you start driving wrong or correctly and safely removing bad habits right from the start.
 
Hi,

I am new to Amibroker and programming so any help with this (hopefully basic) problem is appreciated.

I have coded a basic 20 period breakout system but have the following problem:

When I look on the backtest report it appears that not all relevant trades are included. For example, the backtest report shows one trade for IMI.L over a 12 year period. However when I look on the chart for IMI there are at least 6 trades.

I don't think the problem is a result of the system being fully invested and therefore the missing trades are not included. I've specified a maximum of 20 position but the system never gets to a point where there are 20 positions.

Again, thanks for any help. I need to move on from a few time consuming problems now.

Here is the code at the moment. Apologies for the amateurish nature of code but it is a reflection of my inexperience.

Code:
SetOption("MaxOpenPositions", 20);
SetPositionSize(5, spsPercentOfEquity);

Index = Foreign ("^FTSE", "C", True);
IndexMa = Index >= MA(Index, 10);

HighestValue = HHV(C, 20);
LowestValue= LLV(C, 20);

// ATR Stop Length //
stopLength = (7 * ATR(10));

// Buys and sells //
Buy = C >= HighestValue AND IndexMA;
Sell = C = 0;

// Stop loss //
ApplyStop (stopTypeTrailing, stopModePoint, stopLength, 2, True, 1);

// Plotting stop loss //
Equity(1, 0); // evaluate stops, all quotes

inTrade = Flip (Buy, Sell); // True when buy / False when sell

SetOption ("EveryBarNullCheck", True); // checks for null bars

stopline = IIf (inTrade, HighestSince (Buy, H - stopLength), Null);

Plot(stopline, "Trailing Stop Line", colorRed, styleLine, 0, 0, 0, 0);


Plot(HighestValue, "High", colorGreen, styleLine, 0, 0, 0, 0);

ribbonColor = IIf (IndexMA , colorGreen, colorRed); // color the ribbon. If IndexMA is true, colorGreen, if not true, Red
Plot (3, "", ribbonColor, styleArea|styleOwnScale, 0, 100); // plot the ribbon
 
Hi,

I am new to Amibroker and programming so any help with this (hopefully basic) problem is appreciated.

I have coded a basic 20 period breakout system but have the following problem:

When I look on the backtest report it appears that not all relevant trades are included. For example, the backtest report shows one trade for IMI.L over a 12 year period. However when I look on the chart for IMI there are at least 6 trades.

I don't think the problem is a result of the system being fully invested and therefore the missing trades are not included. I've specified a maximum of 20 position but the system never gets to a point where there are 20 positions.

Again, thanks for any help. I need to move on from a few time consuming problems now.

Here is the code at the moment. Apologies for the amateurish nature of code but it is a reflection of my inexperience.

Code:
SetOption("MaxOpenPositions", 20);
SetPositionSize(5, spsPercentOfEquity);

Index = Foreign ("^FTSE", "C", True);
IndexMa = Index >= MA(Index, 10);

HighestValue = HHV(C, 20);
LowestValue= LLV(C, 20);

// ATR Stop Length //
stopLength = (7 * ATR(10));

// Buys and sells //
Buy = C >= HighestValue AND IndexMA;
Sell = C = 0;

// Stop loss //
ApplyStop (stopTypeTrailing, stopModePoint, stopLength, 2, True, 1);

// Plotting stop loss //
Equity(1, 0); // evaluate stops, all quotes

inTrade = Flip (Buy, Sell); // True when buy / False when sell

SetOption ("EveryBarNullCheck", True); // checks for null bars

stopline = IIf (inTrade, HighestSince (Buy, H - stopLength), Null);

Plot(stopline, "Trailing Stop Line", colorRed, styleLine, 0, 0, 0, 0);


Plot(HighestValue, "High", colorGreen, styleLine, 0, 0, 0, 0);

ribbonColor = IIf (IndexMA , colorGreen, colorRed); // color the ribbon. If IndexMA is true, colorGreen, if not true, Red
Plot (3, "", ribbonColor, styleArea|styleOwnScale, 0, 100); // plot the ribbon

Check you initial equity setting. It could be too low since you have set 5% of equity as position size.
Also check "Limit trade size as % of entry bar volume" in backtest settings' Portfolio tab.

BTW why do you set price to zero in this line?
Sell = C = 0;

Just use
Sell = 0;
 
Check you initial equity setting. It could be too low since you have set 5% of equity as position size.
Also check "Limit trade size as % of entry bar volume" in backtest settings' Portfolio tab.

BTW why do you set price to zero in this line?
Sell = C = 0;

Just use
Sell = 0;

Thank you sir.

Problem not resolved but thanks for that correction to the code and making me aware of some other things to look at.

Currently this system only has 14 positions open yet I can see many cases where a trade should have been made. So some further work by me to understand why this simple system is not functioning properly.

Cheers.
 
Thank you sir.

Problem not resolved but thanks for that correction to the code and making me aware of some other things to look at.

Currently this system only has 14 positions open yet I can see many cases where a trade should have been made. So some further work by me to understand why this simple system is not functioning properly.

Cheers.

Do you agree that there are 20 open positions from Jan 2007 to Feb 15 2007 in this example and on March 20 2007 it's again 20 open positions since two ones were exited before.

ODvvSHE.png

So I don't know if we talk about the same things.

Activate the detailed log in backtest settings Report tab.


BTW, Equity() function is SINGLE SECURITY EQUITY!
https://www.amibroker.com/guide/afl/equity.html
 
Do you agree that there are 20 open positions from Jan 2007 to Feb 15 2007 in this example and on March 20 2007 it's again 20 open positions since two ones were exited before.

ODvvSHE.png

So I don't know if we talk about the same things.

Activate the detailed log in backtest settings Report tab.


BTW, Equity() function is SINGLE SECURITY EQUITY!
https://www.amibroker.com/guide/afl/equity.html


Hi,

Yes, it looks like 20 positions are open on your example.

It occurred to me that in some cases there might not be enough equity to open a new position at, for example, 5% of equity. Do you know how Amibroker deals with this? I would like to be fully invested (ideally 20 positions) so is there a way to tell Amibroker to use all available funds?

I hope that is clear but if not here is an example:

- Say you instruct AB to open (maximum) 10 positions at 10% equity each.
- Account size $100,000 so each position $10,000.
- 9 position are 20% up and remain open (equity £108,000).
- 1 position hits stop 45% stop (equity left $5,500).
- Total remaining equity is $113,500 meaning a new position should be opened at 5% of equity.
- 5% of $113,500 is $5,675......but there is only $5,500 available.

Apologies as I know this is very basic stuff but this has opened up a whole series of problems for me. Do you know how Amibroker deals with this? My other concern is the effects of selection bias in such a system.

Any help / advise is appreciated.
 
Hi,

Yes, it looks like 20 positions are open on your example.

It occurred to me that in some cases there might not be enough equity to open a new position at, for example, 5% of equity. Do you know how Amibroker deals with this? I would like to be fully invested (ideally 20 positions) so is there a way to tell Amibroker to use all available funds?

Again.. if you are unsure what is happening activate the Detailed log in backtest settings Report tab.

I hope that is clear but if not here is an example:

- Say you instruct AB to open (maximum) 10 positions at 10% equity each.
- Account size $100,000 so each position $10,000.
- 9 position are 20% up and remain open (equity £108,000).
- 1 position hits stop 45% stop (equity left $5,500).
- Total remaining equity is $113,500 meaning a new position should be opened at 5% of equity.
- 5% of $113,500 is $5,675......but there is only $5,500 available.

Apologies as I know this is very basic stuff but this has opened up a whole series of problems for me. Do you know how Amibroker deals with this? My other concern is the effects of selection bias in such a system.

Any help / advise is appreciated.

If you want to invest in remaining cash instead of 5%, 10%, ... of equity then you would have to program that via custom backtester https://www.amibroker.com/guide/a_custombacktest.html
 
Hi,

Yes, it looks like 20 positions are open on your example.

It occurred to me that in some cases there might not be enough equity to open a new position at, for example, 5% of equity. Do you know how Amibroker deals with this? I would like to be fully invested (ideally 20 positions) so is there a way to tell Amibroker to use all available funds?

I hope that is clear but if not here is an example:

- Say you instruct AB to open (maximum) 10 positions at 10% equity each.
- Account size $100,000 so each position $10,000.
- 9 position are 20% up and remain open (equity £108,000).
- 1 position hits stop 45% stop (equity left $5,500).
- Total remaining equity is $113,500 meaning a new position should be opened at 5% of equity.
- 5% of $113,500 is $5,675......but there is only $5,500 available.

Apologies as I know this is very basic stuff but this has opened up a whole series of problems for me. Do you know how Amibroker deals with this? My other concern is the effects of selection bias in such a system.

Any help / advise is appreciated.


Try SetOption(Allow Position Size Shrinking) see if that helps.

Also, see https://www.amibroker.com/guide/w_settings.html

Allow position size shrinking
If you mark this box AmiBroker will shrink down positions if available equity is less than requested position size (via PositionSize variable). If this box is unmarked positions will not be entered in such case.
 
There are three ways for this:
- CBT (custom backtest interface), in case for more flexibility
- checking Allow Position Size Shrinking in backtest settings General tab
- via AFL function SetOption( "AllowPositionShrinking" );
 
There are three ways for this:
- CBT (custom backtest interface), in case for more flexibility
- checking Allow Position Size Shrinking in backtest settings General tab
- via AFL function SetOption( "AllowPositionShrinking" );

Minor Point..
- via AFL function SetOption( "AllowPositionShrinking", True );
 
Back to time periodicy...

I am now trying to find every fortnight. The code below when plotted does the job fine, however when put into a trading system no trades are taken. I don't know why.

Code:
// Days of the week
timeDayName = DayOfWeek();

// Every Friday
checkEndWeek = timeDayName < Ref( timeDayName, -1 );

// Every fortnight
checkEndWeekCount = Cum( checkEndWeek );
checkEndFortnight = checkEndWeek AND ( checkEndWeekCount % 2 == 0 );

This is for a rotational trading system and after running the backtest with detailed log it shows scoring weekly but no trades are taken which is a clue I guess. Any help appreciated.
 
Also, a while ago I found an AFL for a profit table that colored the cells based on positive or negative values. Does anyone have something similar? I lost mine and can't work out how to modify the code in the default one.
 
Back to time periodicy...

I am now trying to find every fortnight. The code below when plotted does the job fine, however when put into a trading system no trades are taken. I don't know why.

Code:
// Days of the week
timeDayName = DayOfWeek();

// Every Friday
checkEndWeek = timeDayName < Ref( timeDayName, -1 );

// Every fortnight
checkEndWeekCount = Cum( checkEndWeek );
checkEndFortnight = checkEndWeek AND ( checkEndWeekCount % 2 == 0 );

This is for a rotational trading system and after running the backtest with detailed log it shows scoring weekly but no trades are taken which is a clue I guess. Any help appreciated.



Code:
SetBacktestMode( backtestRotational );
SetPositionSize( 1, spsShares );

score = 100 - RSI(); // example score

rotation = checkEndFortnight;

PositionScore = IIf( rotation, score, scoreNoRotate );
 
Also, a while ago I found an AFL for a profit table that colored the cells based on positive or negative values. Does anyone have something similar? I lost mine and can't work out how to modify the code in the default one.

You have to comment color variable within PrintInCell function of ProfitTable AFL and add a color argument to same function.

Code:
function PrintInCell( string, row, Col, Color ) 
{
 //Color =  ColorRGB( IIf( row == 0 || col == 0 || col == 13, 220, 255 ), 255, IIf( row % 2, 255, 220 ) );
 GfxSelectSolidBrush( Color   );
 GfxRectangle( Col * CellWidth, 
                    row * CellHeight, (Col + 1 ) * CellWidth + 1, 
                    (row + 1 ) * CellHeight  + 1); 
 GfxDrawText( string, Col * CellWidth + 1, 
                    row * CellHeight + 1, 
                    (Col + 1 ) * CellWidth, (row + 1 ) * CellHeight, 32+5 ); 
}

Then in each call of PrintInCell function within DisplayProfitTable() function you add custom color.

for example for variable mth color
Code:
for ( m = 1; m <= 12; m++ ) { 
   Chg = VarGet( "ChgMon" + y + "-" + m ); 
   mthcolor = IIf( Chg > 0, colorGreen, colorRed ); 

   if ( Chg ) 
      PrintInCell( StrFormat( "%.1f%%", Chg ), Row, m, mthcolor ); 
   else 
      PrintInCell( "N/A", Row, m, colorWhite ); 
}
 
Code:
SetBacktestMode( backtestRotational );
SetPositionSize( 1, spsShares );

score = 100 - RSI(); // example score

rotation = checkEndFortnight;

PositionScore = IIf( rotation, score, scoreNoRotate );

I definitely have a working score and positionScore algorithm in my model because it works with all other time periods. I have a list which is End of day, End of week, Fortnightly, End of month. They all work except for the Fortnightly. It's only the Fortnightly rotation period that throws back no trades.
 
I definitely have a working score and positionScore algorithm in my model because it works with all other time periods. I have a list which is End of day, End of week, Fortnightly, End of month. They all work except for the Fortnightly. It's only the Fortnightly rotation period that throws back no trades.

For me it works. Apply the code of my upper post to current members of DJ30 on daily time frame.

If it does not work for you you may upload an APX file (analysis project file).
 
Top