All perfect praise be to Allaah, The Lord of the Worlds. I testify that there is none worthy of worship except Allaah, and that Muhammad, sallallaahu ‘alayhi wa sallam, is His slave and Messenger.
First of all, you should repent to Allaah for being negligent and not inquiring about the nature of these companies before you actually bought stocks from them. In addition to this, if these stocks belong to companies which deal in a forbidden way, like Ribaa (interest or usury) or gambling, then you are only allowed to keep the capital money which you invested. Then, you are obliged to get rid of whatever remains thereafter (interest) by spending it in the general interest of Muslims, like helping the poor and destitute, building Islamic schools, digging wells and spending it in other beneficial areas, as Allaah Says (what means): {…But if you repent, you shall have your capital sums. Deal not unjustly (by asking more than your capital sums), and you shall not be dealt with unjustly (by receiving less than your capital sums).} [Quran 2:279]
However, if these stocks belong to companies whose dealings are permissible in principle but they may invest some of their money in Ribaa transactions - like is the case with some petroleum companies - then, from the price of these stocks, you are obliged to get rid of the amount of interest from these companies as we already mentioned, and whatever remains is lawful for you; as per the verse mentioned above.
Allaah Knows best.