When a stock becomes non-compliant after investing

Assalamu Alaikum Wa Rahmatullahi Wa Barakatuh,

If I have invested in a stock which was shariah compliant at the time of investing, but when I go to sell I find out it’s non-compliant, am I able to keep the profits ? Or do I have to get rid of them all?

I would imagine it wouldn’t be possible to find out when the company became non-compliant.

JazakAllah Khair

Valon