Search in sources :

Example 6 with DataSource

use of suite.trade.data.DataSource in project suite by stupidsing.

the class StatisticalArbitrageTest method testMonteCarloBestBet.

@Test
public void testMonteCarloBestBet() {
    int nTrials = 10000;
    int nBets = 40;
    DataSource ds = cfg.dataSource(Asset.hsiSymbol).range(period).cleanse();
    float[] returns = ds.returns();
    for (float bet = 0f - 2f; bet < 1f + 2f; bet += .02f) {
        float notBet = 1f - bet;
        double sum = 0d;
        for (int i = 0; i < nTrials; i++) {
            double account = 1d;
            for (int j = 0; j < nBets; j++) {
                double return_ = returns[random.nextInt(returns.length)];
                account = notBet * account + bet * account * (1d + return_);
            }
            sum += account;
        }
        System.out.println("bet = " + To.string(bet) + ", avg outcome = " + To.string(sum / nTrials));
    }
}
Also used : AlignKeyDataSource(suite.trade.data.DataSource.AlignKeyDataSource) DataSource(suite.trade.data.DataSource) Test(org.junit.Test)

Example 7 with DataSource

use of suite.trade.data.DataSource in project suite by stupidsing.

the class BackAllocatorTest method testStop.

@Test
public void testStop() {
    Time start = Time.of(2017, 1, 1);
    String symbol = "S";
    float[] prices = { 1f, .99f, .98f, .5f, .5f, .5f, 0f, 0f, 0f };
    BackAllocator ba0 = (akds, ts) -> index -> List.of(Pair.of(symbol, 1d));
    BackAllocator ba1 = ba0.stopLoss(.98d);
    int length = prices.length;
    long[] ts = Longs_.toArray(length, i -> start.addDays(i).epochSec());
    DataSource ds = DataSource.of(ts, prices);
    AlignKeyDataSource<String> akds = DataSource.alignAll(Read.from2(List.of(Pair.of(symbol, ds))));
    int[] indices = Ints_.toArray(length, i -> i);
    OnDateTime odt = ba1.allocate(akds, indices);
    List<Double> potentials = // 
    Ints_.range(// 
    indices.length).map(// 
    index -> 0 < index ? Read.from(odt.onDateTime(index)) : Read.<Pair<String, Double>>empty()).map(// 
    pairs -> pairs.toDouble(Obj_Dbl.sum(pair -> pair.t1))).toList();
    assertEquals(List.of(0d, 1d, 1d, 1d, 0d, 0d, 0d, 0d, 0d), potentials);
}
Also used : OnDateTime(suite.trade.backalloc.BackAllocator.OnDateTime) Pair(suite.adt.pair.Pair) List(java.util.List) Read(suite.streamlet.Read) Time(suite.trade.Time) AlignKeyDataSource(suite.trade.data.DataSource.AlignKeyDataSource) DataSource(suite.trade.data.DataSource) Test(org.junit.Test) Obj_Dbl(suite.primitive.DblPrimitives.Obj_Dbl) Ints_(suite.primitive.Ints_) Assert.assertEquals(org.junit.Assert.assertEquals) Longs_(suite.primitive.Longs_) OnDateTime(suite.trade.backalloc.BackAllocator.OnDateTime) Time(suite.trade.Time) AlignKeyDataSource(suite.trade.data.DataSource.AlignKeyDataSource) DataSource(suite.trade.data.DataSource) OnDateTime(suite.trade.backalloc.BackAllocator.OnDateTime) Pair(suite.adt.pair.Pair) Test(org.junit.Test)

Example 8 with DataSource

use of suite.trade.data.DataSource in project suite by stupidsing.

the class BackAllocatorOld method questoQuella.

