Search in sources :

Example 6 with Ints_

use of suite.primitive.Ints_ 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 7 with Ints_

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

the class Trade_ method collectBrokeredTrades.

public static Streamlet<Trade> collectBrokeredTrades(Outlet<Trade> outlet) {
    Trade[] trades0 = outlet.toArray(Trade.class);
    List<Trade> trades1 = new ArrayList<>();
    int length0 = trades0.length;
    int i0 = 0;
    IntIntSink tx = (i0_, i1_) -> {
        if (Ints_.range(i0_, i1_).mapInt(i -> trades0[i].buySell).sum() != 0)
            while (i0_ < i1_) {
                Trade trade0 = trades0[i0_++];
                if (!String_.equals(trade0.remark, "#"))
                    trades1.add(trade0);
            }
    };
    for (int i = 1; i < length0; i++) {
        Trade trade0 = trades0[i0];
        Trade trade1 = trades0[i];
        boolean isGroup = // 
        true && // 
        String_.equals(trade0.date, trade1.date) && // 
        String_.equals(trade0.symbol, trade1.symbol) && trade0.price == trade1.price;
        if (!isGroup) {
            tx.sink2(i0, i);
            i0 = i;
        }
    }
    tx.sink2(i0, length0);
    return Read.from(trades1);
}
Also used : LngIntPair(suite.primitive.adt.pair.LngIntPair) Outlet(suite.streamlet.Outlet) Read(suite.streamlet.Read) Obj_Flt(suite.primitive.FltPrimitives.Obj_Flt) IntFltPair(suite.primitive.adt.pair.IntFltPair) IntIntSink(suite.primitive.IntIntSink) HashMap(java.util.HashMap) Fun(suite.util.FunUtil.Fun) ArrayList(java.util.ArrayList) String_(suite.util.String_) Dbl_Dbl(suite.primitive.Dbl_Dbl) Map(java.util.Map) Ints_(suite.primitive.Ints_) Valuation(suite.trade.Account.Valuation) Set_(suite.util.Set_) LngFltPair(suite.primitive.adt.pair.LngFltPair) Friends.min(suite.util.Friends.min) Source(suite.util.FunUtil.Source) Set(java.util.Set) Pair(suite.adt.pair.Pair) Friends.max(suite.util.Friends.max) List(java.util.List) Obj_Int(suite.primitive.IntPrimitives.Obj_Int) Streamlet(suite.streamlet.Streamlet) Eod(suite.trade.data.DataSource.Eod) MathUtil(suite.math.MathUtil) As(suite.streamlet.As) IntIntSink(suite.primitive.IntIntSink) ArrayList(java.util.ArrayList)

Example 8 with Ints_

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

the class MarketTiming method time.

public int[] time(float[] prices) {
    int length = prices.length;
    int lookback = 40;
    float[] ma20 = ma.movingAvg(prices, 20);
    float[] ma50 = ma.movingAvg(prices, 50);
    double lookback80 = lookback * .8d;
    int[] flags = new int[length];
    for (int i = 0; i < length; i++) {
        int past = max(0, i - lookback);
        IntStreamlet past_i = Ints_.range(past, i);
        IntStreamlet past1_i = past_i.drop(1);
        int ma20abovema50 = past_i.filter(j -> ma50[j] < ma20[j]).size();
        int ma50abovema20 = past_i.filter(j -> ma20[j] < ma50[j]).size();
        double r = ma50abovema20 / (double) ma20abovema50;
        boolean isStrglyBullish = // 
        true && // 
        lookback <= ma20abovema50 && // 
        past1_i.isAll(j -> ma20[j - 1] <= ma20[j]) && // 
        past1_i.isAll(j -> ma50[j - 1] <= ma50[j]) && // 
        (1.02d * ma50[i] <= ma20[i] || ma20[past] - ma50[past] < ma20[i] - ma50[i]) && past_i.isAll(j -> ma20[j] <= prices[j]);
        boolean isWeaklyBullish = // 
        true && // 
        lookback80 <= ma20abovema50 && // 
        past1_i.isAll(j -> ma50[j - 1] <= ma50[j]) && past_i.isAll(j -> ma50[j] <= prices[j]);
        boolean isStrglyBearish = // 
        true && // 
        lookback <= ma50abovema20 && // 
        past1_i.isAll(j -> ma20[j] <= ma20[j - 1]) && // 
        past1_i.isAll(j -> ma50[j] <= ma50[j - 1]) && // 
        (1.02d * ma20[i] <= ma50[i] || ma50[past] - ma20[past] < ma50[i] - ma20[i]) && past_i.isAll(j -> prices[j] <= ma20[j]);
        boolean isWeaklyBearish = // 
        true && // 
        lookback80 <= ma50abovema20 && // 
        past1_i.isAll(j -> ma50[j] <= ma50[j - 1]) && past_i.isAll(j -> prices[j] <= ma50[j]);
        boolean isRangeBound__ = // non-trending
        true && 2d / 3d <= r && // 
        r <= 3d / 2d && // 
        stat.meanVariance(past_i.collect(Int_Flt.lift(j -> ma50[j])).toArray()).volatility() < .02d && // 
        .02d < stat.meanVariance(past_i.collect(Int_Flt.lift(j -> ma20[j])).toArray()).volatility() && (ma20[i] + ma50[i]) * .02d <= Math.abs(ma20[i] - ma50[i]);
        int flag = // 
        0 + // 
        (isStrglyBearish ? strgBear : 0) + // 
        (isWeaklyBearish ? weakBear : 0) + // 
        (isRangeBound__ ? rngBound : 0) + // 
        (isWeaklyBullish ? weakBull : 0) + (isStrglyBullish ? strgBull : 0);
        flags[i] = flag;
    }
    return flags;
}
Also used : Friends.max(suite.util.Friends.max) Statistic(suite.math.numeric.Statistic) Ints_(suite.primitive.Ints_) Int_Flt(suite.primitive.Int_Flt) IntStreamlet(suite.primitive.streamlet.IntStreamlet) IntStreamlet(suite.primitive.streamlet.IntStreamlet)

