COCO研究院

 找回密碼
 註冊
搜索
樓主: orangelam

[教學] 有關futures position size 一問

[複製鏈接]
發表於 14-7-19 13:09 | 顯示全部樓層
joshsmi 發表於 14-7-19 05:10
"I don't see why not use "equity()" in analysis or how nonsense it is."

Because Equity() function i ...

Hi,

The reason I use equity() in anaylsis is to see how position sizing/reinvestment works,
because equity() gives the equity result from backtest.

In real trading, I use IB Controller's function -- GetAccountValue() to get the total cash value.

For example, if I want to do fixed-dollar amout,

I just set my position size like...

Margindeposit=4000;
fixdollar=margindeposit*10;
ibc = GetTradingInterface("IB");
cash = ibc.GetAccountValue("TotalCashBalance");

SetPositionSize( cash/fixdollar, spsShares);

My purpose is to increase the position size by every 10 times of margin deposit for each share.
(the position size depends on my accout balance)

---
I wonder if equity() in analysis is wrong, then how can I do it right on both backtest and real trading.

thanks dude.
發表於 14-7-19 13:18 | 顯示全部樓層
joshsmi 發表於 14-7-19 05:16
kilroy wrote: " thanks but the pic is too small to see."

Just click the picture to maximize or down ...

Hi,

You may upload your pics directly to the article by clikcing on "paper clip".
2014-07-19_131218.png

2014-07-19_131748.png


發表於 14-7-20 01:12 | 顯示全部樓層
本帖最後由 joshsmi 於 14-7-20 01:13 編輯

kilroy wrote "My purpose is to increase the position size by every 10 times of margin deposit for each share.(the position size depends on my accout balance)"

For analysis and to vary position size use custom backtester!
Again don't use Equity() function there. It is simply wrong.


Example


SetOption( "MaxOpenPositions", 1 );
SetOption( "InitialEquity", 40000 );
SetOption( "FuturesMode", 1 );
SetPositionSize( 30, spsPercentOfEquity );
SetOption( "UsePrevBarEquityForPosSizing", 1 );

// 2nd Phase - custom backtest
SetOption( "UseCustomBacktestProc", True );
if( Status("action") == actionPortfolio )
{
    // retrieve the interface to portfolio backtester
    bo = GetBacktesterObject();
   
    bo.PreProcess();

    for( bar = 0; bar < BarCount; bar++ )
    {
         // this retrieves current value of portfolio-level equity
         CurrentPortfolioEquity = bo.Equity;

         // this for loop iterates through all trade signals and adjust pos size
         for( sig = bo.GetFirstSignal( bar ); sig; sig = bo.GetNextSignal( bar ) )
         {
            // when our equity grows to $50000 decrease pos size to 20%
            if( CurrentPortfolioEquity > 50000 ) sig.PosSize = -20;
            // if above $60K then decrease to 15%
            if( CurrentPortfolioEquity > 60000 ) sig.PosSize = -15;
            // if above $80K then decrease to 10%
            if( CurrentPortfolioEquity > 80000 ) sig.PosSize = -10;
         }

         bo.ProcessTradeSignals( bar );
    }
   
    bo.PostProcess();
}


// 1st Phase - standard backtest

Buy = ...;
Sell = ...;
Short = Cover = 0;


I have re-uploaded picture of last page again. I can read it. If you can't then you need new glasses. :-)
Untitled.png

評分

參與人數 1金錢 +2 收起 理由
orangelam + 2 按一個讚

查看全部評分

發表於 14-7-20 01:18 | 顯示全部樓層
If you wanna output equity column in backtest result list then again you have to use custom backtest interface.


// start CBT ###############################################################################
SetCustomBacktestProc( "" );
if ( Status( "action" ) == actionPortfolio )
{
    bo = GetBacktesterObject();
    bo.Backtest( 1 );
   
    eq = bo.EquityArray;
   
   // Output Equity at entry column in backtest result list
    for ( trade = bo.GetFirstTrade(); trade; trade = bo.GetNextTrade() )
    {
        EquityAtExit = Lookup( eq, trade.ExitDateTime );
        trade.AddCustomMetric( "Equity at exit", EquityAtExit );
    }
   
    // iterate through open trades and add same info
    for( pos = bo.GetFirstOpenPos(); pos; pos = bo.GetNextOpenPos() )
    {
        EquityAtExit = Lookup( eq, pos.ExitDateTime );
        pos.AddCustomMetric( "Equity at exit", EquityAtExit );
    }
   
    bo.ListTrades();
}

評分

參與人數 1金錢 +2 收起 理由
orangelam + 2 感謝分享

查看全部評分

發表於 14-7-20 01:30 | 顯示全部樓層
 樓主| 發表於 14-7-20 03:16 | 顯示全部樓層
joshsmi, thank you very much!!!! i believe you are amibroker expert!
i reproduced your code in the pic u attached. i found that the shares still weird. so that i can confirm that, there must be my setting problem instead of coding.

