Search in sources :

Example 1 with Floats_

use of suite.primitive.Floats_ in project suite by stupidsing.

the class Strategos method lowPassPrediction.

public BuySellStrategy lowPassPrediction(int windowSize, int nFutureDays, int nLowPass, float threshold) {
    DiscreteCosineTransform dct = new DiscreteCosineTransform();
    int nPastDays = windowSize - nFutureDays;
    return prices -> holdFixedDays(prices.length, nFutureDays, day -> {
        if (nPastDays <= day) {
            // moving window
            float[] fs0 = new float[windowSize];
            float price0 = prices[day];
            Floats_.copy(prices, day - nPastDays, fs0, 0, nPastDays);
            Arrays.fill(fs0, nPastDays, windowSize, price0);
            float[] fs1 = dct.dct(fs0);
            float[] fs2 = Floats_.toArray(windowSize, j -> j < nLowPass ? fs1[j] : 0f);
            float[] fs3 = dct.idct(fs2);
            float predict = fs3[fs3.length - 1];
            return getSignal(price0, predict, threshold);
        } else
            return 0;
    });
}
Also used : GetBuySell(suite.trade.singlealloc.BuySellStrategy.GetBuySell) Arrays(java.util.Arrays) Floats_(suite.primitive.Floats_) Vector(suite.math.linalg.Vector) MovingAverage(suite.trade.analysis.MovingAverage) Ints_(suite.primitive.Ints_) Quant(ts.Quant) DiscreteCosineTransform(suite.math.transform.DiscreteCosineTransform) DiscreteCosineTransform(suite.math.transform.DiscreteCosineTransform)

Example 2 with Floats_

use of suite.primitive.Floats_ in project suite by stupidsing.

the class Arch method arch.

public float[] arch(float[] ys, int p, int q) {
    // auto regressive
    int length = ys.length;
    float[][] xs0 = To.array(length, float[].class, i -> copyPadZeroes(ys, i - p, i));
    LinearRegression lr0 = stat.linearRegression(xs0, ys, null);
    float[] variances = To.vector(lr0.residuals, residual -> residual * residual);
    // conditional heteroskedasticity
    LinearRegression lr1 = stat.linearRegression(// 
    Ints_.range(// 
    length).map(i -> FltObjPair.of(variances[i], copyPadZeroes(variances, i - p, i))));
    return Floats_.concat(lr0.coefficients, lr1.coefficients);
}
Also used : Friends.max(suite.util.Friends.max) Arrays(java.util.Arrays) DblSource(suite.primitive.DblPrimitives.DblSource) Statistic(suite.math.numeric.Statistic) Floats_(suite.primitive.Floats_) FltObjPair(suite.primitive.adt.pair.FltObjPair) Random(java.util.Random) To(suite.util.To) Ints_(suite.primitive.Ints_) LinearRegression(suite.math.numeric.Statistic.LinearRegression) Int_Dbl(suite.primitive.Int_Dbl) LinearRegression(suite.math.numeric.Statistic.LinearRegression)

Example 3 with Floats_

use of suite.primitive.Floats_ in project suite by stupidsing.

the class StatisticTest method testLinearRegression.

@Test
public void testLinearRegression() {
    int m = 7, n = 9;
    float[] expect = Floats_.toArray(m, j -> random.nextFloat());
    float[][] xs = To.matrix(n, m, (i, j) -> random.nextFloat());
    LinearRegression lr = stat.linearRegression(// 
    Read.from(// 
    xs).map(x -> FltObjPair.of((float) (vec.dot(expect, x) + random.nextGaussian() * .01f), x)));
    Dump.out(lr);
    float[] actual = lr.coefficients();
    vec.verifyEquals(expect, actual, .1f);
    float[] xtest = Floats_.toArray(m, j -> random.nextFloat());
    MathUtil.verifyEquals(vec.dot(expect, xtest), lr.predict(xtest), .1f);
    MathUtil.verifyEquals(1f, (float) lr.r2, .1f);
}
Also used : Read(suite.streamlet.Read) Dump(suite.inspect.Dump) Floats_(suite.primitive.Floats_) Vector(suite.math.linalg.Vector) MathUtil(suite.math.MathUtil) FltObjPair(suite.primitive.adt.pair.FltObjPair) Random(java.util.Random) Test(org.junit.Test) To(suite.util.To) LinearRegression(suite.math.numeric.Statistic.LinearRegression) LinearRegression(suite.math.numeric.Statistic.LinearRegression) Test(org.junit.Test)

Example 4 with Floats_

use of suite.primitive.Floats_ in project suite by stupidsing.

the class AnalyzeTimeSeriesTest method analyze.

