I am implementing a method in Java to
calculate the variance, covariance,
and value at risk for a portfolio,
which should be flexible for use with
any number of assets in a portfolio. I
am struggling with how to calculate
the covariance of the assets as I can
only find formulae to do so for two or
three sets of values.
Are you sure you are up to the task? Do you have access to R (hey, it's free and open source) or Matlab (hey, Octave is free and open source) or something similar (hint: no, not Excel) to prototype this?
Otherwise, I don't even know where to start as there is so much more to this:
- non-synchronocity of returns (as your assets may not all trade at the same time),
- missing observations (leading to non-positive definite matrices),
- roundoff error,
- modeling issues,
- factor-models for dimension reduction as you do not want N x N for really large N.
There have literally been shelves full of dissertations and practitioner books been written on this. Read some---fifteen years ago we all read the first RiskMetrics (now part of MSCI) manual which was pretty novel and path-breaking then. It has answers to your questions too.
A decade ago, I did something like this for a universe of 200 assets in Perl (don't ask) and it can be done that way. That doesn't mean it should be done that way. Besides learning about the underlying (financial econometrics) math, you should also learn about some numerical libraries for Java. No need to reinvent the wheel.