This book presents a consistent and complete framework for studying the risk management of a pension fund. It gives the reader the opportunity to understand, replicate and widen the analysis. To this aim, the book provides all the tools for computing the optimal asset allocation in a dynamic framework where the financial horizon is stochastic (longevity risk) and the investor's wealth is not self-financed. This tutorial enables the reader to replicate all the results presented. The R codes are provided alongside the presentation of the theoretical framework. The book explains and discusses the problem of hedging longevity risk even in an incomplete market, though strong theoretical results about an incomplete framework are still lacking and the problem is still being discussed in most recent literature.