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

Re: [amibroker] Re: Hedging with PositionScore?



PureBytes Links

Trading Reference Links

ok will do that later. For now here is the code,
 
rgds, Ed
 
 
 
// E.M.Pottasch, May 2007
// using as lead:

// http://www.amibroker.com/kb/2006/04/24/using-redundant-signals-for-entries/#more-28

am =
GetOption("AccountMargin"
);
posSize =
abs(-5
);
maxTot =
round((100/posSize) * (100 / am)); // maximum total positions

maxLong =
round((maxTot / 100) * 50
);
maxShort =
round((maxTot / 100) * 50
);

dateArr =
DateTime
();

SetOption("UseCustomBacktestProc", True
);

if( Status("action") == actionPortfolio
) {

   bo =
GetBacktesterObject
();
   bo.PreProcess();
// Initialize backtester

   
   
for(bar=0; bar<BarCount; bar++) {
           
           
// write output to AA window

            bo.RawTextOutput(
DateTimeToStr(dateArr[ bar ]) + "\n"
);
           bo.RawTextOutput(
"\t" + "Max Long: "
+ maxLong );
           bo.RawTextOutput(
"\t" + "Max Short: "
+ maxShort );
           
           
// loop through open positions and count open long and short positions

      cntLongOpenPositions =
0
;
      cntShortOpenPositions =
0
;
           
for
( openpos = bo.GetFirstOpenPos(); openpos; openpos = bo.GetNextOpenPos() ) {
                            
              
if
(openpos.IsLong() ) {
              
                 cntLongOpenPositions = cntLongOpenPositions +
1
;
                 
              }
else if
(!openpos.IsLong() ) {

            cntShortOpenPositions = cntShortOpenPositions +
1
;
            
              }
              
      }
           
           
           
// loop through signals and count the number of long and short signals

           sigStrEntry =
""
;
           sigStrExit =
""
;
           cntLongSignals =
0
;
           cntShortSignals =
0
;
           
for
( sig = bo.GetFirstSignal(bar); sig; sig=bo.GetNextSignal(bar)) {
                      
              
if (sig.IsLong() AND
sig.IsEntry() ) {
              
                 sigStrEntry = sigStrEntry + sig.Symbol +
"=Buy(" + sig.PosScore + "),"
;    
                 cntLongSignals = cntLongSignals +
1
;
                 
              }
else if (!sig.IsLong() AND
sig.IsEntry() ) {
                      
                      sigStrEntry = sigStrEntry + sig.Symbol +
"=Short(" + sig.PosScore + "),"
;
                 cntShortSignals = cntShortSignals +
1
;
                 
              }
else if (sig.IsExit() AND sig.Type == 2
) {
                      
                      sigStrExit = sigStrExit + sig.Symbol +
"=Sell,"
;
                      
              }
else if (sig.IsExit() AND sig.Type == 4
) {
                      
                      sigStrExit = sigStrExit + sig.Symbol +
"=Cover,"
;
                      
              }
           
           }

      bo.RawTextOutput(
"\t" + "Entry signals(score): "
+ sigStrEntry );
      bo.RawTextOutput(
"\t" + "Exit signals: "
+ sigStrExit );

           
// calculate maxNewLong

           
if
(cntLongOpenPositions + cntLongSignals > maxLong) {
           
              maxNewLong = maxLong - cntLongOpenPositions;
           
           }
else
{
           
              maxNewLong = cntLongSignals;
           
           }
           
            
// calculate maxNewShort

           
if
(cntShortOpenPositions + cntShortSignals > maxShort) {
           
              maxNewShort = maxShort - cntShortOpenPositions;
           
           }
else
{
           
              maxNewShort = cntShortSignals;
           
           }            
          
             
// trade entry

             cntl =
0
;
             cnts =
0
;
           bContinue =
True
;
           
for ( sig=bo.GetFirstSignal(bar); sig AND
bContinue; sig=bo.GetNextSignal(bar)) {
        
              
// enter new trade

              
if (cntl < maxNewLong AND sig.IsLong() AND sig.IsEntry() AND sig.Price != -1 AND IsNull( bo.FindOpenPos( sig.Symbol ) ) ) {
           
                 cntl = cntl +
1
;
                 
// Entry Signal

                 
if( bo.EnterTrade(bar, sig.symbol, sig.IsLong(), sig.Price,sig.PosSize) == 0 ) {
              
                     bContinue =
False
;
                 
                 }
              
              }
else if (cnts < maxNewShort AND !sig.IsLong() AND sig.IsEntry() AND sig.Price != -1 AND IsNull
( bo.FindOpenPos( sig.Symbol ) ) ) {
           
                 cnts = cnts +
1
;
                 
// Entry Signal

                 
if( bo.EnterTrade(bar, sig.symbol, sig.IsLong(), sig.Price,sig.PosSize) == 0 ) {
              
                     bContinue =
False
;
                 
                 }
                 
              }
           
           }
           
           
// trade exit

           
for
( sig=bo.GetFirstSignal(bar); sig; sig=bo.GetNextSignal(bar) ) {
        
              
// first handle exit signals

              
if (sig.IsExit() AND sig.Price != -1 ) {
           
                 
// Exit Signal

                 bo.ExitTrade(bar,sig.symbol,sig.Price);
              
              }
           
           }

           
// update stats after closing trades
           bo.UpdateStats(bar,
1); // MAE/MFE is updated when timeinbar is set to 1.
           bo.UpdateStats(bar,
2);
   
      
// loop through open positions and write to AA output window

      openPosition =
""
;
      cntLongOpenPositions =
0
;
      cntShortOpenPositions =
0
;
           
for
( openpos = bo.GetFirstOpenPos(); openpos; openpos = bo.GetNextOpenPos() ) {
                             
               
if
(openpos.IsLong() ) {
               
                  openPosition = openPosition + openpos.Symbol +
"(+" + openpos.Shares + "),"
;
                  cntLongOpenPositions = cntLongOpenPositions +
1
;
                  
               }
else if
(!openpos.IsLong() ) {
            
            openPosition = openPosition + openpos.Symbol +
"(-" + openpos.Shares + "),"
;
            cntShortOpenPositions = cntShortOpenPositions +
1
;
            
               }
               
      }
      totpos = cntLongOpenPositions + cntShortOpenPositions;
      bo.RawTextOutput(
"\t" + totpos + " Open Positions: "
+ openPosition );
      bo.RawTextOutput(
"\t" + "Long Positions: "
+ cntLongOpenPositions  );
      bo.RawTextOutput(
"\t" + "Short Positions: "
+ cntShortOpenPositions  );


   }
   
      bo.PostProcess();
// Finalize backtester

   
//bo.ListTrades();

   
// initialisations

   longTrades =
0
;
   shortTrades =
0
;
   
   
// store the DateTime() in a STRING array.

   fdatetime =
DateTime
();

   
// loop through trades   

   
for
( trade = bo.GetFirstTrade(); trade ; trade = bo.GetNextTrade() ) {
                                 
      
// find the entry datetime of the trade

      entry_datetime = trade.EntryDateTime;

      
// find the exit datetime of the trade

      exit_datetime = trade.ExitDateTime;
      
      
// locate the array index at entry

      index_entry =
IIf(entry_datetime == fdatetime, 1, 0
);
      
      
// locate the array index at exit

      index_exit =
IIf(exit_datetime == fdatetime, 1, 0
);
      
      
// indicate bars where the trade occurs

      index_trade =
Flip
(index_entry,index_exit);
      
      
// accumulate long and short trades

      
if
(trade.IsLong) {
               
         longTrades = longTrades + index_trade;

      }
else if
(!trade.IsLong) {
      
         shortTrades = shortTrades + index_trade;

      }      

            
   }    
   
   
   
// loop through open positions

   
for
( Openpos = bo.GetFirstOpenPos(); Openpos ; Openpos = bo.GetNextOpenPos() ) {
         
      
// find the entry datetime of the trade

      entry_datetime = Openpos.EntryDateTime;

      
// find the exit datetime of the trade

      exit_datetime = Openpos.ExitDateTime;
      
      
// locate the array index at entry

      index_entry =
IIf(entry_datetime == fdatetime, 1, 0
);
      
      
// locate the array index at exit

      index_exit =
IIf(exit_datetime == fdatetime, 1, 0
);
      
      
// indicate bars where the trade occurs

      index_trade =
Flip
(index_entry,index_exit);
      
      
// accumulate long and short trades

      
if
(Openpos.IsLong) {
      
         longTrades = longTrades + index_trade;

      }
else if
(!Openpos.IsLong) {
      
         shortTrades = shortTrades + index_trade;

      }      

            
   }    
   
   
AddToComposite(longTrades,"~longTrades","C",atcFlagDeleteValues | atcFlagEnableInPortfolio
);
   
AddToComposite(shortTrades,"~shortTrades","C",atcFlagDeleteValues | atcFlagEnableInPortfolio
);   
   
}
 
 
 
