Explorer to count total trades and yields

Hello:

I am trying to program an Explore code that buys on the first trading day of the month and sells on the last. Calculate and display the performance per trade and the average performance of each of the trades. To do that I calculate the variable “Rendimiento”, then the variable “AccumulatedReturn” to accumulate all the profits/losses in % and add them to me, to finally apply a counter of total trades “TradeCountArray” to divide the two previous variables and thus obtain the average profit/loss of the trades. The problem is that I can't get the trade counter to work. Can someone help me?

Thanks

mes = Month(); 
new_mes = mes != Ref(mes, -1); // First trading day of the month
old_mes = mes != Ref(mes, 1);  // Last trading day of the month
elelegido = Param("Month", 12, 1, 12, 1); // Select the month

Buy = new_mes AND mes == elelegido;  // Buy on the first trading day of the chosen month
Sell = old_mes AND mes == elelegido; // Sell on the last trading day of the chosen month
Short = Cover = 0;

BuyPrice = ValueWhen(Buy, Open);   // Entry price
SellPrice = ValueWhen(Sell, Close); // Exit price

// Calculate return for the trade
Rendimiento = IIf(Sell AND BuyPrice != 0, (SellPrice - BuyPrice) / BuyPrice * 100, 0);

AccumulatedReturn = Sum(Rendimiento, 1);

// Initial variables
TradeCount = 0;
IsTradeOpen = False;
TradeCounterArray = Null;

// Loop to go through all the bars on the chart
for (i = 0; i < BarCount; i++)
{
    // Trade opening condition (you can adjust this condition according to your logic)
    if (Buy[i] && !IsTradeOpen)
    {
        TradeCount++;  // Increment the trade counter when a new trade opens
        IsTradeOpen = True;  // Mark that a trade is open
    }

    // Trade closing condition
    if (Sell[i] && IsTradeOpen)
    {
        IsTradeOpen = False;  // Mark that the trade has been closed
    }

    // Store the value of the trade counter for each bar
    TradeCounterArray[i] = TradeCount;
}

// Calculate average return
AverageReturn = IIf(TradeCounterArray > 0, AccumulatedReturn / TradeCounterArray, 0);

// Show only on selling days (one line per trade)
Filter = Sell;

// Add columns with results
AddColumn(TradeCounterArray, "TradeCount", 1.0);
AddColumn(BuyPrice, "Entry Price", 1.2, colorDefault, colorDefault);
AddColumn(SellPrice, "Exit Price", 1.2, colorDefault, colorDefault);
AddColumn(Rendimiento, "Return %", 1.2, colorDefault, colorDefault);
AddColumn(AverageReturn, "Average Return %", 1.2, colorDefault, colorDefault);

All of the metrics you described are reported automatically by AmiBroker when you run a backtest. Is there a reason that you want to calculate them yourself as part of an Exploration?

1 Like

Yes, to run Explore on a Watchlist and see over a range of dates, which tickers in the list give the best performance on those dates, you know, seasonality. I'd really like to do that on specific dates, but so far I've only figured out how to do it from the first trading day of the month to the last.

I have already solved the date issue with this code snippet:

// VARIABLES
NewMonth=Month()!=ref(Month(),-1);
BuyDay = Param("Día Compra",12,1,31,1);
BuyMonth = Param("Mes Compra",10,1,12,1);
SellDay = Param("Día Venta",10,1,31,1);
SellMonth = Param("Mes Venta",10,1,12,1);

// CONDICIONES
compra = Day() >= BuyDay  AND BuyMonth == Month();
venta = Day() >= SellDay AND SellMonth == Month();

//mes = Month(); 
//new_mes = mes != Ref(mes, -1); // First trading day of the month
//old_mes = mes != Ref(mes, 1);  // Last trading day of the month
//elelegido = Param("Month", 12, 1, 12, 1); // Select the month

//Buy = new_mes AND mes == elelegido;  // Buy on the first trading day of the chosen month
Buy = compra;
//Sell = old_mes AND mes == elelegido; // Sell on the last trading day of the chosen month
Sell = venta;
Short = Cover = 0;

I can then choose the day and month I want using the Parameters tool.

Try this revised version instead:

mes = Month(); 
new_mes = mes != Ref(mes, -1); // First trading day of the month
old_mes = mes != Ref(mes, 1);  // Last trading day of the month
elelegido = Param("Month", 12, 1, 12, 1); // Select the month
inRange = Status("BarInRange");

Buy = new_mes AND mes == elelegido AND inRange;  // Buy on the first trading day of the chosen month
Sell = old_mes AND mes == elelegido  AND inRange; // Sell on the last trading day of the chosen month
Short = Cover = 0;

BuyPrice = ValueWhen(Buy, Open);   // Entry price
SellPrice = ValueWhen(Sell, Close); // Exit price

// Calculate return for the trade
Rendimiento = IIf(Sell AND BuyPrice != 0, (SellPrice - BuyPrice) / BuyPrice * 100, 0);

//AccumulatedReturn = Sum(Rendimiento, 1);
AccumulatedReturn = Cum(Rendimiento);

// Loop removed
TradeCounterArray = Cum(Buy);

// Calculate average return
AverageReturn = IIf(TradeCounterArray > 0, AccumulatedReturn / TradeCounterArray, 0);

// Show only on selling days (one line per trade)
Filter = Sell;

// Add columns with results
AddColumn(TradeCounterArray, "TradeCount", 1.0);
AddColumn(BuyPrice, "Entry Price", 1.2, colorDefault, colorDefault);
AddColumn(SellPrice, "Exit Price", 1.2, colorDefault, colorDefault);
AddColumn(Rendimiento, "Return %", 1.2, colorDefault, colorDefault);
AddColumn(AverageReturn, "Average Return %", 1.2, colorDefault, colorDefault);

Trading on a specific date is easy. Here's the general idea for a trade that enters at the beginning of January 2020 and exits at the end of that month. You can make this more usable using ParamDate for the start and end dates. Also note that in this example, the dates must be actual trading days

startDateNum = 1200102;
endDateNum = 1200131;

dn = DateNum();
Buy = startDateNum == dn;
Sell = endDateNum == dn;
1 Like

With your solution you will end up with a lot of extra Buy and Sell signals, so you may want to use ExRem() to eliminate them.

It works, very interesting the Status function, I didn't know it. Studying it I have seen that even adding as Filter:

Filter = Status("lastbarinrange");

I get the Explore to show only the last trade per ticker and show me the AverageReturn of the whole series of trades for each ticker in the Watchlist, exactly what I was looking for.

Indeed, with my solution to choose a certain date range, I had to add ExRem to avoid repeating signals.

Thanks

1 Like

You also just select 1-bar range from the Analysis Window UI.
If you select 1 recent quotation it will also display just last bar info.

1 Like