We develop a general framework to apply the Kelly criterion to the stock market data, and consequently, to portfolio optimization. Under few conditions, using Monte Carlo simulations with different scenarios we prove that the Kelly criterion beats any other approach in many aspects. In particular, it maximizes the expected growth rate and the median of the terminal wealth. We also show that, under a normal distribution of returns, the Kelly criterion has the best performance in the long run. Next, we optimize a portfolio with the Kelly criterion with no leverage and no short selling conditions and show that this portfolio lays in the mean-variance efficient frontier and has higher expected return and higher variance, although it is less diversified, respect to the tangent portfolio optimized under the Markowitz approach. Finally, we implement a dynamic strategy applied on the European stock market data and compare the results between the tangent and the optimal Kelly portfolios. In a dynamic setting, the rolling Kelly portfolio outperforms competitors particularly in the case of rebalanced portfolios optimized with a 2-years window width.