Lot calculation by Vince - page 11

 

Finding the optimum f using the geometric mean.

In real trading the size of losses and gains will be constantly changing. So Kelly's formulas cannot give us the correct optimal f. How correctly from the mathematical point of view to find the optimal f, which will allow us to determine the number of contracts to trade? Let us try to answer this question. First, we have to modify the formula for finding HPR to include f:

further see formulas from the first post

further

We have seen that the best trading system is the system with the highest geometric mean. To calculate the geometric mean we need to know f. So, let us describe our actions step by step.

1. Take the history of transactions in the given market system.

2. Find the optimum f by looking at various values of f from 0 to 1. The optimum f corresponds to the highest value of TWR.

3. Onceyou find f, take the root of degree N ofTWR (N is the total number of trades). This is your geometric mean for this market system. Now you can use the obtained geometric mean to compare this system with others. The f-value will tell you how many contracts to trade in this market system. Once f is found, it can be converted into the money equivalent by dividing the biggest loss by the negative optimal/. For example, if the largest loss is equal to $100, and optimal f = 0.25, then -$100 / -0.25 = $400. In other words, you should bet 1 unit for every $400 account. For simplicity you can calculate everything on a unit basis (e.g. one $5 chip or one futures contract, or 100 stocks). The number of dollars to allocate to each unit can be calculated by dividing your largest loss by the negative optimal f. The optimalf is the result of balancing the profitability of the system (based on 1 unit) and its risk (based on 1 unit). Many people think that the optimal fixed fraction is the percentage of the account that is allocated to your bets. This is completely wrong. There has to be another step. The optimal f by itself is not the percentage of your account that is allocated to the trade, it is the divisor of the biggest loss. The quotient of this division is the value by which you have to divide your total account in order to find out how many bets to place or how many contracts to open in the market.

I.e. AccountFreeMargin()/H, with H=D/(-f).

Here's how it's organised in the cov code - see trailer.

if (optimal_f) //--- Расчет оптимального f ---
        {   
          
          double Mas_Outcome_of_transactions [10000];        // Массив профитов/убытков закрытых позиций
          int Qnt = 0, Orders = OrdersHistoryTotal();        // Счётчик количества ордеров   
          ArrayInitialize(Mas_Outcome_of_transactions, 0);   // Обнуление массива
          double f, D, SUMM, TWR, G, G_Rez, H,A,B, Pow;
          int orderIndex;
   
          for (orderIndex = 0; orderIndex < Orders; orderIndex++)
          {   
             if (!OrderSelect(orderIndex, SELECT_BY_POS, MODE_HISTORY))
              {
                Print("Ошибка при доступе к исторической базе (",GetLastError(),")");
                continue;
              }
   
             if (OrderSymbol() != Symbol() || OrderMagicNumber() != MAGICMA || OrderCloseTime()==0)
                continue; 
         
             int lastType = OrderType();
             double lastLots = OrderLots();
             double lastProfit = OrderProfit() + OrderSwap();
      
             if (orderIndex == 0 || lastProfit < D)
                D = lastProfit;
      
             Mas_Outcome_of_transactions[Qnt] = lastProfit;  // Заполняем массив профитом/лоссом по всем закрытым позициям 
             SUMM=SUMM+lastProfit;
             Qnt++;                                          // увеличиваем счетчик закрытых ордеров    
          }   
   
         if (Transaction_number<Qnt) { //при репрезентативном кол-ве ордеров на истории открываемся объемом через оптим-ую f 
            Pow = 1/NormalizeDouble(Orders, 0);
            for (f = 0.01; f<=1.0; f=f+0.01)                   // цикл перебора переменной f для поиска оптимального ее значения,
            {                                                  // при котором TWR - максимально
               G= 1;
               for ( orderIndex = 1; orderIndex < Qnt; orderIndex++) // при заданной f проходим по всем закрытым ордерам
                {                                                     // и считаем среднее геометрическое от TWR
                  TWR = 1+f*(-Mas_Outcome_of_transactions[orderIndex]/(D));
                  G *= NormalizeDouble (MathPow(TWR, Pow),8);
                }
               if (G > G_Rez)  G_Rez = G;// если текущий > результирующего, то результирующий делаем равным текущему
               else break;               // иначе переходим на следующую итерацию цикла по f
            }
               
            
            if (f>0) H=D/(-f); //денежный эквивалент фракций (оптимального f) для торговли 0,1 лотом.
            lot = NormalizeDouble((AccountFreeMargin()/H)*Min_Lot,1);
            if (lot==0)    lot=Min_Lot;
            Print("H=D/(-f): ", H, " lot = ", DoubleToStr (lot,1), "Transaction_number = ", Transaction_number);  
            Print("G_Rez максимальна = ", DoubleToStr (G_Rez,8), " при f = ", f);             
            Print(" Максимальный лосс по позиции, D = ", DoubleToStr(D, 2), " Pow (1/Orders)= ", DoubleToStr(Pow, 8));
            Print("Закрытых позиций = ",   Qnt,
                " Нетто Профит/лосс = ", SUMM,
                " У последней ",         Qnt,
                " закрытой позы профит/лосс = ", Mas_Outcome_of_transactions[Qnt-1]);  
                
            return(lot);         
          }    // Выход из  if (Transaction_number<Qnt)                   
          else {
             lot=Min_Lot; 
             Print("Закрытых позиций = ",   Qnt, " Transaction_number = ", Transaction_number);
             return(lot); 
          } 
  
      }  //Выход из расчета оптимального f     

