May Allah bless you.
If these shares are from two different companies, then it is best not to offset your losses against the amount that need to be purified. I don’t think it is permissible to do this, even though mathematically the result is the same.
How about if the money was used to pay off the interest part on a loan for example
I have to pay of £500 in interest on a loan and I made 50 gain on a non shariah can I get rid of this by using that to pay the interest on the loan? So now I only have to pay £450 in interest?
Only when the interest payment towards the same creditor/owner, For example, let’s say you received interest from HSBC, you can use this interest to pay the interest you owe them for unarranged overdraft. Because the payment you received from initially does not belong to you from a shariah perspective. So in reality you are just returning their money via another payment arrangement.
Otherwise, you cannot use the haram revenue to pay off another haram payment due to a different company.