Search in sources :

Example 6 with Trade_

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

the class WalkForwardRecorderMain method run.

@Override
protected boolean run(String[] args) {
    Streamlet<Asset> assets = cfg.queryCompaniesByMarketCap(Time.now());
    float fund0 = 1000000f;
    Trade_.isCacheQuotes = false;
    Trade_.isShortSell = true;
    Trade_.leverageAmount = fund0;
    if (Boolean.FALSE) {
        // record
        String ts = Time.now().ymdHms().replace("-", "").replace(" ", "-").replace(":", "");
        String filename = "wfa." + ts + ".csv";
        Schedule schedule = // 
        Schedule.ofRepeat(5, () -> {
            String ymdHms = Time.now().ymdHms();
            Map<String, Float> priceBySymbol = cfg.quote(assets.map(asset -> asset.symbol).toSet());
            try (OutputStream os = // 
            Files.newOutputStream(// 
            HomeDir.resolve(filename), // 
            StandardOpenOption.APPEND, // 
            StandardOpenOption.CREATE, // 
            StandardOpenOption.WRITE);
                PrintWriter bw = new PrintWriter(os)) {
                for (Entry<String, Float> e : priceBySymbol.entrySet()) bw.println(ymdHms + ", " + e.getKey() + ", " + e.getValue());
            } catch (IOException ex) {
                Fail.t(ex);
            }
        });
        Scheduler.of(schedule.filterTime(dt -> HkexUtil.isMarketOpen(Time.of(dt)))).run();
    } else {
        // replay
        String ts = "20170612-092616";
        String filename = "wfa." + ts + ".csv";
        Map<Time, Map<String, Float>> data = new TreeMap<>();
        try (// 
        InputStream is = Files.newInputStream(HomeDir.resolve(filename));
            // 
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr)) {
            while (br.ready()) {
                String[] array = br.readLine().split(",");
                Time time = Time.of(array[0].trim());
                String symbol = array[1].trim();
                float price = Float.parseFloat(array[2].trim());
                data.computeIfAbsent(time, s -> new HashMap<>()).put(symbol, price);
            }
        } catch (IOException ex) {
            Fail.t(ex);
        }
        WalkForwardAllocConfiguration wfac = new // 
        WalkForwardAllocConfiguration(// 
        cfg.queryCompaniesByMarketCap(Time.now()), bag.rsi.unleverage().walkForwardAllocator());
        WalkForwardAllocTester tester = new WalkForwardAllocTester(cfg, wfac.assets, fund0, wfac.walkForwardAllocator);
        for (Entry<Time, Map<String, Float>> e : data.entrySet()) System.out.println(tester.tick(e.getKey(), e.getValue()));
        System.out.println(tester.conclusion());
    }
    return true;
}
Also used : WalkForwardAllocTester(suite.trade.walkforwardalloc.WalkForwardAllocTester) Schedule(suite.os.Schedule) Trade_(suite.trade.Trade_) HashMap(java.util.HashMap) Scheduler(suite.os.Scheduler) HomeDir(suite.util.HomeDir) RunUtil(suite.util.RunUtil) ConfigurationImpl(suite.trade.data.ConfigurationImpl) Map(java.util.Map) OutputStream(java.io.OutputStream) PrintWriter(java.io.PrintWriter) HkexUtil(suite.trade.data.HkexUtil) Files(java.nio.file.Files) ExecutableProgram(suite.util.RunUtil.ExecutableProgram) StandardOpenOption(java.nio.file.StandardOpenOption) IOException(java.io.IOException) WalkForwardAllocConfiguration(suite.trade.walkforwardalloc.WalkForwardAllocConfiguration) InputStreamReader(java.io.InputStreamReader) Streamlet(suite.streamlet.Streamlet) Time(suite.trade.Time) TreeMap(java.util.TreeMap) Configuration(suite.trade.data.Configuration) Entry(java.util.Map.Entry) BufferedReader(java.io.BufferedReader) Asset(suite.trade.Asset) BackAllocatorGeneral(suite.trade.backalloc.strategy.BackAllocatorGeneral) Fail(suite.util.Fail) InputStream(java.io.InputStream) InputStreamReader(java.io.InputStreamReader) HashMap(java.util.HashMap) WalkForwardAllocTester(suite.trade.walkforwardalloc.WalkForwardAllocTester) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) Time(suite.trade.Time) IOException(java.io.IOException) TreeMap(java.util.TreeMap) WalkForwardAllocConfiguration(suite.trade.walkforwardalloc.WalkForwardAllocConfiguration) Schedule(suite.os.Schedule) BufferedReader(java.io.BufferedReader) Asset(suite.trade.Asset) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) PrintWriter(java.io.PrintWriter)

Example 7 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 8 with Trade_

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

the class DailyMain method sellForEarn.

// some orders caused by stupid bugs. need to sell those at suitable times.
private Result sellForEarn(String tag) {
    Streamlet<Trade> history = cfg.queryHistory().filter(r -> String_.equals(r.strategy, tag));
    Account account = Account.ofPortfolio(history);
    Map<String, Float> faceValueBySymbol = // 
    history.groupBy(record -> record.symbol, // 
    rs -> (float) Read.from(rs).toDouble(Obj_Dbl.sum(Trade::amount))).toMap();
    List<Trade> trades = // 
    account.portfolio().map((symbol, sell) -> {
        double targetPrice = (1d + 3 * Trade_.riskFreeInterestRate) * faceValueBySymbol.get(symbol) / sell;
        return Trade.of(-sell, symbol, (float) targetPrice);
    }).toList();
    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) Trade(suite.trade.Trade) Account(suite.trade.Account)

