Search in sources :

Example 1 with Trade

use of suite.trade.Trade in project suite by stupidsing.

the class DailyMain method alloc.

private Result alloc(String tag, float fund, BackAllocator backAllocator, Streamlet<Asset> assets) {
    TimeRange period = TimeRange.daysBefore(64);
    Simulate sim = BackAllocTester.of(cfg, period, assets, backAllocator, log).simulate(fund);
    Account account0 = Account.ofPortfolio(cfg.queryHistory().filter(r -> String_.equals(r.strategy, tag)));
    Account account1 = sim.account;
    Map<String, Integer> assets0 = account0.assets();
    Map<String, Integer> assets1 = account1.assets();
    Set<String> symbols = Set_.union(assets0.keySet(), assets1.keySet());
    Map<String, Float> priceBySymbol = cfg.quote(symbols);
    List<Trade> trades = Trade_.diff(Trade.NA, assets0, assets1, priceBySymbol::get).toList();
    sb.append("\nstrategy = " + tag + ", " + sim.conclusion());
    return new Result(tag, trades);
}
Also used : BackAllocator(suite.trade.backalloc.BackAllocator) Read(suite.streamlet.Read) LogUtil(suite.os.LogUtil) SerializedStoreCache(suite.os.SerializedStoreCache) Trade_(suite.trade.Trade_) RunUtil(suite.util.RunUtil) ArrayList(java.util.ArrayList) Bacs(suite.trade.backalloc.BackAllocConfigurations.Bacs) ConfigurationImpl(suite.trade.data.ConfigurationImpl) String_(suite.util.String_) BackAllocatorOld(suite.trade.backalloc.strategy.BackAllocatorOld) Map(java.util.Map) BackAllocTester(suite.trade.backalloc.BackAllocTester) Simulate(suite.trade.backalloc.BackAllocTester.Simulate) Set_(suite.util.Set_) BuySellStrategy(suite.trade.singlealloc.BuySellStrategy) Streamlet2(suite.streamlet.Streamlet2) ExecutableProgram(suite.util.RunUtil.ExecutableProgram) Summarize(suite.trade.analysis.Summarize) Set(java.util.Set) To(suite.util.To) Obj_Dbl(suite.primitive.DblPrimitives.Obj_Dbl) Serialize(suite.util.Serialize) Strategos(suite.trade.singlealloc.Strategos) Pair(suite.adt.pair.Pair) List(java.util.List) Trade(suite.trade.Trade) BackAllocConfiguration(suite.trade.backalloc.BackAllocConfiguration) Streamlet(suite.streamlet.Streamlet) Time(suite.trade.Time) BackAllocConfigurations(suite.trade.backalloc.BackAllocConfigurations) Configuration(suite.trade.data.Configuration) MathUtil(suite.math.MathUtil) Account(suite.trade.Account) DataSource(suite.trade.data.DataSource) Sink(suite.util.FunUtil.Sink) As(suite.streamlet.As) SingleAllocBackTest(suite.trade.singlealloc.SingleAllocBackTest) DblStreamlet(suite.primitive.streamlet.DblStreamlet) Asset(suite.trade.Asset) SmtpSslGmail(suite.smtp.SmtpSslGmail) TimeRange(suite.trade.TimeRange) SummarizeByStrategy(suite.trade.analysis.Summarize.SummarizeByStrategy) Account(suite.trade.Account) TimeRange(suite.trade.TimeRange) Trade(suite.trade.Trade) Simulate(suite.trade.backalloc.BackAllocTester.Simulate)

Example 2 with Trade

use of suite.trade.Trade in project suite by stupidsing.

the class Summarize method summarize_.

private // 
Summarize_ summarize_(// 
Streamlet<Trade> trades_, // 
Map<String, Float> priceBySymbol, Iterate<String> infoFun) {
    Streamlet<Trade> trades0 = trades_;
    Streamlet<Trade> trades1 = sellAll(trades0, priceBySymbol);
    Streamlet<String> details = // 
    Read.from2(// 
    Trade_.portfolio(trades0)).map((symbol, nShares) -> {
        Asset asset = cfg.queryCompany(symbol);
        float price = priceBySymbol.get(symbol);
        String info = infoFun.apply(symbol);
        return // 
        asset + ": " + price + " * " + // 
        nShares + " = " + // 
        ((long) (nShares * price)) + (info != null ? " \t(" + info + ")" : "");
    }).sort(// 
    Object_::compare).collect(As::streamlet);
    return new Summarize_(details, trades0, trades1);
}
Also used : Trade(suite.trade.Trade) As(suite.streamlet.As) Asset(suite.trade.Asset)