public BackAllocator questoQuella(String symbol0, String symbol1) {
    int tor = 64;
    double threshold = 0d;
    BackAllocator ba0 = (akds, indices) -> {
        Streamlet2<String, DataSource> dsBySymbol = akds.dsByKey;
        Map<String, DataSource> dsBySymbol_ = dsBySymbol.toMap();
        DataSource ds0 = dsBySymbol_.get(symbol0);
        DataSource ds1 = dsBySymbol_.get(symbol1);
        return index -> {
            int ix = index - 1;
            int i0 = ix - tor;
            double p0 = ds0.get(i0).t1, px = ds0.get(ix).t1;
            double q0 = ds1.get(i0).t1, qx = ds1.get(ix).t1;
            double pdiff = Quant.return_(p0, px);
            double qdiff = Quant.return_(q0, qx);
            if (threshold < Math.abs(pdiff - qdiff))
                return // 
                List.of(// 
                Pair.of(pdiff < qdiff ? symbol0 : symbol1, 1d), Pair.of(pdiff < qdiff ? symbol1 : symbol0, -1d));
            else
                return List.of();
        };
    };
    return ba0.filterByAsset(symbol -> String_.equals(symbol, symbol0) || String_.equals(symbol, symbol1));
}
Also used : BackAllocator(suite.trade.backalloc.BackAllocator) Arrays(java.util.Arrays) Streamlet2(suite.streamlet.Streamlet2) Statistic(suite.math.numeric.Statistic) MovingAverage(suite.trade.analysis.MovingAverage) Quant(ts.Quant) BollingerBands(ts.BollingerBands) MovingRange(suite.trade.analysis.MovingAverage.MovingRange) Pair(suite.adt.pair.Pair) Friends.max(suite.util.Friends.max) List(java.util.List) MeanVariance(suite.math.numeric.Statistic.MeanVariance) String_(suite.util.String_) Configuration(suite.trade.data.Configuration) Map(java.util.Map) DataSource(suite.trade.data.DataSource) TimeSeries(ts.TimeSeries) BackAllocator(suite.trade.backalloc.BackAllocator) Streamlet2(suite.streamlet.Streamlet2) Map(java.util.Map) DataSource(suite.trade.data.DataSource)

Example 9 with DataSource

use of suite.trade.data.DataSource in project suite by stupidsing.

the class MovingAvgMeanReversionBackAllocator method backAllocator.

public BackAllocator backAllocator() {
    return (akds, indices) -> {
        Map<String, DataSource> dsBySymbol = akds.dsByKey.toMap();
        double dailyRiskFreeInterestRate = Trade_.riskFreeInterestRate(1);
        DataSourceView<String, MeanReversionStat> dsv = // 
        DataSourceView.of(tor, 256, akds, (symbol, ds, period) -> new MeanReversionStat(ds, period));
        return index -> {
            Map<String, MeanReversionStat> mrsBySymbol = // 
            akds.dsByKey.map2(// 
            (symbol, ds) -> dsv.get(symbol, index)).filterValue(// 
            mrsReversionStat -> mrsReversionStat != null).toMap();
            // ensure 0 < half-life: determine investment period
            return // 
            Read.from2(mrsBySymbol).filterValue(mrs -> // 
            mrs.adf < 0d && // 
            mrs.hurst < .5d && // 
            mrs.movingAvgMeanReversionRatio() < 0d).map2((symbol, mrs) -> {
                DataSource ds = dsBySymbol.get(symbol);
                double price = ds.prices[index - 1];
                double lma = mrs.latestMovingAverage();
                double diff = mrs.movingAvgMeanReversion.predict(new float[] { (float) lma, 1f });
                double dailyReturn = diff / price - dailyRiskFreeInterestRate;
                ReturnsStat returnsStat = ts.returnsStatDaily(ds.prices);
                double sharpe = returnsStat.sharpeRatio();
                double kelly = dailyReturn * price * price / mrs.movingAvgMeanReversion.sse;
                return new PotentialStat(dailyReturn, sharpe, kelly);
            }).filterValue(// 
            ps -> 0d < ps.kelly).cons(Asset.cashSymbol, // 
            new PotentialStat(Trade_.riskFreeInterestRate, 1d, 0d)).mapValue(// 
            ps -> ps.kelly).sortBy(// 
            (symbol, potential) -> -potential).take(// 
            top).toList();
        };
    };
}
Also used : BackAllocator(suite.trade.backalloc.BackAllocator) Read(suite.streamlet.Read) Trade_(suite.trade.Trade_) MovingAverage(suite.trade.analysis.MovingAverage) To(suite.util.To) LinearRegression(suite.math.numeric.Statistic.LinearRegression) ReturnsStat(ts.TimeSeries.ReturnsStat) Map(java.util.Map) DataSource(suite.trade.data.DataSource) TimeSeries(ts.TimeSeries) Asset(suite.trade.Asset) TimeRange(suite.trade.TimeRange) DataSourceView(suite.trade.data.DataSourceView) DataSourceView(suite.trade.data.DataSourceView) ReturnsStat(ts.TimeSeries.ReturnsStat) Map(java.util.Map) DataSource(suite.trade.data.DataSource)