So everything is correct here - Strictly by the book.

Twist this to your sOves, test it, check it, share results here.

Files:
 
ph3onix:

1. The first thing that comes to mind is that the lot size should be based on the stop loss on the next position,

2. knowing the fraction of the deoposit that Vince's maths recommends to use in the trade

3...the lot size used in testing EAs in this thread is a bit wrong


1. this is where you need to go.

2. You are not familiar with Vince's maths, he recommends a completely different approach, we are not talking about "fractions" as you write ...

"

Optimal f in itself is not the percentage of your account that is allocated for trading, it is the divisor of the biggest loss. The quotient of that division is the value, by which you need to divide your total account, in order to find out how many bets to place or how many contracts to open in the market.

"

3. All strictly according to the information from the source - read carefully, especially from page 31, compare on your sOves, check, share the results.

 

The topic is not closed, continuation follows...

The lot calculation function is publicly available here in the EA (see trailer).

Files:
 

You guys are clearly overthinking something. TWR is a measure of how many times the initial account has been increased. Optimal f is the risk per trade as a percentage of the deposit. TWR is a derivative of the optimal f. Simply calculate the percentage risk in the strategy tester from 1 to 100% per trade. After a certain value, the final profit will stop growing. This value will be the optimal value of f.

If you make such a mess for simple percentage of the deposit, then it is scary to imagine how you start to calculate the optimal G (yes, there is such a thing).

 
C-4:

You guys are clearly overthinking something. TWR is a measure of how many times the initial account has been increased. The optimal f is the risk per trade as a percentage of the deposit. TWR is a derivative of the optimal f. Simply calculate the percentage risk in the strategy tester from 1 to 100% per trade. After a certain value, the final profit will stop growing. This value will be the optimal value of f.

If you create such a mess for simple percentage of deposit, then it is scary to imagine how you start to calculate the optimal G.


It's already calculated - all beats, all tested, see the thread first... :-)

"How do you calculate the optimal G..." - everything is calculated from the source...

 if (Transaction_number<Qnt) { //при репрезентативном кол-ве ордеров на истории открываемся объемом через оптим-ую f 
            Pow = 1/NormalizeDouble(Orders, 0);
            for (f = 0.01; f<=1.0; f=f+0.01)                   // цикл перебора переменной f для поиска оптимального ее значения,
            {                                                  // при котором TWR - максимально
               G= 1;
               for ( orderIndex = 1; orderIndex < Qnt; orderIndex++) // при заданной f проходим по всем закрытым ордерам
                {                                                     // и считаем среднее геометрическое от TWR
                  TWR = 1+f*(-Mas_Outcome_of_transactions[orderIndex]/(D));
                  G *= NormalizeDouble (MathPow(TWR, Pow),8);
                }
               if (G > G_Rez)  G_Rez = G;// если текущий > результирующего, то результирующий делаем равным текущему
               else break;               // иначе переходим на следующую итерацию цикла по f
            }
               
            
            if (f>0) H=D/(-f); //денежный эквивалент фракций (оптимального f) для торговли 0,1 лотом.
            lot = NormalizeDouble((AccountFreeMargin()/H)*Min_Lot,1);
 
C-4:

...

If you make such a mess for a simple percentage of the deposit, it is scary to imagine how you will start to calculate the optimal G (yes, there is such a thing).

I haven't come across it yet, I'll look it up, what kind of bird is this - optimal G...?
 
The optimal G is the capitalisation factor of the portfolio. In order to find the optimal G, one must at least optimise the variance of the total portfolio and be fluent in Markowitz's portfolio theory. I see nothing of the sort in these calculations.
 

C-4:
1. Оптимальное G - это фактор капитализации портфеля. Для поиска оптимального G нужно как минимум оптимизировать дисперсию совокупного портфеля и свободно разбираться в портфельной теории Марковица.

2. I don't see anything wrong with the above calculations.


1. I see - this is closer to the calculation and the order of portfolio formation... I am interested in the question.

2. This is not present here. I have confused the optimum G with the geometric mean G, the calculation of which is present here... :-)

