# Make an Animation with R

In a recent project for my optimization and simulation class, I was tackling a portfolio optimization problem. I was asked to find a portfolio with the same return rate but lower portfolio variance. Using quadratic programming to obtain the minimal variance portfolio is not an issue for me.

The target portfolio has a expected return of 2.22% and the associated portfolio standard deviation is 3.31%. Using optimization, I found a portfolio maintaining the same return rate but a lower portfolio standard deviation of 2.85%.

Here is a plot comparing the simulated return distributions for these two portfolios.

After I got this plot, I was thinking about a way to show the differences in a dynamic way, better if I can make an animation for it and I wish to do so in R.  I found that the slope diagram might be a good chart type for this task and I found an R package called animation for creating animation within R.

There is no default geom in ggplot for creating the slope diagram, however, I found that one can create slope diagram using geom_segment().

Here is an example of slope diagram.  Basically, the vertical position determines the portfolio returns and for each iteration in the simulation we add a line segment connecting the two different portfolio return values from both sides and coloring the line segment.

To use the animation package, one need to write a loop or a function that can plot all the plots needed to generate the animation in time sequence order.

You can define your own function to make all the plots needed for your animation. And once you have done this, you can use the saveVideo() function from the animation package to generate a .mp4 animation.

To do so, you just need to specify your operation system and the path to ffmpeg executable in your system and then calling saveVideo() by passing the plot making function along with some parameters for setting up the video quality.

Here is the animation created using the above code.

The animation dynamically showing the performance difference between two portfolios, while the minimal variance portfolio has a lower chance of losing a huge amount of money, it also gives up some chance to earning large returns. This is depicted by the difference between density of points on the lower and upper parts in two sides. Also, the amount of red color and green color are approximately equal, suggesting that half of the time the minimal variance will yield a lower return than the target portfolio.

There are many other options in the animation package. You can use it to generate GIF, HTML or SWF animations with similar method.