Example 3 with Trade

use of suite.trade.Trade 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)

Example 4 with Trade

use of suite.trade.Trade in project suite by stupidsing.

the class Summarize method summarize.

public <K> SummarizeByStrategy<K> summarize(Fun<Trade, K> fun) {
    Streamlet2<K, Summarize_> summaryByKey = // 
    trades.groupBy(fun, // 
    trades_ -> summarize_(trades_, priceBySymbol, s -> null)).filterKey(// 
    key -> key != null).collect(As::streamlet2);
    Map<String, Map<K, Integer>> nSharesByKeyBySymbol = // 
    summaryByKey.concatMap((key, summary) -> // 
    summary.account.portfolio().map(// 
    (symbol, n) -> Fixie.of(symbol, key, n))).groupBy(Fixie3::get0, fixies0 -> // 
    fixies0.groupBy(Fixie3::get1, fixies1 -> // 
    fixies1.map(Fixie3::get2).uniqueResult()).toMap()).toMap();
    Map<String, Float> acquiredPrices = trades.collect(Trade_::collectBrokeredTrades).collect(Trade_::collectAcquiredPrices);
    Time now = Time.now();
    Summarize_ overall = summarize_(trades, priceBySymbol, symbol -> {
        boolean isMarketOpen = // 
        false || // 
        HkexUtil.isMarketOpen(now) || HkexUtil.isMarketOpen(now.addHours(1));
        DataSource ds = cfg.dataSource(symbol);
        // acquisition price
        float price0 = acquiredPrices.get(symbol);
        // previous close
        float price1 = ds.get(isMarketOpen ? -1 : -2).t1;
        // now
        float pricex = isMarketOpen ? priceBySymbol.get(symbol) : ds.get(-1).t1;
        String keys = // 
        Read.from2(// 
        nSharesByKeyBySymbol.getOrDefault(symbol, Map.ofEntries())).keys().map(// 
        Object::toString).sort(// 
        String_::compare).collect(As.joinedBy("/"));
        return // 
        percent(price1, pricex) + ", " + // 
        percent(price0, pricex) + (!keys.isEmpty() ? ", " + keys : "");
    });
    Map<K, String> outByKey = summaryByKey.mapValue(Summarize_::out0).toMap();
    StringBuilder sb = new StringBuilder();
    Sink<String> log = sb::append;
    for (Entry<K, String> e : outByKey.entrySet()) log.sink("\nFor strategy " + e.getKey() + ":" + e.getValue());
    log.sink(FormatUtil.tablize("\nOverall:\t" + Time.now().ymdHms() + overall.out1()));
    // profit and loss
    Map<K, Double> pnlByKey = // 
    sellAll(trades, priceBySymbol).groupBy(fun, // 
    t -> (double) Account.ofHistory(t).cash()).toMap();
    return new SummarizeByStrategy<>(sb.toString(), overall.account, pnlByKey);
}
Also used : Read(suite.streamlet.Read) Trade_(suite.trade.Trade_) Fun(suite.util.FunUtil.Fun) Yahoo(suite.trade.data.Yahoo) String_(suite.util.String_) Dbl_Dbl(suite.primitive.Dbl_Dbl) Map(java.util.Map) Fixie3(suite.adt.pair.Fixie_.Fixie3) LngFltPair(suite.primitive.adt.pair.LngFltPair) TransactionSummary(suite.trade.Account.TransactionSummary) Streamlet2(suite.streamlet.Streamlet2) HkexUtil(suite.trade.data.HkexUtil) Object_(suite.util.Object_) Hsbc(suite.trade.data.Broker.Hsbc) To(suite.util.To) Quant(ts.Quant) Iterate(suite.util.FunUtil.Iterate) Trade(suite.trade.Trade) Streamlet(suite.streamlet.Streamlet) Time(suite.trade.Time) Fixie(suite.adt.pair.Fixie) Configuration(suite.trade.data.Configuration) Account(suite.trade.Account) Entry(java.util.Map.Entry) DataSource(suite.trade.data.DataSource) Sink(suite.util.FunUtil.Sink) As(suite.streamlet.As) Asset(suite.trade.Asset) FormatUtil(suite.util.FormatUtil) Time(suite.trade.Time) DataSource(suite.trade.data.DataSource) Trade_(suite.trade.Trade_) As(suite.streamlet.As) Map(java.util.Map)