after checking my setting, i found that in

setting->portfolio
limit trade size as % of entry bar volumn=10

this is the reason why my backtest didn't use all equity to invest. after setting it to zero (zero means no limit), the results is fine.

really appreciated for your help. i am new in amibroker and i am now accumulating my amibroker experience/knowledge.(your custom backtest interface eg equity at exit is also really helpful).

if lacking of your help and discussing here, i might not realize that the problem is in setting instead of coding.

Thank you very much joshsmi!



  


 樓主| 發表於 14-7-20 03:42 | 顯示全部樓層
by the way, after searching the internet, i still can't find the afl for setting
limit trade size as % of entry bar volumn
as i don't want this mistake happen the second time, i am going to type it by afl code.
do you know is there any afl code for setting it in the program?


發表於 14-7-20 05:08 | 顯示全部樓層
orangelam 發表於 14-7-20 03:42
by the way, after searching the internet, i still can't find the afl for setting
limit trade size as ...

Just save as project file. Project files have .apx extension and they save AFL and all analysis settings!
If you open analysis and have all set and done then go to File>Save... or File>Save as...
If you  wanna open project then it is just File > open and all will be re-established as it was set when project was saved. You can also automate the run of analysis via OLE Automation Object Model.
Just go to help file of AB


 樓主| 發表於 14-7-23 19:20 | 顯示全部樓層
有一個關於iterate across open positions 的問題想請教一下:

// start CBT
SetCustomBacktestProc( "" );
if ( Status( "action" ) == actionPortfolio )
{
    bo = GetBacktesterObject(); //get access to backtester object
    bo.Backtest(1);        // run default backtest procedure         
    eq = bo.EquityArray;

    st = bo.GetPerformanceStats(0); // get stats for all trades
   
   // Output Equity at entry column in backtest result list
    for ( trade = bo.GetFirstTrade(); trade; trade = bo.GetNextTrade() )
    {
        EquityAtExit = Lookup( eq, trade.ExitDateTime );
        trade.AddCustomMetric( "Equity at exit_trade", EquityAtExit );
    }

   // iterate through closed trades first
   for( trade = bo.GetFirstTrade(); trade; trade = bo.GetNextTrade() )
   {
      // here we sum up profit per $100 invested
       //SumProfitPer100Inv = SumProfitPer100Inv + trade.GetPercentProfit();
       //NumTrades++;
                trade.AddCustomMetric("Percent_profit_close",trade.GetPercentProfit() );
   }

   // iterate through eventually still open positions
   for( trade = bo.GetFirstOpenPos(); trade; trade = bo.GetNextOpenPos() )
   {
       //SumProfitPer100Inv = SumProfitPer100Inv + trade.GetPercentProfit();
       //NumTrades++;
trade.AddCustomMetric("Percent_profit_open",trade.GetPercentProfit() );
   }

    bo.ListTrades();
}   

附件是backtest result, 在最後兩段codes其實我預期result 會有兩個columns , 一個是 Percent_profit_close, 另一個是
Percent_profit_open
而Percent_profit_open 道理上全部都是零, 而最後一個row 才有數值(因為只有最後一行是open position)

但結果很奇怪, 不知道為什麼沒有Percent_profit_open的column, 而且Equity at exit_trade的最後一個row是3.33 , 一個很奇怪的數, 我估計這個值應該是Percent_profit_open吧?

應該是iterate 的logic 出了問題導致overlap了, 前輩可以提點一下嗎?

thanks.

question.jpg
發表於 14-7-23 22:19 | 顯示全部樓層
謝謝您的分享,感謝您~~~~~~~
發表於 14-7-23 22:20 | 顯示全部樓層
謝謝您的分享,感謝您~~~~~~~
發表於 14-7-23 23:28 | 顯示全部樓層
本帖最後由 joshsmi 於 14-7-23 23:44 編輯
orangelam 發表於 14-7-23 19:20
有一個關於iterate across open positions 的問題想請教一下:

// start CBT

It is strange because you are doing it wrong again

SetOption( "ExtraColumnsLocation", 12 );// defines location of CBT columns in AA

period = 20; // number of averaging periods
m = MA( Close, period ); // simple moving average
Buy = Cross( Close, m ); // buy when close crosses ABOVE moving average
Sell = Cross( m, Close ); // sell when closes crosses BELOW moving average
Short = Cover = 0;

BuyPrice = SellPrice = Close;

