Search in sources :

Example 1 with SampleSet

use of org.ojalgo.random.SampleSet 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();
}
Also used : CalendarDateUnit(org.ojalgo.type.CalendarDateUnit) SampleSet(org.ojalgo.random.SampleSet) PrimitiveMatrix(org.ojalgo.matrix.PrimitiveMatrix) CoordinationSet(org.ojalgo.series.CoordinationSet) PrimitiveSeries(org.ojalgo.series.primitive.PrimitiveSeries)

Example 2 with SampleSet

use of org.ojalgo.random.SampleSet in project ojAlgo by optimatika.

the class GeometricBrownianMotionTest method testLogNormal.

@Test
@Tag("unstable")
public void testLogNormal() {
    final int tmpPeriods = 10000;
    final double tmpFactoryExpected = 1.05;
    final double tmpFactoryStdDev = PrimitiveFunction.ABS.invoke(new Normal(0.0, (tmpFactoryExpected - ONE)).doubleValue());
    final Normal tmpFactoryDistr = new Normal(tmpFactoryExpected, tmpFactoryStdDev);
    TestUtils.assertEquals("Factory Expected", tmpFactoryExpected, tmpFactoryDistr.getExpected(), 1E-14 / PrimitiveMath.THREE);
    TestUtils.assertEquals("Factory Std Dev", tmpFactoryStdDev, tmpFactoryDistr.getStandardDeviation(), 1E-14 / PrimitiveMath.THREE);
    final Primitive64Array tmpRawValues = Primitive64Array.make(tmpPeriods + 1);
    tmpRawValues.data[0] = ONE;
    for (int t = 1; t < tmpRawValues.count(); t++) {
        tmpRawValues.data[t] = tmpRawValues.data[t - 1] * tmpFactoryDistr.doubleValue();
    }
    final Primitive64Array tmpQuotient = Primitive64Array.make(tmpPeriods);
    final Primitive64Array tmpLogDiffs = Primitive64Array.make(tmpPeriods);
    for (int t = 0; t < tmpPeriods; t++) {
        tmpQuotient.data[t] = tmpRawValues.data[t + 1] / tmpRawValues.data[t];
        tmpLogDiffs.data[t] = PrimitiveFunction.LOG.invoke(tmpRawValues.data[t + 1]) - PrimitiveFunction.LOG.invoke(tmpRawValues.data[t]);
    }
    final SampleSet tmpQuotientSet = SampleSet.wrap(tmpQuotient);
    final SampleSet tmpLogDiffsSet = SampleSet.wrap(tmpLogDiffs);
    final GeometricBrownianMotion tmpProcess = GeometricBrownianMotion.estimate(tmpRawValues, ONE);
    final Normal tmpQuotienDistr = new Normal(tmpQuotientSet.getMean(), tmpQuotientSet.getStandardDeviation());
    final LogNormal tmpLogDiffDistr = new LogNormal(tmpLogDiffsSet.getMean(), tmpLogDiffsSet.getStandardDeviation());
    final LogNormal tmpProcessDistr = tmpProcess.getDistribution(ONE);
    TestUtils.assertEquals("Expected", tmpLogDiffDistr.getExpected(), tmpProcessDistr.getExpected(), 1E-14 / PrimitiveMath.THREE);
    TestUtils.assertEquals("Geometric Mean", tmpLogDiffDistr.getGeometricMean(), tmpProcessDistr.getGeometricMean(), 1E-14 / PrimitiveMath.THREE);
    TestUtils.assertEquals("Geometric Standard Deviation", tmpLogDiffDistr.getGeometricStandardDeviation(), tmpProcessDistr.getGeometricStandardDeviation(), 1E-14 / PrimitiveMath.THREE);
    TestUtils.assertEquals("Standard Deviation", tmpLogDiffDistr.getStandardDeviation(), tmpProcessDistr.getStandardDeviation(), 1E-14 / PrimitiveMath.THREE);
    TestUtils.assertEquals("Variance", tmpLogDiffDistr.getVariance(), tmpProcessDistr.getVariance(), 1E-14 / PrimitiveMath.THREE);
    double tmpFactoryVal = tmpFactoryDistr.getExpected();
    double tmpQuotienVal = tmpQuotienDistr.getExpected();
    double tmpLogDiffVal = tmpLogDiffDistr.getExpected();
    double tmpProcessVal = tmpProcessDistr.getExpected();
    double tmpGeometrVal = tmpProcessDistr.getGeometricMean();
    if (RandomProcessTests.DEBUG) {
        this.logDebug("Expected", tmpFactoryVal, tmpQuotienVal, tmpLogDiffVal, tmpProcessVal, tmpGeometrVal);
    }
    final double tmpDeltaExpected = (1E-14 / THREE) * THOUSAND * THOUSAND * THOUSAND * HUNDRED;
    TestUtils.assertEquals(tmpQuotienVal, tmpLogDiffVal, tmpDeltaExpected);
    TestUtils.assertEquals(tmpQuotienVal, tmpProcessVal, tmpDeltaExpected);
    TestUtils.assertEquals(true, tmpGeometrVal <= tmpProcessVal);
    tmpFactoryVal = tmpFactoryDistr.getStandardDeviation();
    tmpQuotienVal = tmpQuotienDistr.getStandardDeviation();
    tmpLogDiffVal = tmpLogDiffDistr.getStandardDeviation();
    tmpProcessVal = tmpProcessDistr.getStandardDeviation();
    tmpGeometrVal = tmpProcessDistr.getGeometricStandardDeviation();
    if (RandomProcessTests.DEBUG) {
        this.logDebug("Std Dev", tmpFactoryVal, tmpQuotienVal, tmpLogDiffVal, tmpProcessVal, tmpGeometrVal);
    }
    final double tmpDeltaStdDev = (1E-14 / THREE) * THOUSAND * THOUSAND * THOUSAND * THOUSAND;
    TestUtils.assertEquals(tmpQuotienVal, tmpLogDiffVal, tmpDeltaStdDev);
    TestUtils.assertEquals(tmpQuotienVal, tmpProcessVal, tmpDeltaStdDev);
    tmpFactoryVal = tmpFactoryDistr.getVariance();
    tmpQuotienVal = tmpQuotienDistr.getVariance();
    tmpLogDiffVal = tmpLogDiffDistr.getVariance();
    tmpProcessVal = tmpProcessDistr.getVariance();
    tmpGeometrVal = tmpProcessDistr.getGeometricStandardDeviation() * tmpLogDiffDistr.getGeometricStandardDeviation();
    if (RandomProcessTests.DEBUG) {
        this.logDebug("Var", tmpFactoryVal, tmpQuotienVal, tmpLogDiffVal, tmpProcessVal, tmpGeometrVal);
    }
    final double tmpDeltaVar = (1E-14 / THREE) * THOUSAND * THOUSAND * THOUSAND * HUNDRED;
    TestUtils.assertEquals(tmpQuotienVal, tmpLogDiffVal, tmpDeltaVar);
    TestUtils.assertEquals(tmpQuotienVal, tmpProcessVal, tmpDeltaVar);
    tmpFactoryVal = tmpRawValues.data[tmpPeriods];
    tmpQuotienVal = PrimitiveFunction.POW.invoke(tmpQuotienDistr.getExpected(), tmpPeriods);
    tmpLogDiffVal = PrimitiveFunction.POW.invoke(tmpLogDiffDistr.getExpected(), tmpPeriods);
    tmpProcessVal = tmpProcess.getExpected(tmpPeriods);
    tmpGeometrVal = PrimitiveFunction.POW.invoke(tmpProcessDistr.getGeometricMean(), tmpPeriods);
    if (RandomProcessTests.DEBUG) {
        this.logDebug("Final Value", tmpFactoryVal, tmpQuotienVal, tmpLogDiffVal, tmpProcessVal, tmpGeometrVal);
    }
    final double tmpDeltaFinal = (1E-14 / THREE) * THOUSAND;
    TestUtils.assertEquals(ONE, tmpGeometrVal / tmpFactoryVal, tmpDeltaFinal);
}
Also used : SampleSet(org.ojalgo.random.SampleSet) Primitive64Array(org.ojalgo.array.Primitive64Array) LogNormal(org.ojalgo.random.LogNormal) Normal(org.ojalgo.random.Normal) LogNormal(org.ojalgo.random.LogNormal) Test(org.junit.jupiter.api.Test) Tag(org.junit.jupiter.api.Tag)

