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

[amibroker] Re: Custom Optimization Metric



PureBytes Links

Trading Reference Links

Hi,
I'm not sure this is exactly what you want, however TJ posted this on the Knowledge Base and some smart types have modified some. I think this is almost the same as the original and give ideas to solve you requirement.
F

// Yearly/monthly profit chart

/* Low-level gfx example: Yearly/monthly profit chart

The code below is an little bit more complex example of Low Level Graphics
functions (see http://www.amibroker.com/guide/a_lowlevelgfx.html)

It allows to display the following charts:

   1. yearly/monthly profit table
   2. yearly profit bar chart
   3. monthly profit bar chart 
   4. average monthly profit bar chart 

The type of chart is switchable from Parameters dialog.

It should be applied to ~~~Equity - portfolio Equity symbol
(so it only produces output if you run backtest before using it).
*/
FixedEq = ParamToggle("Equity or Capital?","Open|Fixed",1);

SetBarsRequired(1000000,1000000);
Eq		= Foreign("~~~Equity", "C" );

yr		= Year();
mo		= Month();

YearChange	= yr != Ref( yr, -1 );
MonChange	= mo != Ref( mo, -1 );

FirstYr	= 0;
LastYr		= 0;

startbar	= 0;

////////////////////////////
// SKIP non-trading bars
////////////////////////////
for( i=0; i < BarCount; i++ )
{
  if( Eq[i] )
  {
    startbar = i;
    break;
  } 
}
//////////////////////////////////////////////
// collect yearly / monthly changes in equity
// into dynamic variables
//////////////////////////////////////////////
RefYrValue		= Eq[ Startbar ];
RefMoValue		= Eq[ startbar ];

LastYrValue	= Eq[ startbar ];
LastMoValue	= Eq[ startbar ];

MaxYrProfit	= MinYrProfit = 0;
MaxMoProfit	= MinMoProfit = 0;

for( i=startbar+1; i<BarCount; i++ )
{
  if( YearChange[i] || i == BarCount-1 )
  {
    if( !FixedEq ) { RefYrValue = LastYrValue; }
    else { RefYrValue = Eq[startbar]; }//keeps Initial Equity

    Chg = 100 * ( Eq[i] - LastYrValue ) / RefYrValue;
    VarSet("ChgYear"+ yr[i-1], Chg );//year chg each year

    MaxYrProfit = Max( MaxYrProfit, Chg );
    MinYrProfit = Min( MinYrProfit, Chg );

    if( FirstYr == 0 ) FirstYr = yr[i-1];
    LastYr = yr[i];

    LastYrValue = Eq[i];
  }

  if( MonChange[i] || i == BarCount-1 )
  {
    mon = mo[i-1];

    if( !FixedEq ) { RefMoValue = LastMoValue; }
    else { RefMoValue = Eq[startbar]; }//keeps Initial Equity

    Chg = 100 * ( Eq[i] - LastMoValue )/ RefMoValue;

    VarSet("ChgMon" + yr[i-1] + "-" + mon, Chg );//month chg each year
    VarSet("SumChgMon"+ mon, Chg + Nz( VarGet("SumChgMon"+ mon ) ) );
    VarSet("SumMon" + mon, 1 + Nz( VarGet("SumMon"+ mon ) ) );
 
    MaxMoProfit = Max( MaxMoProfit, Chg );
    MinMoProfit = Min( MinMoProfit, Chg );

    LastMoValue = Eq[i];

  }
}
/////////////////////////////////////////////////
// Drawing code & helper functions
////////////////////////////////////////////////

GfxSetOverlayMode(2);

CellHeight		= (Status("pxheight")-1)/(LastYr - FirstYr + 3 ); 
CellWidth		= (Status("pxwidth")-1)/14; 
GfxSelectFont( "Tahoma", 8.5 ); 

GfxSetBkMode(1);

YOffset	= 25;
XOffset	= 10;//15;

width		= Status("pxwidth") - 4 * XOffset;
height		= Status("pxheight") - 2 * YOffset;

//--------------------------------------------------------------------------------
function PrintInCell( string, row, Col ) 
{
 Color =  ColorRGB( IIf( row == 0 || col == 0 || col == 13, 220, 255 ), 255,
							IIf( row % 2, 255, 220 ) );
 GfxSelectSolidBrush( color   );
 GfxRectangle( Col * CellWidth, 
                    row * CellHeight, (Col +1) * CellWidth+1, 
                    (row+1 ) * CellHeight+1); 
 GfxDrawText( string, Col * CellWidth+1, 
                    row * CellHeight+1, 
                    (Col+1) * CellWidth, (row+1) * CellHeight, 32+5 ); 
} 