Example 9 with Trade_

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

the class DailyMain method run.

@Override
protected boolean run(String[] args) {
    Trade_.blackList = Set_.union(Trade_.blackList, blackList);
    String sellPool = "sellpool";
    String ymd = Time.now().ymd();
    String td = ymd + "#";
    // perform systematic trading
    List<Result> results = // 
    List.of(// 
    alloc(bacs.pair_bb, 66666f), // 
    alloc("bug", bacs.bac_sell, 0f), // 
    alloc(bacs.pair_donchian, 100000f), // 
    alloc(bacs.pair_ema, 0f), // 
    mamr(50000f), // 
    alloc(bacs.pair_pmamr, 150000f), // 
    alloc(bacs.pair_pmamr2, 366666f), // 
    alloc(bacs.pair_pmmmr, 80000f), // 
    alloc(bacs.pair_revco, 0f), // 
    alloc(bacs.pair_tma, 0f), alloc(sellPool, bacs.bac_sell, 0f));
    // unused strategies
    if (Boolean.FALSE) {
        alloc(bacs.pair_donchian, 100000f);
        pairs(0f, "0341.HK", "0052.HK");
        sellForEarn(sellPool);
    }
    SummarizeByStrategy<Object> sbs = Summarize.of(cfg).summarize();
    Streamlet2<String, Trade> strategyTrades = // 
    Read.from(// 
    results).concatMap2(// 
    result -> Read.from(result.trades).map2(trade -> result.strategy, trade -> trade)).filterValue(// 
    trade -> trade.buySell != 0).collect(As::streamlet2);
    Streamlet2<String, Trade> requestTrades = strategyTrades.filterKey(strategy -> !String_.equals(strategy, sellPool));
    DblStreamlet amounts = strategyTrades.values().collect(Obj_Dbl.lift(Trade::amount));
    double buys_ = amounts.filter(amount -> 0d < amount).sum();
    double sells = amounts.filter(amount -> amount < 0d).sum();
    sb.append(// 
    sbs.log + "\n" + // 
    sbs.pnlByKey + "\n" + // 
    strategyTrades.sortBy(// 
    (strategy, trade) -> trade.amount()).map((strategy, trade) -> // 
    "\n" + // 
    (0 <= trade.buySell ? "BUY^" : "SELL") + " SIGNAL(" + strategy + ")" + // 
    trade + " = " + // 
    To.string(trade.amount())).collect(// 
    As::joined) + // 
    "\n" + // 
    "\nBUY REQUESTS" + // 
    requestTrades.filterValue(// 
    trade -> 0 < trade.buySell).map((strategy, t) -> // 
    "" + "\n" + // 
    Trade.of(td, -t.buySell, t.symbol, t.price, sellPool).record() + "\n" + // 
    Trade.of(td, +t.buySell, t.symbol, t.price, strategy).record()).collect(// 
    As::joined) + // 
    "\n" + // 
    "\nSELL REQUESTS" + // 
    requestTrades.filterValue(// 
    trade -> trade.buySell < 0).map((strategy, t) -> // 
    "" + "\n" + // 
    Trade.of(td, +t.buySell, t.symbol, t.price, strategy).record() + "\n" + // 
    Trade.of(td, -t.buySell, t.symbol, t.price, sellPool).record()).collect(// 
    As::joined) + // 
    "\n" + "\nTOTAL BUYS_ = " + // 
    To.string(buys_) + "\nTOTAL SELLS = " + // 
    To.string(sells) + // 
    "\n" + // 
    "\nSUGGESTIONS" + // 
    "\n- check your balance" + // 
    "\n- sort the orders and get away the small ones" + // 
    "\n- get away the stocks after ex-date" + "\n- sell mamr and " + // 
    sellPool + // 
    "\n- for mamr, check actual execution using SingleAllocBackTestTest.testBackTestHkexDetails()" + "\n");
    String result = sb.toString();
    LogUtil.info(result);
    SmtpSslGmail smtp = new SmtpSslGmail();
    smtp.send(null, getClass().getName(), result);
    return true;
}
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) Trade(suite.trade.Trade) As(suite.streamlet.As) DblStreamlet(suite.primitive.streamlet.DblStreamlet) SmtpSslGmail(suite.smtp.SmtpSslGmail)

Aggregations

Trade_ (suite.trade.Trade_)9 Asset (suite.trade.Asset)8 Time (suite.trade.Time)8 Configuration (suite.trade.data.Configuration)8 Map (java.util.Map)7 Read (suite.streamlet.Read)7 Streamlet (suite.streamlet.Streamlet)7 DataSource (suite.trade.data.DataSource)7 To (suite.util.To)7 Pair (suite.adt.pair.Pair)6 As (suite.streamlet.As)6 TimeRange (suite.trade.TimeRange)6 ConfigurationImpl (suite.trade.data.ConfigurationImpl)6 Streamlet2 (suite.streamlet.Streamlet2)5 Account (suite.trade.Account)5 Trade (suite.trade.Trade)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4 LogUtil (suite.os.LogUtil)4 Sink (suite.util.FunUtil.Sink)4