Example 10 with DataSource

use of suite.trade.data.DataSource in project suite by stupidsing.

the class WalkForwardAllocTester method tick.

public String tick(Time time, Map<String, Float> priceBySymbol) {
    int last = windowSize - 1;
    System.arraycopy(times, 0, times, 1, last);
    times[last] = time.epochSec();
    for (Entry<String, DataSource> e : dsBySymbol.entrySet()) {
        String symbol = e.getKey();
        float[] prices = e.getValue().prices;
        System.arraycopy(prices, 0, prices, 1, last);
        prices[last] = priceBySymbol.get(symbol);
    }
    AlignKeyDataSource<String> akds = new AlignKeyDataSource<>(times, Read.from2(dsBySymbol));
    List<Pair<String, Double>> ratioBySymbol = wfa.allocate(akds, windowSize);
    UpdatePortfolio up = Trade_.updatePortfolio(time.ymdHms(), account, ratioBySymbol, assetBySymbol, Read.from2(priceBySymbol).mapValue(Eod::of).toMap());
    float valuation_;
    valuations.append(valuation_ = up.valuation0);
    for (Pair<String, Float> e : up.val0.streamlet()) holdBySymbol.compute(e.t0, (s, h) -> e.t1 / valuation_ + (h != null ? h : 0d));
    List<Trade> trades_ = up.trades;
    String actions;
    if (windowSize <= valuations.size())
        actions = play(trades_);
    else
        actions = "wait";
    return // 
    time.ymdHms() + ", valuation = " + // 
    valuation_ + ", portfolio = " + // 
    account + ", actions = " + actions;
}
Also used : Read(suite.streamlet.Read) Statistic(suite.math.numeric.Statistic) FloatsBuilder(suite.primitive.Floats.FloatsBuilder) Trade_(suite.trade.Trade_) AlignKeyDataSource(suite.trade.data.DataSource.AlignKeyDataSource) HashMap(java.util.HashMap) To(suite.util.To) UpdatePortfolio(suite.trade.Trade_.UpdatePortfolio) ArrayList(java.util.ArrayList) Pair(suite.adt.pair.Pair) List(java.util.List) Trade(suite.trade.Trade) Streamlet(suite.streamlet.Streamlet) Time(suite.trade.Time) Configuration(suite.trade.data.Configuration) Eod(suite.trade.data.DataSource.Eod) ReturnsStat(ts.TimeSeries.ReturnsStat) Map(java.util.Map) Account(suite.trade.Account) Entry(java.util.Map.Entry) DataSource(suite.trade.data.DataSource) Sink(suite.util.FunUtil.Sink) TimeSeries(ts.TimeSeries) Asset(suite.trade.Asset) AlignKeyDataSource(suite.trade.data.DataSource.AlignKeyDataSource) AlignKeyDataSource(suite.trade.data.DataSource.AlignKeyDataSource) DataSource(suite.trade.data.DataSource) Trade(suite.trade.Trade) UpdatePortfolio(suite.trade.Trade_.UpdatePortfolio) Eod(suite.trade.data.DataSource.Eod) Pair(suite.adt.pair.Pair)

Aggregations

DataSource (suite.trade.data.DataSource)18 Map (java.util.Map)11 Read (suite.streamlet.Read)11 Asset (suite.trade.Asset)11 Configuration (suite.trade.data.Configuration)11 AlignKeyDataSource (suite.trade.data.DataSource.AlignKeyDataSource)11 Statistic (suite.math.numeric.Statistic)9 Time (suite.trade.Time)9 List (java.util.List)8 Test (org.junit.Test)8 Pair (suite.adt.pair.Pair)8 Streamlet (suite.streamlet.Streamlet)8 Streamlet2 (suite.streamlet.Streamlet2)8 Quant (ts.Quant)8 As (suite.streamlet.As)7 TimeRange (suite.trade.TimeRange)7 Arrays (java.util.Arrays)6 HashMap (java.util.HashMap)6 Obj_Dbl (suite.primitive.DblPrimitives.Obj_Dbl)6 String_ (suite.util.String_)6