//--------------------------------------------------------------------------------
function DrawBar( text, txtLabel, bar, numbars, y, Miny, Maxy )
{
 BarWidth = (Status("pxwidth") - 4 * XOffset )/( numbars+1 ); 
 BarHeight = Status("pxheight") - 2 * YOffset;
 relpos = ( y - Miny ) / (Maxy - Miny );

 xp = XOffset + ( bar+0.5 ) * BarWidth;
 yp = YOffset + BarHeight * ( 1-relpos );
 xe = XOffset + ( bar+1 ) * BarWidth;
 ye = YOffset + BarHeight * ( 1 - ( -miny )/( maxy - miny ) );
  
 if( y>0 )
 {
 GfxGradientRect( xp, yp, 
                  xe , ye,
                  ColorHSB(70, 255*relpos, 255), ColorHSB(70, 20, 255) ); 
 }
 else
 {
 GfxGradientRect( xp, ye, 
                  xe , yp,
                  ColorHSB(0, 20, 255), ColorHSB(0, 255*(1-relpos), 255) ); 
 }
 //draw bar labels along x-axis
 GfxSetTextColor(colorGreen);
 GfxTextOut( text, xp, ye );

 //draw bar% values
 if( y<0 )
 {
  GfxSetTextColor(colorRed);
  GfxTextOut( StrFormat("%.2f", y ), xp, yp );
 }
 else
 {
  GfxTextOut( StrFormat("%.2f", y ), xp, yp-YOffset/2 );
 }

 //draw X-label along the very bottom underneath boxed area
 if( txtLabel != "" )
 {
  GfxSelectFont( "Tahoma", 10, 580 );
  GfxSetTextColor(colorGreen);
  GfxTextOut( txtLabel, xp, XOffset + Height + YOffset);
  GfxSelectFont( "Tahoma", 8.5 );
 }
}    

//--------------------------------------------------------------------------------
function DrawLevels( Miny, Maxy )
{
  range = Maxy - Miny;

  grid = 100;
  if( range < 10 ) grid = 1;
  else 
  if( range < 20 ) grid = 2;
  else 
  if( range < 50 ) grid = 5;
  else 
  if( range < 100 ) grid = 10;
  else 
  if( range < 200 ) grid = 20;
  else 
  if( range < 500 ) grid = 50;

  _TRACE("grid = "+grid +" range "+range );
  
  GfxSelectPen( colorWhite, 1, 2 );
  //draws the grid lines
  for( y = grid * ceil( Miny/grid ); y <= grid * floor( Maxy/grid ); y += grid )
  {
   yp =  YOffset + Height * ( 1 -  ( y - Miny ) / (Maxy - Miny ) );

   GfxMoveTo( XOffset, yp );
   GfxLineTo( XOffset + width , yp );
   GfxTextOut( ""+ y, XOffset + 2 + width, yp );
  }
  //draws the box around the chart area
  GfxSelectPen( colorWhite, 1, 0 );
  GfxMoveTo( XOffset, YOffset );						//move to top/left
  GfxLineTo( XOffset + width, YOffset );				//line to top/right
  GfxLineTo( XOffset + width, YOffset + Height );	//line to bottom/right
  GfxLineTo( XOffset , YOffset + Height );			//line to bottom/left
  GfxLineTo( XOffset , YOffset );						//line to top/left
}

//--------------------------------------------------------------------------------
MonthNames = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";

//--------------------------------------------------------------------------------
function DisplayProfitTable()
{
 Header = "Year,"+MonthNames+",Yr Profit%";
 for( Col=0; (Colname = StrExtract( Header, Col ) ) != ""; Col++ )
 {
  PrintInCell( ColName, 0, Col );
 }

 Row = 1;
 for( y=FirstYr; y <= LastYr; y++ )
 {
  PrintInCell( StrFormat("%g", y ), Row, 0 ); 
  PrintInCell( StrFormat("%.1f%%", VarGet("ChgYear" + y ) ), Row, 13 ); 
  for( m = 1; m <= 12; m++ )
  { 
   Chg = VarGet("ChgMon" + y + "-" + m);
   if( Chg ) 
     PrintInCell( StrFormat("%.1f%%", Chg ), Row, m );
   else
     PrintInCell( "N/A", Row, m );
  }
  Row++;
 } 

 PrintInCell("Mon. Avg", Row, 0 );
 for( m=1; m <= 12; m++ )
 { 
  PrintInCell( StrFormat("%.1f%%",
					Nz( VarGet("SumChgMon"+m) / VarGet("SumMon"+m) ) ), Row, m );
 }
}

//--------------------------------------------------------------------------------
function DisplayYearlyProfits()
{
 Bar = 0;
 for( y=FirstYr; y <= LastYr; y++ )
 {
  Chg = VarGet("ChgYear" + y );
  DrawBar(""+y, "", Bar++, (LastYr - FirstYr +1), Chg, MinYrProfit, MaxYrProfit);
 }
 GfxSelectFont( "Tahoma", 12, 580 );
 GfxTextOut("Yearly % Profit chart", 10, 0 );
 GfxSelectFont( "Tahoma", 8.5 );

 DrawLevels( MinYrProfit, MaxYrProfit ); 
}

