Gambling might refer to a random system or a game of skill, often with unpredictable elements.
The value of a stock depends on an extremely complicated (financial) system.
In some cases, gambling is done on closed, formal mathematical systems where you can calculate or find out the expected value. In some countries, sometimes the expected returns have to even be disclosed.
This is not the case for all gambling, and also not the case for investing in stocks.
Historically, the average value of investments has gone up, with various qualifications like they have to be spread wide enough, while in gambling, the average returns is usually negative.
So, mathematically, you are better off thinking about closed, formal cases versus complicated systems that can not be analyzed exactly, and then, on the other hand, what is the expected value. The natural language concept of "gambling" is not a mathematically precise, analytical concept, in general.