Example 3 with SampleSet

use of org.ojalgo.random.SampleSet in project ojAlgo by optimatika.

the class GeometricBrownianMotion method estimate.

/**
 * @param seriesOfSamples A series of samples, evenly spaced in time.
 * @param samplePeriod The amount of time (in which ever unit you prefer) between each sample in the
 *        series.
 */
public static GeometricBrownianMotion estimate(final Access1D<?> seriesOfSamples, final double samplePeriod) {
    final int tmpSizeMinusOne = (int) (seriesOfSamples.count() - 1);
    final Array1D<Double> tmpLogDiffSeries = Array1D.PRIMITIVE64.makeZero(tmpSizeMinusOne);
    for (int i = 0; i < tmpSizeMinusOne; i++) {
        tmpLogDiffSeries.set(i, PrimitiveFunction.LOG.invoke(seriesOfSamples.doubleValue(i + 1) / seriesOfSamples.doubleValue(i)));
    }
    final SampleSet tmpSampleSet = SampleSet.wrap(tmpLogDiffSeries);
    final double tmpExp = tmpSampleSet.getMean();
    final double tmpVar = tmpSampleSet.getVariance();
    final double tmpDiff = PrimitiveFunction.SQRT.invoke(tmpVar / samplePeriod);
    final double tmpDrift = (tmpExp / samplePeriod) + ((tmpDiff * tmpDiff) / TWO);
    final GeometricBrownianMotion retVal = new GeometricBrownianMotion(tmpDrift, tmpDiff);
    // TODO Seems more natural to set it to the last value, but then some tests fail (need to look into why.)
    retVal.setValue(seriesOfSamples.doubleValue(0));
    return retVal;
}
Also used : SampleSet(org.ojalgo.random.SampleSet)

