[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to calculate STDev?



PureBytes Links

Trading Reference Links

> Vars: STDEV(0), Prof(0);
> 
> Prof = 1 + PositionProfit(1)/(EntryPrice(1)*BigPointValue);
> If LastBarOnChart and TotalTrades <> 0 then Begin
>  STDEV = StdDev(Prof, TotalTrades);
> End;
> 
> What´s wrong with the above code?

The biggest problem is that you're calculating the StdDev 
entirely wrong for what you want.

StdDev(Variable, Length) calculates the StdDev for the values of 
Variable on the last Length bars.  If I understand what you're 
trying to do, you want to calculate the StdDev of the profits of 
the last Length trades -- TotalTrades trades in your case, all 
the trades in your system.

To clarify, let's say your system made 50 trades.  And let's say 
the system didn't have any trades in the last 50 bars.  You would 
then have a StdDev of zero, because the value of Prof is 
*identical* for the last 50 bars.  StdDev is only looking at 
those last 50 values of Prof.

So you need to collect the profits of the each trade, and use 
THOSE to calculate your SD.  Probably the easiest way would be to 
use the StdDev_a function, something like this (untested):

  vars:  Ntrades(0);
  array:  TradeProf[500](0);
  if <<<just exited a trade>>> then begin
    Ntrades = Ntrades + 1;
    TradeProf[Ntrades] =
        1 + PositionProfit(1)/(EntryPrice(1)*BigPointValue);
  end;
  if LastBarOnChart and Ntrades <> 0 then begin
    STDEV = StdDev_a(TradeProf, Ntrades);
  end;

This code (or something close to it) will work for systems that 
have up to 500 trades, due to the size of the array.  If you want 
to handle more trades, increase the size of the array.

You could also calculate the SD yourself, which removes the 
array-length issue:

  vars:  SumX(0), SumX2(0), Ntrades(0);
  if <<<just exited a trade>>> then begin
    Ntrades = Ntrades + 1;
    Prof = 1 + PositionProfit(1)/(EntryPrice(1)*BigPointValue);
    SumX = SumX + Prof;
    SumX2 = SumX2 + Prof*Prof;
  end;
  if LastBarOnChart and Ntrades <> 0 then begin
    STDEV = SquareRoot(SumX2 - 2*SumX*(SumX/Ntrades) +
                       Ntrades*square(SumX/Ntrades));
  end;

I *think* that SD calculation is correct.   It matches the STDEV 
function in Excel, but not in Tradestation.  I trust Excel.

Gary