Example 9 with Ints_

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

the class PairTest method test.

private void test(TimeRange period, String symbol0, String symbol1) {
    DataSource ds0 = cfg.dataSource(symbol0, period);
    DataSource ds1 = cfg.dataSource(symbol1, period);
    LngStreamlet ts0 = Longs_.of(ds0.ts);
    LngStreamlet ts1 = Longs_.of(ds1.ts);
    long[] tradeTimes = Longs_.concat(ts0, ts1).distinct().sort().toArray();
    float[] prices0 = ds0.alignBeforePrices(tradeTimes).prices;
    float[] prices1 = ds1.alignBeforePrices(tradeTimes).prices;
    int length = prices0.length;
    LinearRegression lr = statistic.linearRegression(// 
    Ints_.range(// 
    length).map(i -> FltObjPair.of(prices1[i], new float[] { prices0[i], 1f })));
    System.out.println(symbol0 + " -> " + symbol1 + lr);
    assertTrue(.4d < lr.r2);
}
Also used : ConfigurationImpl(suite.trade.data.ConfigurationImpl) Statistic(suite.math.numeric.Statistic) Configuration(suite.trade.data.Configuration) FltObjPair(suite.primitive.adt.pair.FltObjPair) LngStreamlet(suite.primitive.streamlet.LngStreamlet) DataSource(suite.trade.data.DataSource) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Ints_(suite.primitive.Ints_) LinearRegression(suite.math.numeric.Statistic.LinearRegression) Longs_(suite.primitive.Longs_) LngStreamlet(suite.primitive.streamlet.LngStreamlet) LinearRegression(suite.math.numeric.Statistic.LinearRegression) DataSource(suite.trade.data.DataSource)

Example 10 with Ints_

use of suite.primitive.Ints_ 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)

Aggregations

Ints_ (suite.primitive.Ints_)24 To (suite.util.To)14 Arrays (java.util.Arrays)12 Statistic (suite.math.numeric.Statistic)12 Friends.max (suite.util.Friends.max)12 List (java.util.List)10 LinearRegression (suite.math.numeric.Statistic.LinearRegression)10 FltObjPair (suite.primitive.adt.pair.FltObjPair)10 Pair (suite.adt.pair.Pair)9 Floats_ (suite.primitive.Floats_)9 Read (suite.streamlet.Read)9 Friends.min (suite.util.Friends.min)9 Random (java.util.Random)8 Int_Flt (suite.primitive.Int_Flt)8 As (suite.streamlet.As)8 Test (org.junit.Test)7 Time (suite.trade.Time)6 Trade_ (suite.trade.Trade_)6 Configuration (suite.trade.data.Configuration)6 ConfigurationImpl (suite.trade.data.ConfigurationImpl)6