This paper investigates how, in a heterogeneous agents model with ?nancial frictions, idiosyncratic individual shocks interact with exogenous aggregate shocks to generate time-varying levels of leverage and endogenous aggregate risk. To do so, we show how such a model can be e?ciently computed, despite its substantial nonlinearities, using tools from machine learning. We also illustrate how the model can be structurally estimated with a likelihood function, using tools from inference with di?usions. We document, ?rst, the strong nonlinearities created by ?nancial frictions. Second, we report the existence of multiple stochastic steady states with properties that di?er from the deterministic steady state along important dimensions. Third, we illustrate how the generalized impulse re-sponse functions of the model are highly state-dependent. In particular, we ?nd that the recovery after a negative aggregate shock is more sluggish when the economy is more lever-aged. Fourth, we prove that wealth heterogeneity matters in this economy because of the asymmetric responses of household consumption decisions to aggregate shocks.