As renewable energy installation costs decrease and environmentally-friendly policies are progressively applied in many countries, distributed generation has emerged as the new archetype of energy generation and distribution. The design and economic feasibility of distributed generation systems is constrained by the operation of the microgrid, which has to consider the uncertainty of renewable energy sources, consumption habits and electricity market prices. In this paper, a mathematical model intended to optimize the design and economic feasibility of a microgrid is proposed. After a search in the state-of-the-art, weaknesses and strengths of existing models have been identified and taken into account for building the present model. The present model should be seen as a basis on which other models can be built upon, hence a complete definition of the different sub-models is stated: uncertainty modelling, optimization technique, physical constraints and regulatory framework. One of the main features presented is the generation of synthetic data in uncertainty modelling, employed to enhance the reliability of the model by taking into account a longer time horizon and a shorter time step. Results show significant details about energy management and prove the suitability of using a stochastic approach rather than deterministic or intuitive ones to perform the optimization.