Mesoscopic structure of the stock market and portfolio optimization