Example 4 with SampleSet

use of org.ojalgo.random.SampleSet in project ojAlgo-finance by optimatika.

the class SymbolDataTest method testYahooWeeklyAAPL.

@Test
public void testYahooWeeklyAAPL() {
    final YahooSymbol tmpYahoo = new YahooSymbol("AAPL", CalendarDateUnit.WEEK);
    final List<? extends DatePrice> tmpRows = tmpYahoo.getHistoricalPrices();
    final CalendarDateSeries<Double> tmpDaySeries = new CalendarDateSeries<>(CalendarDateUnit.DAY);
    tmpDaySeries.putAll(tmpRows);
    final CalendarDateSeries<Double> tmpYearSeries = tmpDaySeries.resample(CalendarDateUnit.YEAR);
    final CalendarDateSeries<Double> tmpMonthSeries = tmpDaySeries.resample(CalendarDateUnit.MONTH);
    final PrimitiveSeries tmpDataY = tmpYearSeries.asPrimitive();
    final PrimitiveSeries tmpDataM = tmpMonthSeries.asPrimitive();
    final SampleSet tmpSetY = SampleSet.wrap(tmpDataY.log().differences());
    final SampleSet tmpSetM = SampleSet.wrap(tmpDataM.log().differences());
    final GeometricBrownianMotion tmpProcY = GeometricBrownianMotion.estimate(tmpDataY, 1.0);
    tmpProcY.setValue(1.0);
    final GeometricBrownianMotion tmpProcM = GeometricBrownianMotion.estimate(tmpDataM, 1.0 / 12.0);
    tmpProcM.setValue(1.0);
    LogNormal tmpExpDistr = new LogNormal(tmpSetY.getMean(), tmpSetY.getStandardDeviation());
    LogNormal tmpActDistr = tmpProcY.getDistribution(1.0);
    TestUtils.assertEquals("Yearly Expected", tmpExpDistr.getExpected(), tmpActDistr.getExpected(), 1E-14 / PrimitiveMath.THREE);
    TestUtils.assertEquals("Yearly Var", tmpExpDistr.getVariance(), tmpActDistr.getVariance(), 1E-14 / PrimitiveMath.THREE);
    TestUtils.assertEquals("Yearly StdDev", tmpExpDistr.getStandardDeviation(), tmpActDistr.getStandardDeviation(), 1E-14 / PrimitiveMath.THREE);
    tmpExpDistr = new LogNormal(tmpSetM.getMean() * 12.0, tmpSetM.getStandardDeviation() * PrimitiveFunction.SQRT.invoke(12.0));
    tmpActDistr = tmpProcM.getDistribution(1.0);
    TestUtils.assertEquals("Monthly Expected", tmpExpDistr.getExpected(), tmpActDistr.getExpected(), 1E-14 / PrimitiveMath.THREE);
    TestUtils.assertEquals("Monthly Var", tmpExpDistr.getVariance(), tmpActDistr.getVariance(), 1E-14 / PrimitiveMath.THREE);
    TestUtils.assertEquals("Monthly StdDev", tmpExpDistr.getStandardDeviation(), tmpActDistr.getStandardDeviation(), 1E-14 / PrimitiveMath.THREE);
}
Also used : SampleSet(org.ojalgo.random.SampleSet) LogNormal(org.ojalgo.random.LogNormal) PrimitiveSeries(org.ojalgo.series.primitive.PrimitiveSeries) CalendarDateSeries(org.ojalgo.series.CalendarDateSeries) GeometricBrownianMotion(org.ojalgo.random.process.GeometricBrownianMotion) Test(org.junit.jupiter.api.Test)