private void analyze(float[] prices) {
    int length = prices.length;
    int log2 = Quant.log2trunc(length);
    double nYears = length * Trade_.invTradeDaysPerYear;
    float[] fds = dct.dct(Arrays.copyOfRange(prices, length - log2, length));
    float[] returns = ts.returns(prices);
    float[] logPrices = To.vector(prices, Math::log);
    float[] logReturns = ts.differences(1, logPrices);
    MeanVariance rmv = stat.meanVariance(returns);
    double variance = rmv.variance;
    double kelly = rmv.mean / variance;
    IntFltPair max = IntFltPair.of(Integer.MIN_VALUE, Float.MIN_VALUE);
    for (int i = 4; i < fds.length; i++) {
        float f = Math.abs(fds[i]);
        if (max.t1 < f)
            max.update(i, f);
    }
    IntFunction<BuySell> momFun = n -> {
        int d0 = 1 + n;
        int d1 = 1;
        return buySell(d -> Quant.sign(prices[d - d0], prices[d - d1])).start(d0);
    };
    IntFunction<BuySell> revert = d -> momFun.apply(d).scale(0f, -1f);
    IntFunction<BuySell> trend_ = d -> momFun.apply(d).scale(0f, +1f);
    BuySell[] reverts = To.array(8, BuySell.class, revert);
    BuySell[] trends_ = To.array(8, BuySell.class, trend_);
    BuySell tanh = buySell(d -> Tanh.tanh(3.2d * reverts[1].apply(d)));
    float[] holds = mt.hold(prices, 1f, 1f, 1f);
    float[] ma200 = ma.movingAvg(prices, 200);
    BuySell mat = buySell(d -> {
        int last = d - 1;
        return Quant.sign(ma200[last], prices[last]);
    }).start(1).longOnly();
    BuySell mt_ = buySell(d -> holds[d]);
    Pair<float[], float[]> bbmv = bb.meanVariances(VirtualVector.of(logReturns), 9, 0);
    float[] bbmean = bbmv.t0;
    float[] bbvariances = bbmv.t1;
    BuySell ms2 = buySell(d -> {
        int last = d - 1;
        int ref = last - 250;
        float mean = bbmean[last];
        return Quant.sign(logPrices[last], logPrices[ref] - bbvariances[last] / (2d * mean * mean));
    }).start(1 + 250);
    LogUtil.info(// 
    "" + "\nsymbol = " + // 
    symbol + "\nlength = " + // 
    length + "\nnYears = " + // 
    nYears + "\nups = " + // 
    Floats_.of(returns).filter(return_ -> 0f <= return_).size() + "\ndct period = " + // 
    max.t0 + // 
    Ints_.range(// 
    10).map(// 
    d -> "\ndct component [" + d + "d] = " + fds[d]).collect(// 
    As::joined) + "\nreturn yearly sharpe = " + // 
    rmv.mean / Math.sqrt(variance / nYears) + "\nreturn kelly = " + // 
    kelly + "\nreturn skew = " + // 
    stat.skewness(returns) + "\nreturn kurt = " + // 
    stat.kurtosis(returns) + // 
    Ints_.of(1, 2, 4, 8, 16, // 
    32).map(// 
    d -> "\nmean reversion ols [" + d + "d] = " + ts.meanReversion(prices, d).coefficients[0]).collect(// 
    As::joined) + // 
    Ints_.of(4, // 
    16).map(// 
    d -> "\nvariance ratio [" + d + "d over 1d] = " + ts.varianceRatio(prices, d)).collect(// 
    As::joined) + "\nreturn hurst = " + // 
    ts.hurst(prices, prices.length / 2) + "\nhold " + // 
    buySell(d -> 1d).invest(prices) + "\nkelly " + // 
    buySell(d -> kelly).invest(prices) + "\nma200 trend " + // 
    mat.invest(prices) + // 
    Ints_.range(1, // 
    8).map(// 
    d -> "\nrevert [" + d + "d] " + reverts[d].invest(prices)).collect(// 
    As::joined) + // 
    Ints_.range(1, // 
    8).map(// 
    d -> "\ntrend_ [" + d + "d] " + trends_[d].invest(prices)).collect(// 
    As::joined) + // 
    Ints_.range(1, // 
    8).map(// 
    d -> "\nrevert [" + d + "d] long-only " + reverts[d].longOnly().invest(prices)).collect(// 
    As::joined) + // 
    Ints_.range(1, // 
    8).map(// 
    d -> "\ntrend_ [" + d + "d] long-only " + trends_[d].longOnly().invest(prices)).collect(// 
    As::joined) + "\nms2 " + // 
    ms2.invest(prices) + "\nms2 long-only " + // 
    ms2.longOnly().invest(prices) + "\ntanh " + // 
    tanh.invest(prices) + "\ntimed " + // 
    mt_.invest(prices) + "\ntimed long-only " + mt_.longOnly().invest(prices));
}
Also used : Arrays(java.util.Arrays) LogUtil(suite.os.LogUtil) IntFltPair(suite.primitive.adt.pair.IntFltPair) Trade_(suite.trade.Trade_) ConfigurationImpl(suite.trade.data.ConfigurationImpl) TimeSeries(ts.TimeSeries) Ints_(suite.primitive.Ints_) DiscreteCosineTransform(suite.math.transform.DiscreteCosineTransform) IntFunction(java.util.function.IntFunction) Statistic(suite.math.numeric.Statistic) Test(org.junit.Test) To(suite.util.To) Quant(ts.Quant) BollingerBands(ts.BollingerBands) Tanh(suite.math.Tanh) VirtualVector(suite.math.linalg.VirtualVector) Pair(suite.adt.pair.Pair) Friends.max(suite.util.Friends.max) MeanVariance(suite.math.numeric.Statistic.MeanVariance) Time(suite.trade.Time) Floats_(suite.primitive.Floats_) Configuration(suite.trade.data.Configuration) DataSource(suite.trade.data.DataSource) As(suite.streamlet.As) TimeRange(suite.trade.TimeRange) Int_Dbl(suite.primitive.Int_Dbl) Int_Flt(suite.primitive.Int_Flt) IntFltPair(suite.primitive.adt.pair.IntFltPair) MeanVariance(suite.math.numeric.Statistic.MeanVariance) As(suite.streamlet.As)

