Essays in macroeconomics with heterogeneous agents