See the first post of the first page of the thread.

"

Geometric mean trade

A trader may be interested in calculating his geometric mean trade (that is, the average profit made per contract per trade), assuming that profits are reinvested and fractional contracts can be traded. This is the mathematical expectation when trading on a fixed fraction basis. In reality, this is the system's approximate return per trade when using a fixed fraction of the account.(The geometric mean is actually the mathematical expectation in dollars per contract per trade. Subtract one from the geometric mean and you get the mathematical expectation. Geometric mean of 1.025 corresponds to the mathematical expectation of 2.5% per trade). Many traders look only at the average deal of the market system to see if it is worth trading on this system. However, it is the geometric mean trade (GAT) that should be taken into considerationwhen making a decision.

where G = geometric average - 1;

f = optimal fixed share.

(Of course, the largest loss will always be a negative number).

 
I wouldn't get too carried away with this crap if I were you. All of Vince's maths is based on fitting. The f itself is unstable and tends to collapse over time, is also extremely sensitive to the Z-Score or leverage asymmetry effect, and gives an extremely uneven profit distribution: the first 90% of the time it will take to make 10% profit.
 
C-4:
I wouldn't get too carried away with this crap if I were you. Vince's whole mathematics is based on fitting. The f itself is not stable and tends to collapse over time, in addition it is extremely sensitive to the Z-Score or leverage asymmetry effect, also gives an extremely uneven profit distribution: the first 90% of the time it will take to make 10% profit.


Thank you, Vasily for the information, what it is and what it may lead to... I'm not much into these lot calculations, it was just interesting to bang it all out and look from different angles and compare it with other approaches to MM in one or another covenant...

He, by the way, also touches on the subject of diversification with portfolio theory...:-) Especially when THOSE words are highlighted in red...:-) There is a book, there are formulas - how can you not put this information into a code and see how it calculates the lot in action at various soviets, I wonder... Open the book - write a system using it, look at its behaviour in a tester, on a demo, for a start... this and that... :-) Digging, in general. By the way, I recently monitored a demo account with META-SOT indicators, purely on the basis of your article, without shadows of other types of market behavior analysis - everything is profitable so far ... :-)

"

The better

system, the higher f. The higher f, the greater the possible loss, because the maximum loss (as a percentage) is not less than f. The paradox of the situation is that if a system is capable of producing a sufficiently high optimal f, then the loss for such a system will also be sufficiently high. On the one hand optimal f allows you to get the highest geometric growth, on the other hand it creates a trap for you that you can easily fall into.

We know that if you use optimal f when trading a fixed share, you can expect significant losses (as a percentage of your balance). Optimal f is like plutonium - it gives enormous power, but it is also extremely dangerous. These large losses are a big problem, especially for beginners, because trading at the level of optimum f creates a risk of huge losses faster than in regular trading. Diversification can greatly mitigate losses. The plus side of diversification is that it allows you to make many attempts (run many games) at the same time, thereby increasing your overall profits. It is fair to say that diversification, while usually the best way to smooth out losses, does not necessarily reduce them and in some cases can even increase losses!

There is a misconception that losses can be completely avoided if diversification is effective enough. It is true to some extent that losses can be mitigated through effective diversification, but they can never be completely avoided. Do not be misled. No matter how good the system applied is, no matter how effectively you diversify, you will still encounter significant losses. The reason for this is not because your market systems are mutually correlated, because there are times when most or all of the portfolio's market systems work against you when you think it shouldn't. Try to find a portfolio with five years of historical data so that all trading systems would work at optimum f and still have a maximum loss of less than 30%! It will not be easy. It doesn't matter how many market systems are used. If you want to do everything mathematically correct, you have to be prepared to lose 30 to 95% of your account balance. Strict discipline is required and not everybody can follow it.

As soon as a trader gives up trading a constant number of contracts, he/she faces the problem of how many to trade. It always happens irrespective of whether the trader recognizes this problem or not. Trading a constant number of contracts is not a solution, because this way you will never achieve geometric growth. Therefore, whether you like it or not, the question of how many to trade in the next trade will be unavoidable for everyone. Simply choosing a random quantity can lead to a serious mistake. Optimal f is the only mathematically correct solution.

Modern portfolio theory

Think of a situation with an optimal f and a losing market system. The better the market system, the higher the value of f. However, if you trade with optimal f, the loss (historically) can never be less than f. Generally speaking, the better the market system, the greater the intermediate losses (as a percentage of account balance) will be if you trade at optimal f. Thus, if you want to achieve the highest geometric growth, you must be prepared for serious losses along the way.

"

Reason: