Many Muslims invest in stocks (stock market). The argument is that, since there are risks where one can lose or gain, that it constitutes doing business so long as one does not buy stocks on the margin or be involved in direct interest bearing investments. Please explain the limits of investing in the stock market or if it is forbidden and why?

Praise be to Allaah.
There is nothing wrong with selling or buying shares if they are shares in
permissible companies. If it is an agricultural company, for example, which
produces permissible agricultural products, then it is permissible to buy and
sell shares in it; the same applies to companies which deal in real estate,
manufacturing, etc.
It is permissible to buy the shares of other people and pay them the price
immediately, so that one will not be selling a loan for a loan.
Excluded from this are companies which deal in haraam things, such as selling
alcohol, tobacco and music tapes. It is not permitted to have shares in these
companies, or to buy these shares. If the company openly deals in ribaa (usury,
interest), then it is not permissible to deal with it. but if a manufacturing,
agricultural or business company is compelled to deposit its money with the bank
in order to protect it from being lost or stolen, then it is permissible because
of that necessity for the owners of the company to get rid of the interest which
the bank gives them on their deposits. Companies should also avoid using
riba-based loans in order to set up production lines and factories; that should
be achieved by using cash and the money of the shareholders.
And Allaah is the source of strength.