Example 5 with SampleSet

use of org.ojalgo.random.SampleSet in project ojAlgo-finance by optimatika.

the class FinanceUtils method makeCovarianceMatrix.

/**
 * @param timeSeriesCollection
 * @return Annualised covariances
 */
public static <V extends Number> BasicMatrix makeCovarianceMatrix(final Collection<CalendarDateSeries<V>> timeSeriesCollection) {
    final CoordinationSet<V> tmpCoordinator = new CoordinationSet<>(timeSeriesCollection).prune();
    final ArrayList<SampleSet> tmpSampleSets = new ArrayList<>();
    for (final CalendarDateSeries<V> tmpTimeSeries : timeSeriesCollection) {
        final double[] values = tmpCoordinator.get(tmpTimeSeries.getName()).asPrimitive().toRawCopy1D();
        final int tmpSize1 = values.length - 1;
        final double[] retVal = new double[tmpSize1];
        for (int i = 0; i < tmpSize1; i++) {
            retVal[i] = PrimitiveFunction.LOG.invoke(values[i + 1] / values[i]);
        }
        final SampleSet tmpMakeUsingLogarithmicChanges = SampleSet.wrap(Access1D.wrap(retVal));
        tmpSampleSets.add(tmpMakeUsingLogarithmicChanges);
    }
    final int tmpSize = timeSeriesCollection.size();
    final Builder<PrimitiveMatrix> retValStore = PrimitiveMatrix.FACTORY.getBuilder(tmpSize, tmpSize);
    final double tmpToYearFactor = (double) CalendarDateUnit.YEAR.size() / (double) tmpCoordinator.getResolution().size();
    SampleSet tmpRowSet;
    SampleSet tmpColSet;
    for (int j = 0; j < tmpSize; j++) {
        tmpColSet = tmpSampleSets.get(j);
        for (int i = 0; i < tmpSize; i++) {
            tmpRowSet = tmpSampleSets.get(i);
            retValStore.set(i, j, tmpToYearFactor * tmpRowSet.getCovariance(tmpColSet));
        }
    }
    return retValStore.build();
}
Also used : SampleSet(org.ojalgo.random.SampleSet) PrimitiveMatrix(org.ojalgo.matrix.PrimitiveMatrix) ArrayList(java.util.ArrayList)

Aggregations

SampleSet (org.ojalgo.random.SampleSet)6 Test (org.junit.jupiter.api.Test)2 PrimitiveMatrix (org.ojalgo.matrix.PrimitiveMatrix)2 LogNormal (org.ojalgo.random.LogNormal)2 GeometricBrownianMotion (org.ojalgo.random.process.GeometricBrownianMotion)2 PrimitiveSeries (org.ojalgo.series.primitive.PrimitiveSeries)2 ArrayList (java.util.ArrayList)1 Tag (org.junit.jupiter.api.Tag)1 Primitive64Array (org.ojalgo.array.Primitive64Array)1 Normal (org.ojalgo.random.Normal)1 CalendarDateSeries (org.ojalgo.series.CalendarDateSeries)1 CoordinationSet (org.ojalgo.series.CoordinationSet)1 CalendarDateUnit (org.ojalgo.type.CalendarDateUnit)1