Below is a code to calculate the standard deviation of
monthly returns of the equity curve from a backtest. The monthly return is
defined as change in close of last trading day of last month to the close of
last trading day of this month. I ran a backtest from 1/1/2007 to 12/31/2008
(24 monthly returns). It correctly calculates the sigma for equity curve if the
current chart is the equity curve (~~~Equity). However if I change the current
chart to another symbol (eg. ^GSPC) then sigma is calculated incorrectly. I understand
that the reason is that the number of bar for changes to match the number of
bars in ^GSPC. Also 1/1 & 1/2/2007 are non-trading days. Does anybody have
any suggestions on how I can overcome these issues? TIA
eq =
Foreign
(
"~~~EQUITY"
,
"C"
);
mo =
Month
();
MonChange = mo !=
Ref
(
mo, -
1
);
MonthCnt =
Cum
(MonChange);
dt1=
DateTime
();
StartingBar =
0
;
////////////////////////////
// SKIP non-trading
bars
////////////////////////////
for
( i =
0
; i < BarCount; i++ )
{
if
( eq[ i ] )
{
StartingBar = i;
_TRACE
(
"StartingBar= "
+ i +
" Date: "
+
NumToStr
( dt1[i], formatDateTime ) +
" Eq: "
+ eq[i]);
break
;
}
}
////////////////////////////
// collect monthly
changes in equity
////////////////////////////
LastMoValue = Eq[ StartingBar ];
_TRACE
(
"LastMoValue: "
+ LastMoValue);
StartingEquity = Eq[ StartingBar ];
EndingEquity =
EndValue
( Eq ) ;
TotalReturn =
100
* ( EndingEquity[ StartingBar ] - StartingEquity[ StartingBar ] ) /
StartingEquity[ StartingBar ];
_TRACE
(
"StartingEquity: "
+ StartingEquity +
" EndingEquity: "
+ EndingEquity +
" TotalReturn:"
+
LastValue
(TotalReturn));
dt =
DateTime
();
Cnt =
0
;
Sum_mChgEq = Variance =
0
;
for
( i = StartingBar ; i < BarCount;
i++ )
{
if
( i<(StartingBar +
20
)) mChgEq[i] =
0
;
if
( (MonChange [ i ] && MonthCnt[i] <
LastValue
(MonthCnt) ))
{
mChgEq[i] =
100
* ( -
1
+ eq[ i-
1
] / LastMoValue );
Cnt = Cnt+
1
;
Sum_mChgEq = Sum_mChgEq + mChgEq[i];
LastMoValue = eq[ i-
1
];
}
else
if
( (MonthCnt[i] >=
LastValue
(MonthCnt)) && i == BarCount
-
1
)
{
mChgEq[i] =
100
* ( -
1
+ EndingEquity / LastMoValue );
Cnt = Cnt+
1
;
Sum_mChgEq = Sum_mChgEq + mChgEq[i];
}
}
Mean_mChgEq =
LastValue
(Sum_mChgEq) /
LastValue
(MonthCnt);
Deviation = SumDeviationSqrd =
0
;
for
( i = StartingBar ; i < BarCount;
i++ )
{
if
(mChgEq[i])
{
Deviation = (mChgEq[i] -
Mean_mChgEq);
DeviationSqrd[i] = Deviation[i] ^
2
;
SumDeviationSqrd = SumDeviationSqrd +
DeviationSqrd[i] ;
Variance = SumDeviationSqrd /
MonthCnt[i] ;
Sigma[i] =
sqrt
(Variance);
_TRACE
(
" i: "
+ i +
" Date: "
+
NumToStr
( dt[i], formatDateTime ) +
" LastMoValue: "
+ LastMoValue +
" mEq: "
+ eq [i-
1
] +
" mChgEq: "
+ mChgEq[i] +
" SumChgEq: "
+ Sum_mChgEq[i] +
" Mean_mChgEq: "
+ Mean_mChgEq[i] +
" Deviation: "
+ Deviation[i] +
" DeviationSqrd: "
+ DeviationSqrd[i] +
" Variance: "
+ Variance[i] +
" Sigma: "
+ Sigma[i]);
}
}