----- Original Message -----
From: vlanschot
Sent: Tuesday, May 08, 2007 1:46 PM
Subject: [amibroker] Re: Hedging with PositionScore?

Thanks Ed, but don't receive those. Could you perhaps load it up in
the files-section?

Thx,

PS

--- In amibroker@xxxxxxxxxps.com, "Edward Pottasch" <empottasch@...>
wrote:
>
> hi,
>
> I posted some code in the amibroker-beta group few days ago. It
should help with setting up re-balancing for portfolio type systems.
Have a look at that code (balancingBasic_cbi.afl) because I am only
now starting to understand this stuff.
>
> regards, Ed
>
>
>
>
>
> ----- Original Message -----
> From: vlanschot
> To: amibroker@xxxxxxxxxps.com
> Sent: Tuesday, May 08, 2007 11:35 AM
> Subject: [amibroker] Re: Hedging with PositionScore?
>
>
> Question for Ed (nl) who created the code below in 03/2005, or of
> course anybody else who cares to jump in.
>
> Is there any reason why I cannot seem to get, in the
GetFirstSignal-
> loop, the values from a VarSet which I defined previously in the
> GetFirstOpenPos-loop. Your code below shows that
the "cntlongopen"
> variable, defined in the 1st loop, can be called later in the 2nd
> loop.
>
> For all clarity, I need to make a link between stock-specific
> variables between these loops. In other words, I use VarSet
> ("Var1"+openpos.Symbol, var1) in order to retrieve it in the 2nd
loop
> via VarGet("Var1"+sig.Symbol). So far, this doesn't work.
>
> For context, and as mentioned in some of my previous mails, I'm
> trying to code a fairly simple (I thought) rebalancing strategy,
this
> time without the rotational trading bit. Any help appreciated.
>
> Thx,
>
> PS
>
> --- In amibroker@xxxxxxxxxps.com, "ed nl" <ed2000nl@> wrote:
> >
> > Herman,
> >
> > I expanded the code a little. Now you can set maxShort is well.
The
> nice thing about this is that you will only go full inside the
margin
> with mixed long and short positions and not just either long or
short,
> >
> > rgds, Ed
> >
> >
> >
> > /*
> >
> > Do not allow more than "maxLong" LONG positions OR "maxShort"
SHORT
> positions
> >
> > */
> >
> > SetCustomBacktestProc("");
> >
> > maxLong = 8;
> > maxShort = 9;
> >
> > if( Status("action") == actionPortfolio ) {
> >
> > bo = GetBacktesterObject();
> > bo.PreProcess();
> >
> > for( i = 0; i < BarCount; i++ ) {
> >
> >
> > cntLongOpen = 0;
> > cntShortOpen = 0;
> >
> > // scan through open positions and count the number of long
> positions
> > for( openpos = bo.GetFirstOpenPos(); openpos; openpos =
> bo.GetNextOpenPos() ) {
> >
> > // check for entry signal and long signal
> > if( openpos.IsOpen AND openpos.IsLong ) {
> >
> > cntLongOpen = cntLongOpen + 1;
> >
> > } else if ( openpos.IsOpen AND openpos.IsLong == 0) {
> >
> > cntShortOpen = cntShortOpen + 1;
> >
> > }
> >
> > }
> >
> >
> > // look at new signals and exclude Long signals if they
> exceed maxLong
> > for( sig = bo.GetFirstSignal(i); sig; sig = bo.GetNextSignal
> (i) ) {
> >
> > // check for entry signal and long signal
> > if( sig.IsEntry() AND sig.IsLong() ) {
> >
> > if( cntLongOpen >= maxLong ) {
> >
> > sig.PosSize = 0;
> >
> > } else {
> >
> > cntLongOpen = cntLongOpen + 1;
> >
> >
> > }
> >
> > // check for entry signal and short signal
> > } else if ( sig.IsEntry() AND sig.IsLong() == 0) {
> >
> > if( cntShortOpen >= maxShort ) {
> >
> > sig.PosSize = 0;
> >
> > } else {
> >
> > cntShortOpen = cntShortOpen + 1;
> >
> >
> > }
> >
> >
> > }
> >
> >
> > }
> >
> > bo.ProcessTradeSignals( i );
> > }
> >
> > bo.PostProcess();
> >
> > }
> > ----- Original Message -----
> > From: Herman van den Bergen
> > To: amibroker@xxxxxxxxxps.com
> > Sent: Tuesday, March 01, 2005 11:59 AM
> > Subject: RE: [amibroker] Hedging with PositionScore?
> >
> >
> > Thank you Ed, will try that!
> >
> > herman
> > -----Original Message-----
> > From: ed nl [mailto:ed2000nl@]
> > Sent: Tuesday, March 01, 2005 2:42 AM
> > To: amibroker@xxxxxxxxxps.com
> > Subject: Re: [amibroker] Hedging with PositionScore?
> >
> >
> > I think I answered my own question in case you are interested.
> It seems to work.
> >
> > rgds, Ed
> >
> >
> > /*
> >
> > Number of positions: do not allow more than "maxLong" LONG
> positions
> >
> > */
> >
> > SetCustomBacktestProc("");
> >
> > maxLong = 7;
> >
> > if( Status("action") == actionPortfolio ) {
> >
> > bo = GetBacktesterObject();
> > bo.PreProcess();
> >
> > for( i = 0; i < BarCount; i++ ) {
> >
> >
> > cntLongOpen = 0;
> >
> > // scan through open positions and count the number of
> long positions
> > for( openpos = bo.GetFirstOpenPos(); openpos; openpos =
> bo.GetNextOpenPos() ) {
> >
> > // check for entry signal and long signal
> > if( openpos.IsOpen AND openpos.IsLong ) {
> >
> > cntLongOpen = cntLongOpen + 1;
> >
> > }
> >
> > }
> >
> >
> > // look at new signals and exclude Long signals if they
> exceed maxLong
> > for( sig = bo.GetFirstSignal(i); sig; sig =
> bo.GetNextSignal(i) ) {
> >
> > // check for entry signal and long signal
> > if( sig.IsEntry() AND sig.IsLong() ) {
> >
> > if( cntLongOpen > maxLong ) {
> >
> > sig.PosSize = 0;
> >
> > } else {
> >
> > cntLongOpen = cntLongOpen + 1;
> >
> >
> > }
> >
> >
> > }
> >
> > }
> >
> > bo.ProcessTradeSignals( i );
> > }
> >
> > bo.PostProcess();
> >
> > }
>

__._,_.___

Please note that this group is for discussion between users only.

To get support from AmiBroker please send an e-mail directly to
SUPPORT {at} amibroker.com

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

For other support material please check also:
http://www.amibroker.com/support.html





SPONSORED LINKS
Investment management software Investment property software Investment software
Investment tracking software Return on investment software

Your email settings: Individual Email|Traditional
Change settings via the Web (Yahoo! ID required)
Change settings via email: Switch delivery to Daily Digest | Switch to Fully Featured
Visit Your Group | Yahoo! Groups Terms of Use | Unsubscribe

__,_._,___