Profit factor AFL code

Hallo, could someone help me with profit factor AFL code?
Profit Factor is defined as gross profits divided by gross losses.

(IIf ( (Ref(Close,-1) - Ref(Open,0))>0, Sum (Ref(Close,-1) - Ref(Open,0),20),0)) / (IIf ( (Ref(Close,-1) - Ref(Open,0))<0, Sum (Ref(Close,-1) - Ref(Open,0),20),0)),_DEFAULT_NAME(),colorOrange );

This code is not working. Do you know the code for Profit factor?
Thank you

Profit Factor is based on trade entries and exits. Why are you trying to calculate it with Open and Close prices? Are you trying to calculate a different metric that is similar to Profit Factor but actually is not?

Hi mradtke, thank you for answer. This is just simple example system, where we buy on close of day and sell on open next day. For this I would need calculate Profit Factor. This Profit Factor I would use as Position Score for rotational backtest.
I would need calculate:
gross profits = this is sum of positive trades for N bars
gross losses = this is sum of negative trades for N bars

Please do you know how can I calculate it?
Thank you

Something similar to this untested snippet should work:

lookbackBars = 20;
tradeProfit = O - Ref(C,-1);
grossProfits = Sum(IIf(tradeProfit >=0, tradeProfit, 0), lookbackBars);
grossLosses = Sum(IIf(tradeProfit < 0, -tradeProfit, 0), lookbackBars);
pf = grossProfits / grossLosses ;
1 Like

Hi mradtke, thank you for answer again. Your code is great. I have change it little bit according my purpose….It looks very good, but there is problem in "pf" column. There is wrong division and it looks like that it is rounded, do you know how to solve it please?

lookbackBars = 5;
tradeProfit = O - Ref(C,-1);

profitcondition = tradeProfit >0;
losscondition = tradeProfit <= 0;

grossProfits = Sum(profitcondition, lookbackBars);
grossLosses = Sum(losscondition, lookbackBars);
pf = grossProfits / grossLosses ;
Filter = 1;
AddColumn( grossProfits , "grossProfits", 1, colorDefault, colorDefault, format=1.2) ;
AddColumn( profitcondition , "profitcondition", 1, colorDefault, colorDefault, format=1.2) ;
AddColumn( grossLosses , "grossLosses", 1, colorDefault, colorDefault, format=1.2) ;
AddColumn( losscondition , "losscondition", 1, colorDefault, colorDefault, format=1.2) ;
AddColumn( pf , "pf", 1, colorDefault, colorDefault, format=1.2) ;


Please see the picture attached

Thank you

Finally I found it:
AddColumn( pf , "pf",1.2) ;