Amibroker Tutorial Video - Position Sizing In Amibroker With SetPositionSize Function

A short tutorial video by Adrian Reid (Enlightened Stock Trading) explaining how to implement and test different position sizing models in Amibroker for backtesting trading systems. Covers non-compounding methods (fixed shares, fixed value) and compounding methods (percent of equity, percent risk, percent volatility/ATR), with code examples using the SetPositionSize function and practical advice on choosing models.
Chapters
Are you looking for help on how to backtest your trading system with different position sizing models in amibroker?
Well, if that's the case, you're in the right place. My name is Adrian Reid, founder of Enlightened Stock Trading, and in this amibroker tutorial, I'm going to run through the different position sizing models you can use when backtesting your trading system in amibroker and how you can code them up and use them for yourself. So let's jump straight into it. For the purposes of this tutorial video, I've got a simple breakout trading system that I've designed for the Australian Stock Exchange. This system can be used on any stock market, but I happen to be testing it on the Australian Stock market and I know it works quite well there. Now, I don't recommend you trade this system, certainly without backtesting and refining and adding your own unique twist to it, but it's a really good start and certainly serves a good purpose for the demonstration of how to do position sizing in amibroker. So whenever I do a trading system, I always have the backtest setup section at the top here. And that just defines the sort of global parameters of the backtest. So how much starting equity, what the maximum number of open positions are, the account margin, whether or not using a custom backtest. And we're not in this video, the commission payments. I always include commissions in my backtesting to make sure that the backtest is realistic and then also the trade delays and the buy in and sell price parameters. Now, I'm not going to get into the detail of all of that. I'll cover that in other amibroker tutorial videos. But let's go down a little further now to the actual guts of the trading system. Now, I always separate in my trading systems parameters and rules. And because if I want to change a number, change an input parameter, I want to make sure that it's easy to see where I should change that, that I can track it, that it doesn't get lost. And similarly, if I change the rules, I want to make sure that the rules are easy to understand, written in plain English, without numbers and math all over the place. So I always have this block of parameters where I specify the value for each of the input parameters. Now, if you're going to do an optimization, then these would be optimized statements or they could also be param statements. But right now, for the purpose of this tutorial video, I'm just using a single input number because we're not going to do any optimization in this video. So here we've defined the minimum turnover which is part of my liquidity filter. The moving average bars, it's a 200 bar moving average. The number of breakout bars, it's a 500 bar breakout. The initial stop multiple, it's a 6 ATR initial stop loss and the default position size is 0.5% risk per trade. So what are the rules of the system? Well, the trading system rules are down here we've got a slow moving average which is a 200 bar exponential moving average. You can see this MA function refers up to MA bars which is 200. I've also got a minimum turnover requirement. Because we can only trade liquid stocks. I want to filter out anything that doesn't have a sufficiently high trading volume. And the entry rule is a highest high breakout. So when today's close is the highest close of the last 200 days then actually no, sorry, the last 500 days, then we're going to enter the stock and we're going to hold the stock and sell it. When the price crosses below the slow moving average or the 200 day moving average and you can see the buy and sell lines, pull all that together here. I've also got a position score model to rank the trades and I've got a volatility based stop loss. I'm not going to go through the code of the stop loss in this video. I'll cover the apply stop function in a separate Amy Berke tutorial video. So now let's talk about position sizing. There's a number of different position sizing models you could use in your backtest and most of these are covered in the literature, particularly by Van Tharp in Trade youe Way to Financial Freedom or the Definitive Guide to Position Sizing. But I want to cover today the position sizing methods you can use specifically in amibroker. And first we'll cover the non compounding methods and then we'll cover the compounding methods. Non compounding position sizing models are position sizing models where the position size is constant for the life of the test. And compounding models are position sizing models where as the account equity grows, the position size also grows. And so you get that nice exponential growth in your equity curve which is what you're looking for in real time trading. So first of all, non compounding models, the first model you can use in amibroker is the number of shares per trade model. And the way we define position sizing in amibroker is using this argument here or this statement here called set position size. And set position size is a function that amibroker understands and only has two input values. The first input is a value. That's the number that amibroker is going to use to determine position size. And, and the second is the model, the position size model that you're telling amibroker to use. So in order to trade a certain number of shares or contracts per trade, we're going to use SPS shares.
So this is the whole statement to do your position sizing. Set position size, open brackets, then a number, and in this case 100. This represents 100 shares. And we're going to tell Amibroker it's shares because we're using SPSS shares. And then we finish with a bracket and a semicolon. So remember, all lines of code in amibroker must end with a semicolon because it tells amibroker that line is finished and to move on to the next one. So set position size 100 SPSS shares will force your backtest to take 100 shares of each stock every time a trade is triggered. So every trade will be 100 shares. Now in reality, you're never going to trade like that. That just doesn't make sen sense at all because you really need to link your position size to your account size and also to the specific stock you're trading. But this can have some useful applications. This number of shares position sizing model in back testing and in checking the validity stability of your position sizing model. Like let's say for instance, you were trading ETFs and you wanted to check whether the edge in your trading system was stable over time. You might tell amibroker to take one ETF.
To buy one ETF every single time it gets a trading signal. And that way you can look at the backtest, the equity curve and see the profit over time from a single contract. And the idea is you want to make sure that that was fairly linear profit over time. But in reality, like I said, the number of shares per trade model is not one that I actively would recommend you. The second model that you can use is the value of positions. So the value of positions is like the dollar value of the trades. Now again, this has a non compounding model. So we're going to define a certain dollar value for every single trade in our backtest. Now I do use this in backtesting for checking stability of my system over time instability of the edge. So say, for example, I'm trading a system just like this One breakout system on regular stocks. And I want to make sure that the edge has remained constant over time. I might force Amibroker to take $10,000 of each stock every time it takes a trade and then look at that resulting equity curve. And what I'd like to see is a nice linear equity curve from bottom left to top right. And if it's linear and the angle is constant over the life of the backtest, that means the system is stable. But if the equity curve is sort of falling away or it turns over and starts losing money dramatically, then you know that the edge of the system has decayed. Now again, the value based position sizing model, you force amibroker to use that by saying SPS value in your set position sizing.
Code here. Now, you don't use that for real time trading most of the time, but it is a really useful tool for backtesting and to make sure that your system is stable. Now I'm going to cover the three main compounding position size models. The first one is percent of equity. Now this is the simplest, the way percent of equity position sizing model works is amibroker. Whenever you get a buy signal for a trade, it will go and look at the amount of equity you've got in your backtest on that day, multiply it by some set percentage and that's going to give you the dollar amount, dollar value of the position that Amy Broker is going to take in the backtest. So as an example, let's say you've got in your back test, you get a buy Signal and there's $100,000 in the account and you're using 5% of equity, then Amibroker is going to put $5,000 into that trade. And then if your account over time grows and goes up to say $200,000 and you're still using a 5% of equity model, then now the position is going to be twice as big and it's going to be $10,000 per trade. So that's how the percent of equity model works. How do we code it in a AME broker formula language? Well, again, you're just using set position size with these two standard arguments. And if you're using 5% of equity, you're typing 5 here and then SPS percent of equity. Now, SPS stands for set position size, just in case you're wondering. And this number here, this 5%, it's written as a whole number. So 5 represents 5%, 1 represents 1%, 0.5 represents 0.5%. And you can make this an input sort of parameter and optimize it and have Amy Brocker vary it automatically if you want to. Now the next compounding position size model you can use is percent risk. Now this was popularized by Van Tharp and other authors, but I particularly learned this from Trade youe Way to Financial Freedom and percent risk based position sizing model requires that your system has a stop loss. And the way it works is you have your entry price and you have your stop loss level and this distance between your entry price and your stop loss level, that is your risk on that trade under normal circumstances. And what the position sizing model does, the risk based position sizing model is it equates that risk to a certain percentage of your account. So let's say you wanted to risk half a percent of your account per trade. Then you're going to get amibroker to calculate the number of shares for you to buy in that trade so that this distance between your entry price and your stop loss equates to half a percent of your account. So how do we do that? Well, the way we do it is we modify the percent of equity position sizing formula that we used before. So first of all, like I said, we need a stop loss to use risk based position sizing. And we happen to have a stop loss in this system. And the width of the stop loss is defined by this line here, risk per share. And it's an ATR based stop loss. So I don't know if you remember up here we had an initial stop multiple of 6. So this stop loss is 6 ATRs wide, 6 times the average true range, which is quite a wide stop loss. So we're going to enter and if we're wrong in this trade and it falls, it's going to fall six times the average true range before it hits the stop loss and we get out.
So how do we calculate the number of shares to buy? Well, the position sizing model set. Position size requires two parameters. The percent risk of your account and the percent using this percent of equity model. So this percent size number, we want this to equate to half a percent of our equity. So the percent size is calculated by saying what is the percent risk on that trade? Now here we're defining percent risk as 0.5%. Like I said, 0.5% risk, not percent of equity. So if we lose on the trade, the loss should be 0.5 of a percent of our account. We need to now convert that to how much total exposure we need on that trade. So we're going to say 0.5% risk per trade. We multiply it by the buy price and then divide it by the risk per share. And that's going to tell us the percentage of our account to put into this trade. So again, the percentage of our account to put into this trade is equal to the percent risk on the trade times the buy price divided by the risk per share. And then this percent size number gets fed into the position sizing formula on the next line. So this is how you do percent risk based position sizing model and the percent risk. If we're wrong, we're going to lose 0.5% on this trade. And you can set that as optimization variables as well. So you can vary it from say 0.1 to 1% in steps of 0.1 and see how your system performs. So this, pardon me, this is the percent risk based position sizing model. Now the other position sizing model that Van Tharp talks about is the percent of volatility position sizing model. So what is the percent volatility position sizing model? Well, the percent volatility model aims to equate the volatility of your trade, the daily volatility of each position, to a certain percentage of your account. So maybe you want to say, for instance, equate one ATR1 average true range to 1% of equity. So the daily movement of each trade is roughly equivalent to 1% of equity or half a percent of equity. That's what the percent volatility model does. And again, we're going to calculate that in amibroker using a variation on the percent of equity position sizing model. There's a couple of different ways to do this, but this is the way that I do it. This is the way that I like. So first of all, we're going to define the volatility unit, the unit of measure or the indicator that we use to define volatility. And I tend to use average true range for this. Now I'm using yesterday's average true range because if you're placing your order at the Open, you don't yet know today's average true range. So you've got to use yesterday's average true range. And what percent volatility do I want to equate the average true range to? I've just picked a number and said 0.2. You've got to be careful using the percent volatility model that you don't end up having positions which are too big or risking too much. But that's A parameter for you to optimize and vary in your system testing. So we've defined the volatility units, average true range. We've defined the percent volatility that we want to equate the average true range to. I'm saying 0.2%. So let's convert it now to the percent size input that we need for this position sizing formula. Again, we're using the position sizing set, position size, percent size, sps, percent of equity. But we need to calculate the percent size so that it equates to a certain volatility.
Amount, equates the volatility to a certain percentage of our account. So we do that here on line 83. So the percent size is equal to the percent volatility per trade that we want times the buy price divided by the volatility units. So in this case it's the 2.2% volatility times the opening price divided by the average true range. Now, you'll notice this formula is very similar to the percent risk based formula here. It's just that the numerator and the denominator values aren't changed. So if you use this formula in your AFL code for your backtest, that will equate the ATR of each trade that you take on the day of entry to 0.2% of your account. So the bigger the volatility, the smaller the trade will be. The smaller the volatility, the bigger the trade will be. And this is quite useful. It's a useful alternative to allow you to normalize volatility between your different trades if you're not using a stop loss because you can measure the atr. And for a really volatile stock, you take a smaller position, and for a really quiet low volatility stock to take a bigger position. So the average daily movement of each of your positions tends to be the same. And that way no one position in your portfolio kind of wags the portfolio around. So a lot of people will divert to center equity position sizing models when you don't have a stop loss. But you don't need to do that. You can still normalize all your positions based on volatility. Now, which one of these trading position sizing models is best? Well, for backtesting, you're probably going to want to use the value of the position model and also one or all of these for real time trading. You're going to have to test each of these compounding models and find the one that works best with your system. Every single time I develop a trading system. I'll test each of these different position sizing models and find the one that happens to work best gives the most stable, smoothest returns for that system. So I have some systems that work on percent of equity, some that work on percent risk, and some that work on percent volatility. So there's no one right answer. You need to test it for yourself. So I hope you found this tutorial on position sizing in amibroker useful. Now, if you want to get this code to save you typing it all out for yourself and figuring out the syntax and so on, click the link below and download the code from this video so that you can just follow along, edit the code, and change it, and use it in your own trading systems. Again, my name is Adrian Reed. This is Enlightened Stock Trading, and I'll see you in the next amibroker tutorial video. Bye for now.
Sam.