Example 5 with Floats_

use of suite.primitive.Floats_ in project suite by stupidsing.

the class Arima method maIa.

// "High Frequency Trading - A Practical Guide to Algorithmic Strategies and
// Trading Systems", Irene Aldridge, page 100
// xs[t]
// = mas[0] * 1 + mas[1] * ep[t - 1] + ... + mas[q] * ep[t - q]
// + ep[t]
@SuppressWarnings("unused")
private float[] maIa(float[] xs, int q) {
    int length = xs.length;
    float[][] epqByIter = new float[q][];
    int iter = 0;
    int qm1 = q - 1;
    while (true) {
        int iter_ = iter;
        LinearRegression lr = stat.linearRegression(// 
        Ints_.range(// 
        length).map(t -> {
            int tqm1 = t + qm1;
            float[] lrxs = Floats_.concat(Floats_.of(1f), Ints_.range(iter_).collect(Int_Flt.lift(i -> epqByIter[i][tqm1 - i]))).toArray();
            return FltObjPair.of(xs[t], lrxs);
        }));
        if (iter < q)
            System.arraycopy(lr.residuals, 0, epqByIter[iter++] = new float[q + length], q, length);
        else
            return lr.coefficients();
    }
}
Also used : Arrays(java.util.Arrays) DblSource(suite.primitive.DblPrimitives.DblSource) Friends.min(suite.util.Friends.min) Statistic(suite.math.numeric.Statistic) Random(java.util.Random) To(suite.util.To) LinearRegression(suite.math.numeric.Statistic.LinearRegression) Friends.max(suite.util.Friends.max) Floats_(suite.primitive.Floats_) Vector(suite.math.linalg.Vector) Floats(suite.primitive.Floats) FltObjPair(suite.primitive.adt.pair.FltObjPair) FltStreamlet(suite.primitive.streamlet.FltStreamlet) Ints_(suite.primitive.Ints_) Int_Dbl(suite.primitive.Int_Dbl) Int_Flt(suite.primitive.Int_Flt) DblObjPair(suite.primitive.adt.pair.DblObjPair) LinearRegression(suite.math.numeric.Statistic.LinearRegression)

Aggregations

Floats_ (suite.primitive.Floats_)10 Ints_ (suite.primitive.Ints_)9 Arrays (java.util.Arrays)8 To (suite.util.To)8 Random (java.util.Random)7 Statistic (suite.math.numeric.Statistic)7 LinearRegression (suite.math.numeric.Statistic.LinearRegression)7 FltObjPair (suite.primitive.adt.pair.FltObjPair)7 Int_Flt (suite.primitive.Int_Flt)6 Friends.max (suite.util.Friends.max)6 Test (org.junit.Test)4 Vector (suite.math.linalg.Vector)4 DiscreteCosineTransform (suite.math.transform.DiscreteCosineTransform)4 LogUtil (suite.os.LogUtil)4 Int_Dbl (suite.primitive.Int_Dbl)4 Friends.min (suite.util.Friends.min)4 Quant (ts.Quant)4 Pair (suite.adt.pair.Pair)3 DblSource (suite.primitive.DblPrimitives.DblSource)3 IntFltPair (suite.primitive.adt.pair.IntFltPair)3