Please ask all Zorro Trader questions in the Zorro Trader forum. You need to sign up first.
Quote from Jordie S on April 1, 2024, 4:13 amHello Fellow Quants,
I'm running into a challenge with my backtesting and could use some guidance.
I'm trying to factor in capital gain tax, but every time I try to adjust the balance or equity, it seems to maintain its own calculated value, making it tough to integrate tax calculations.
Has anyone dealt with this before or knows a workaround? Any help would be greatly appreciated!
--------------------- CODE -----------------------
SellPrice = Balance;Profit = SellPrice - BuyPrice;// Calculate capital gain taxvar TaxRate = 0.21; // 21% tax ratevar CapitalGainTax = Profit * TaxRate;// Subtract capital gain tax from profitif((Profit > 0) and (position > 0)){string Date = strdate("%Y-%m-%d", 0);// Print trade information including dateprintf("\nDate: %s -- Profit per trade: %.2f, Capital Gain Tax: %.2f, Profit after Tax: %.2f\n", Date, Profit, CapitalGainTax, Profit - CapitalGainTax);// Deduct capital gain tax from account balanceBalance -= CapitalGainTax;}Many thanks.Wishing you all the heath and wealth,Jordie
Hello Fellow Quants,
I'm running into a challenge with my backtesting and could use some guidance.
I'm trying to factor in capital gain tax, but every time I try to adjust the balance or equity, it seems to maintain its own calculated value, making it tough to integrate tax calculations.
Has anyone dealt with this before or knows a workaround? Any help would be greatly appreciated!
--------------------- CODE -----------------------
Quote from Algo Mike on April 3, 2024, 9:27 pmHi Jeordi, welcome to the forum! The code you posted would not run at all, as it lacks the run() function and the trading logic. Is this the complete code you are trying to execute, or is there more to it? Also, I find it odd to calculate the capital gains tax for every trade. Unfortunately, you will have losing trades as well. Would you make the capital gains tax negative for those trades? Wouldn't it be easier if you would calculate the cost basis and profit or loss per trade, and the capital gains tax at the end of the tax year? In the US, we pay our taxes only once a year (it's April, so I just did). Is it different in your jurisdiction?
Now, if this is just a programming exercise, please disregard my two cents above. I will try running your code with a vanilla strategy tomorrow and see what I get.
Hi Jeordi, welcome to the forum! The code you posted would not run at all, as it lacks the run() function and the trading logic. Is this the complete code you are trying to execute, or is there more to it? Also, I find it odd to calculate the capital gains tax for every trade. Unfortunately, you will have losing trades as well. Would you make the capital gains tax negative for those trades? Wouldn't it be easier if you would calculate the cost basis and profit or loss per trade, and the capital gains tax at the end of the tax year? In the US, we pay our taxes only once a year (it's April, so I just did). Is it different in your jurisdiction?
Now, if this is just a programming exercise, please disregard my two cents above. I will try running your code with a vanilla strategy tomorrow and see what I get.
Quote from Algo Mike on April 4, 2024, 6:58 pmHi Jeordy, here's my version of what I think you wanted to do. I used internal Zorro variables for the most part. For example, TradeProfit. While holding a position, Zorro knows "automagically" if there is a profit or a loss, so there's no need to calculate this manually. Same with Balance, but you need to initialize the Capital variable, and Balance will be calculated automatically by Zorro. I subtracted the capital gains tax from the Balance as per your code, but I am still not sure why you would want to do that. Anyway, here's the code. It runs fine on my machine.
function run(){set(PLOTNOW);MaxLong = MaxShort = 1;BarPeriod = 1440;//Set initial capital so that Balance can be calculated automaticallyCapital = 10000;// Set capital gain tax rate at 21%var TaxRate = 0.21;// Get price and moving averagevars price = series(priceClose());vars sma = series(SMA(price, 20));// Enter a long trade at cross overif(crossOver(price, sma)) enterLong();//Exit the long trade at cross under and print desired parameters at each trade exitif(crossUnder(price, sma)) {exitLong();// Calculate capital gain taxvar CapitalGainTax = TradeProfit * TaxRate;// Get current date in desired formatstring Date = strdate("%Y-%m-%d", 0);// Print trade information including dateprintf("\nDate: %s -- Profit per trade: %.2f, Capital Gain Tax: %.2f, Profit after Tax: %.2f\n", Date, TradeProfit, CapitalGainTax, TradeProfit - CapitalGainTax);// Deduct capital gain tax from account balanceBalance -= CapitalGainTax;// Print new balanceprintf("Balance: %.2f\n", Balance);}plot("SMA", sma, LINE, BLUE);}I hope this helps. Please let me know if you have any questions.
Hi Jeordy, here's my version of what I think you wanted to do. I used internal Zorro variables for the most part. For example, TradeProfit. While holding a position, Zorro knows "automagically" if there is a profit or a loss, so there's no need to calculate this manually. Same with Balance, but you need to initialize the Capital variable, and Balance will be calculated automatically by Zorro. I subtracted the capital gains tax from the Balance as per your code, but I am still not sure why you would want to do that. Anyway, here's the code. It runs fine on my machine.
Quote from Jordie S on April 6, 2024, 2:42 pmHello Algo Mike, Thanks for the welcome,
I much appreciate your replay, no I didn't post the whole code, only the part of the calculation.
I will backtest your provided code tomorrow and come back to you. 🙂
However my code was also running, but when checking the balance in the log, I could see that in the new run cycle, my balance wouldn't be Balance -= CapitalGainTax but I would just stay at its own calculated Balance. That is the reason for the post ;-).
I'm based in Spain, and my understanding of the law here is that I would need to pay capital gain tax only over my winning trades. (Need to double-check this)
The losing trades don't offset any profit, so I wanted to lower my balance after each trade, to keep the capital aside for the taxes, does that make sense?
Many thanks.Wishing you all the health and wealth,Jordie
Hello Algo Mike, Thanks for the welcome,
I much appreciate your replay, no I didn't post the whole code, only the part of the calculation.
I will backtest your provided code tomorrow and come back to you. 🙂
However my code was also running, but when checking the balance in the log, I could see that in the new run cycle, my balance wouldn't be Balance -= CapitalGainTax but I would just stay at its own calculated Balance. That is the reason for the post ;-).
I'm based in Spain, and my understanding of the law here is that I would need to pay capital gain tax only over my winning trades. (Need to double-check this)
The losing trades don't offset any profit, so I wanted to lower my balance after each trade, to keep the capital aside for the taxes, does that make sense?
Quote from Jordie S on April 7, 2024, 8:24 amHi Algo Mike,
As promised I ran the logic again but I'm getting the same result.
I attached a screenshot of the log file with some explanation.
I also copied more of the code.
Best Regards,
Jordie
//------- CODE --------
var position = 0;
function run()
{
set(LOGFILE,PLOTNOW);
BarPeriod = 1440;
StartDate = 20100101;
EndDate = 20220601;asset("SPY");
Capital = 10000;var TaxRate = 0.21; // 21% tax rate
MaxLong = MaxShort = 1;vars Prices = series(priceClose());
//-------------------------------
Logic Containing algo
//-------------------------------
if(//---Trigger for long entry---// ){
if(position < 1){
printf("\nCapital before trade = %.2f\n", Capital);
printf("Equity before trade = %.2f\n", Equity);
printf("Balance before trade = %.2f\n", Balance);var qty = floor(Balance/ priceClose());
enterLong(qty);
position = 1;
}
} else if(//---Trigger for trade exit---// and position > 0) {
exitLong();// Calculate capital gain tax
var CapitalGainTax = TradeProfit * TaxRate;// Subtract capital gain tax from profit
if((TradeProfit > 0) and (position > 0)){string Date = strdate("%Y-%m-%d", 0);
// Print trade information including date
printf("\nDate: %s -- Profit per trade: %.2f, Capital Gain Tax: %.2f, Profit after Tax: %.2f\n", Date, TradeProfit, CapitalGainTax, TradeProfit - CapitalGainTax);// Deduct capital gain tax from account balance
Balance -= CapitalGainTax;// Print new balance
printf("Balance: %.2f\n", Balance);}
position = 0;
}
}
Hi Algo Mike,
As promised I ran the logic again but I'm getting the same result.
I attached a screenshot of the log file with some explanation.
I also copied more of the code.
Best Regards,
Jordie
//------- CODE --------
var position = 0;
function run()
{
set(LOGFILE,PLOTNOW);
BarPeriod = 1440;
StartDate = 20100101;
EndDate = 20220601;
asset("SPY");
Capital = 10000;
var TaxRate = 0.21; // 21% tax rate
MaxLong = MaxShort = 1;
vars Prices = series(priceClose());
//-------------------------------
Logic Containing algo
//-------------------------------
if(//---Trigger for long entry---// ){
if(position < 1){
printf("\nCapital before trade = %.2f\n", Capital);
printf("Equity before trade = %.2f\n", Equity);
printf("Balance before trade = %.2f\n", Balance);
var qty = floor(Balance/ priceClose());
enterLong(qty);
position = 1;
}
} else if(//---Trigger for trade exit---// and position > 0) {
exitLong();
// Calculate capital gain tax
var CapitalGainTax = TradeProfit * TaxRate;
// Subtract capital gain tax from profit
if((TradeProfit > 0) and (position > 0)){
string Date = strdate("%Y-%m-%d", 0);
// Print trade information including date
printf("\nDate: %s -- Profit per trade: %.2f, Capital Gain Tax: %.2f, Profit after Tax: %.2f\n", Date, TradeProfit, CapitalGainTax, TradeProfit - CapitalGainTax);
// Deduct capital gain tax from account balance
Balance -= CapitalGainTax;
// Print new balance
printf("Balance: %.2f\n", Balance);
}
position = 0;
}
}
Quote from Algo Mike on April 7, 2024, 10:59 pmHi Jeordie,
In the US, our capital gain tax rules are described reasonably well in this IRS document, which may be of interest to all our members: https://www.irs.gov/taxtopics/tc409
As you can see in this document, you can use some of your losses to decrease your taxable income, and if you hit the IRS limit on that, you can carry them over for the future. This is somehow the spirit of the code I posted for you. Profit capital gain tax is positive, loss capital gain tax, negative. The losses are not really lost (in a tax sense), as they do decrease your income, and your taxes as such (either now, or in the future). It may be different in Spain, of course, so if you talk to your accountant about this, please do share.
I will try to figure out what's going on with your code and circle back here.
Happy trading!
Hi Jeordie,
In the US, our capital gain tax rules are described reasonably well in this IRS document, which may be of interest to all our members: https://www.irs.gov/taxtopics/tc409
As you can see in this document, you can use some of your losses to decrease your taxable income, and if you hit the IRS limit on that, you can carry them over for the future. This is somehow the spirit of the code I posted for you. Profit capital gain tax is positive, loss capital gain tax, negative. The losses are not really lost (in a tax sense), as they do decrease your income, and your taxes as such (either now, or in the future). It may be different in Spain, of course, so if you talk to your accountant about this, please do share.
I will try to figure out what's going on with your code and circle back here.
Happy trading!