// start CBT
SetCustomBacktestProc( "" );
if ( Status( "action" ) == actionPortfolio )
{
   bo = GetBacktesterObject(); //get access to backtester object
   bo.Backtest( 1 );      // run default backtest procedure

   eq = bo.EquityArray;// close equity

   //st = bo.GetPerformanceStats( 0 ); // get stats for all trades

   //NumTrades = 0;
   //SumProfitPer100Inv = 0;

   // iterate through closed trades first
   for ( trade = bo.GetFirstTrade(); trade; trade = bo.GetNextTrade() )
   {
      // Output Equity at entry column in backtest result list
      EquityAtExit = Lookup( eq, trade.ExitDateTime );
      trade.AddCustomMetric( "Equity@Exit", EquityAtExit );

      percprofit = trade.GetPercentProfit();

      // here we sum up profit per $100 invested
      //SumProfitPer100Inv += percprofit;
      //NumTrades++;

      trade.AddCustomMetric( "%Profit", percprofit );
   }

   // iterate through eventually still open positions
   for ( pos = bo.GetFirstOpenPos(); pos; pos = bo.GetNextOpenPos() )
   {
      // Output Equity at entry column in backtest result list
      EquityAtExit = Lookup( eq, pos.ExitDateTime );
      pos.AddCustomMetric( "Equity@Exit", EquityAtExit );

      percprofit = pos.GetPercentProfit();

      //SumProfitPer100Inv += percprofit;
      //NumTrades++;

      pos.AddCustomMetric( "%Profit", percprofit );
   }

   bo.ListTrades();
}

發表於 14-7-23 23:39 | 顯示全部樓層
本帖最後由 joshsmi 於 14-7-23 23:43 編輯
joshsmi 發表於 14-7-23 23:28
It is strange because you are doing it wrong again

SetOption( "ExtraColumnsLocation", 12 );// def ...

SetOption( "ExtraColumnsLocation", 12 );// defines location of CBT columns in AA

period = 20; // number of averaging periods
m = MA( Close, period ); // simple moving average
Buy = Cross( Close, m ); // buy when close crosses ABOVE moving average
Sell = Cross( m, Close ); // sell when closes crosses BELOW moving average
Short = Cover = 0;

BuyPrice = SellPrice = Close;

// start CBT
SetCustomBacktestProc( "" );
if ( Status( "action" ) == actionPortfolio )
{
   bo = GetBacktesterObject(); //get access to backtester object
   bo.Backtest( 1 );      // run default backtest procedure

   //eq = bo.EquityArray;// close equity

   st = bo.GetPerformanceStats( 0 ); // get stats for all trades
   initialcap = st.GetValue( "InitialCapital" );
   
   //NumTrades = 0;
   //SumProfitPer100Inv = 0;
   SumProf = 0;
   
   // iterate through closed trades first
   for ( trade = bo.GetFirstTrade(); trade; trade = bo.GetNextTrade() )
   {
      // Output Equity at entry column in backtest result list
      SumProf += trade.GetProfit();// cum. profit
        EquityAtExit = initialcap + SumProf;
      trade.AddCustomMetric( "Equity@Exit", EquityAtExit );

      percprofit = trade.GetPercentProfit();

      // here we sum up profit per $100 invested
      //SumProfitPer100Inv += percprofit;
      //NumTrades++;

      trade.AddCustomMetric( "%Profit", percprofit );
   }

    // iterate through eventually still open positions
   for ( pos = bo.GetFirstOpenPos(); pos; pos = bo.GetNextOpenPos() )
   {
      // Output Equity at entry column in backtest result list
      SumProf += pos.GetProfit();// cum. profit
        EquityAtExit = initialcap + SumProf;
      pos.AddCustomMetric( "Equity@Exit", EquityAtExit );

      percprofit = pos.GetPercentProfit();

      //SumProfitPer100Inv += percprofit;
      //NumTrades++;

      pos.AddCustomMetric( "%Profit", percprofit );
   }

   bo.ListTrades();
}
 樓主| 發表於 14-7-24 01:23 | 顯示全部樓層
thanks, but i also found a curious case. would you please try below:

Case 1:
just hide/not execute the first "for" loop, expected result is, there will be two columns "Equity@Exit" and "%Profit" created, with all zero value except the last row. indeed, this is the reasonable result as only the last row is open position.

Case2:
not execute "trade.AddCustomMetric( "%Profit", percprofit );" in the first for loop. the expected result is,

"Equity@Exit", filled whole column
"%Profit", only the last row have value

but, you will find that, the whole %profit column disappeared.

do you know why? i am quite concerned about this.

thanks!
發表於 14-7-24 02:25 | 顯示全部樓層
本帖最後由 joshsmi 於 14-7-24 02:30 編輯

You don't have any clue at all. Keep away from advanced programming and learn the basics first.

First of all if you comment/remove the whole first loop of my code then there will be no columns at all. If you comment/remove Addcustommetric there will be no column of that metric at all also.

Secondly it makes no sense to hide first loop. It is simply an idiotic thought to remove iteration through closed trades. You can not have just output of open trade. If you don't want any output then don't code any custom backtest metric at all. Instead do something else that does not have anything to do with programming like going to the beach.

您需要登錄後才可以回帖 登錄 | 註冊

本版積分規則

手機版|Archiver|站長信箱|廣告洽詢|COCO研究院

GMT+8, 24-12-23 09:49

Powered by Discuz! X3.4

Copyright © 2001-2023, Tencent Cloud.

快速回復 返回頂部 返回列表
理財討論網站 |