The different crystal structures of ferromagnetic Ni$_2$MnGa have been calculated using density functional theory (DFT) with special emphasis on the modulated structures 10M and 14M. These are important for understanding the stability of Ni$_2$MnGa martensites and their functionality as shape-memory materials. The modulated structures have been optimized in the calculations and their properties are discussed in relation to the structures without modulation. The occurrence of the modulated structures is related to the soft TA$_2$ phonon mode observed in Ni$_2$MnGa. The latter is related to the specific nesting behavior of the Fermi surface in Ni$_2$MnGa. Particular shapes of the modulated structures are stabilized by the covalent interaction mediated by the textit{p}-orbitals of Ga and textit{d}-orbitals of Ni. The role of this interaction becomes clear seen when considering the phonon dispersion spectrum of Ni$_2$MnGa, where some characteristic anomalies occur in the coupling of acoustical vibrational modes and the optical modes of Ni.