use of org.ojalgo.series.CoordinationSet in project ojAlgo-finance by optimatika.
the class FinanceUtils method makeCovarianceMatrix.
/**
* @param listOfTimeSeries An ordered collection of time series
* @param mayBeMissingValues Individual series may be missing some values - try to fix this or not
* @return Annualised covariances
*/
public static <N extends Number> PrimitiveMatrix makeCovarianceMatrix(final List<CalendarDateSeries<N>> listOfTimeSeries, final boolean mayBeMissingValues) {
final int tmpSize = listOfTimeSeries.size();
final CoordinationSet<N> tmpUncoordinated = new CoordinationSet<>(listOfTimeSeries);
final CalendarDateUnit tmpDataResolution = tmpUncoordinated.getResolution();
if (mayBeMissingValues) {
tmpUncoordinated.complete();
}
final CoordinationSet<N> tmpCoordinated = tmpUncoordinated.prune(tmpDataResolution);
final Builder<PrimitiveMatrix> tmpMatrixBuilder = PrimitiveMatrix.FACTORY.getBuilder(tmpSize, tmpSize);
final double tmpToYearFactor = (double) CalendarDateUnit.YEAR.size() / (double) tmpDataResolution.size();
SampleSet tmpSampleSet;
final SampleSet[] tmpSampleSets = new SampleSet[tmpSize];
for (int j = 0; j < tmpSize; j++) {
final PrimitiveSeries tmpPrimitiveSeries = tmpCoordinated.get(listOfTimeSeries.get(j).getName()).asPrimitive();
tmpSampleSet = SampleSet.wrap(tmpPrimitiveSeries.quotients().log().toDataSeries());
tmpMatrixBuilder.set(j, j, tmpToYearFactor * tmpSampleSet.getVariance());
for (int i = 0; i < j; i++) {
final double tmpCovariance = tmpToYearFactor * tmpSampleSets[i].getCovariance(tmpSampleSet);
tmpMatrixBuilder.set(i, j, tmpCovariance);
tmpMatrixBuilder.set(j, i, tmpCovariance);
}
tmpSampleSets[j] = tmpSampleSet;
}
return tmpMatrixBuilder.get();
}
Aggregations