Example 5 with Trade

use of suite.trade.Trade in project suite by stupidsing.

the class DailyMain method mamr.

// moving average mean reversion
private Result mamr(float factor) {
    String tag = "mamr";
    int nHoldDays = 8;
    Streamlet<Asset> assets = cfg.queryCompanies();
    BuySellStrategy strategy = new Strategos().movingAvgMeanReverting(64, nHoldDays, .15f);
    // pre-fetch quotes
    cfg.quote(assets.map(asset -> asset.symbol).toSet());
    // identify stocks that are mean-reverting
    Map<String, Boolean> backTestBySymbol = // 
    SerializedStoreCache.of(// 
    serialize.mapOfString(serialize.boolean_)).get(getClass().getSimpleName() + ".backTestBySymbol", () -> // 
    assets.map2(stock -> stock.symbol, stock -> {
        try {
            TimeRange period = TimeRange.threeYears();
            DataSource ds = cfg.dataSource(stock.symbol, period).range(period).validate();
            SingleAllocBackTest backTest = SingleAllocBackTest.test(ds, strategy);
            return MathUtil.isPositive(backTest.account.cash());
        } catch (Exception ex) {
            LogUtil.warn(ex + " for " + stock);
            return false;
        }
    }).toMap());
    TimeRange period = TimeRange.daysBefore(128);
    List<Trade> trades = new ArrayList<>();
    // capture signals
    for (Asset asset : assets) {
        String symbol = asset.symbol;
        if (backTestBySymbol.get(symbol))
            try {
                DataSource ds = cfg.dataSource(symbol, period).validate();
                float[] prices = ds.prices;
                int last = prices.length - 1;
                float latestPrice = prices[last];
                int signal = strategy.analyze(prices).get(last);
                int nShares = signal * asset.lotSize * Math.round(factor / nHoldDays / (asset.lotSize * latestPrice));
                Trade trade = Trade.of(nShares, symbol, latestPrice);
                if (signal != 0)
                    trades.add(trade);
            } catch (Exception ex) {
                LogUtil.warn(ex.getMessage() + " in " + asset);
            }
    }
    return new Result(tag, trades);
}
Also used : ArrayList(java.util.ArrayList) DataSource(suite.trade.data.DataSource) TimeRange(suite.trade.TimeRange) Trade(suite.trade.Trade) Asset(suite.trade.Asset) Strategos(suite.trade.singlealloc.Strategos) SingleAllocBackTest(suite.trade.singlealloc.SingleAllocBackTest) BuySellStrategy(suite.trade.singlealloc.BuySellStrategy)

Aggregations

Asset (suite.trade.Asset)7 Trade (suite.trade.Trade)7 DataSource (suite.trade.data.DataSource)6 ArrayList (java.util.ArrayList)5 Map (java.util.Map)5 As (suite.streamlet.As)5 Read (suite.streamlet.Read)5 Streamlet (suite.streamlet.Streamlet)5 Account (suite.trade.Account)5 Time (suite.trade.Time)5 Trade_ (suite.trade.Trade_)5 Configuration (suite.trade.data.Configuration)5 Sink (suite.util.FunUtil.Sink)5 List (java.util.List)4 Pair (suite.adt.pair.Pair)4 Streamlet2 (suite.streamlet.Streamlet2)4 TimeRange (suite.trade.TimeRange)4 BuySellStrategy (suite.trade.singlealloc.BuySellStrategy)4 SingleAllocBackTest (suite.trade.singlealloc.SingleAllocBackTest)4 Strategos (suite.trade.singlealloc.Strategos)4