//--------------------------------------------------------------------------------
function DisplayMonthlyProfits(YrOff, NumYrs)
{
 Bar = 0;
 MoXLbl = "";
 dspStartYr	= Min(FirstYr + YrOff, LastYr);
 dspEndYr		= Min(FirstYr + YrOff + NumYrs - 1, LastYr);

 //determine monthly min/max for the displayed range
 MinMoProfit = MaxMoProfit = 0;
 for( y = dspStartYr; y <= dspEndYr; y++ )
 {
  for( m=1; m<=12; m++ )
  {
   Chg = VarGet("ChgMon" + y + "-" + m);

   if( abs( Nz(Chg) ) > 0 )
   { MaxMoProfit = Max( MaxMoProfit, Chg ); 
     MinMoProfit = Min( MinMoProfit, Chg ); }
  }
 }

 for( y = dspStartYr; y <= dspEndYr; y++ )
 {
  for( m=1; m<=12; m++ )
  {
   if( m==1 ) { YrXLbl = "" + y; } else { YrXLbl = ""; }

   MoXLbl = StrLeft( StrExtract(MonthNames, m-1 ), 3*(3/(NumYrs)) );
   TotMos	= 12*(dspEndYr - dspStartYr + 1);

   Chg = VarGet("ChgMon" + y + "-" + m);
   DrawBar( MoXLbl, YrXLbl, Bar++, TotMos, Chg, MinMoProfit , MaxMoProfit );
  }
 }
 GfxSelectFont( "Tahoma", 12, 580 );
 GfxSetTextColor( colorGreen );
 GfxTextOut("Monthly % Profit chart", 10, 0 );
 GfxSelectFont( "Tahoma", 8.5 );

 DrawLevels( MinMoProfit , MaxMoProfit ); 
}

//--------------------------------------------------------------------------------
function DisplayAvgMonthlyProfits()
{
 Bar = 0;
 
 MinAvgProf = MaxAvgProf = 0;
 for( y=1; y <= 12; y++ )
 {
  Chg = VarGet("SumChgMon" + y ) / VarGet("SumMon" + y );
  MinAvgProf = Min( MinAvgProf, Chg );
  MaxAvgProf = Max( MaxAvgProf, Chg );
 }

 for( y=1; y <= 12; y++ )
 {
  Chg = VarGet("SumChgMon" + y ) / VarGet("SumMon" + y );
  DrawBar(StrExtract(MonthNames, y-1), Bar++, 13, Chg, MinAvgProf, MaxAvgProf,"");
 }
 GfxSelectFont( "Tahoma", 12, 580 );
 GfxTextOut("Avgerage Monthly % Profit chart", 10, 0 );
 GfxSelectFont( "Tahoma", 8.5 );

 DrawLevels( MinAvgProf , MaxAvgProf ); 
}

///////////////////////////
// This function checks if currently selected symbol
// is portfolio equity
//////////////////////////
function CheckSymbol()
{
 if( Name() != "~~~EQUITY" )
 {
  GfxSelectFont( "Tahoma", 20 ); 
  GfxSetBkMode( 2 );
  GfxTextOut("For accurate results switch to ~~~EQUITY symbol", 10, 10 );
 }
}

////////////////////////////
// Main program - chart type switch
////////////////////////////
type = ParamList( "Chart Profit Type", "Table|Yearly|Monthly|Avg. Monthly", 1 );
dspStart	= Param( "Shift Display #Yrs later", 0, 0, 30, 1 );
dspBars	= Param( "NumberOfYrs displayed", 1, 1, 30, 1 );

switch( type )
{
 case "Table": 
         DisplayProfitTable();  
         break;
 case "Yearly": 
         DisplayYearlyProfits();
         break;
 case "Monthly": 
         DisplayMonthlyProfits(dspStart, dspBars);
         break;
 case "Avg. Monthly": 
         DisplayAvgMonthlyProfits();
         break;
}

CheckSymbol();






------------------------------------

**** IMPORTANT PLEASE READ ****
This group is for the discussion between users only.
This is *NOT* technical support channel.

TO GET TECHNICAL SUPPORT send an e-mail directly to 
SUPPORT {at} amibroker.com

TO SUBMIT SUGGESTIONS please use FEEDBACK CENTER at
http://www.amibroker.com/feedback/
(submissions sent via other channels won't be considered)

For NEW RELEASE ANNOUNCEMENTS and other news always check DEVLOG:
http://www.amibroker.com/devlog/

Yahoo! Groups Links

<*> To visit your group on the web, go to:
    http://groups.yahoo.com/group/amibroker/

<*> Your email settings:
    Individual Email | Traditional

<*> To change settings online go to:
    http://groups.yahoo.com/group/amibroker/join
    (Yahoo! ID required)

<*> To change settings via email:
    mailto:amibroker-digest@xxxxxxxxxxxxxxx 
    mailto:amibroker-fullfeatured@xxxxxxxxxxxxxxx

<*> To unsubscribe from this group, send an email to:
    amibroker-unsubscribe@xxxxxxxxxxxxxxx

<*> Your use of Yahoo! Groups is subject to:
    http://docs.yahoo.com/info/terms/