Search in sources :

Example 6 with Time

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

the class BackTestMain method run.

@Override
protected boolean run(String[] args) {
    // BEGIN
    // END
    String arg0 = 0 < args.length ? args[0] : "";
    String arg1 = 1 < args.length ? args[1] : "";
    String arg2 = 2 < args.length ? args[2] : "";
    Streamlet<String> strategyMatches = !arg0.isEmpty() ? Read.from(arg0.split(",")) : null;
    Streamlet<Integer> years = !arg1.isEmpty() ? // 
    Read.from(// 
    arg1.split(",")).concatMap(s -> {
        Pair<String, String> pair = ParseUtil.search(s, "-", Assoc.RIGHT);
        return // 
        pair != null ? // 
        Ints_.range(Integer.valueOf(pair.t0), Integer.valueOf(pair.t1)).map(i -> i) : Read.each(Integer.valueOf(s));
    }) : // 
    Ints_.range(2007, Trade_.thisYear).map(i -> i);
    Fun<Time, Streamlet<Asset>> fun = // 
    !arg2.isEmpty() ? // 
    time -> Read.from(arg2.split(",")).map(cfg::queryCompany).collect(As::streamlet) : cfg::queryCompaniesByMarketCap;
    BackAllocConfigurations bac_ = new BackAllocConfigurations(cfg, fun);
    Streamlet2<String, BackAllocConfiguration> bacByTag = bac_.bacs().bacByName;
    Streamlet2<String, Simulate> simulationByKey = // 
    bacByTag.filterKey(// 
    n -> strategyMatches == null || strategyMatches.isAny(sm -> Wildcard.match(sm, n) != null)).map(// 
    Pair::of).join2(// 
    years.sort(Object_::compare).map(TimeRange::ofYear)).map2((pair, period) -> pair.t0, (pair, period) -> {
        BackAllocConfiguration bac = pair.t1;
        Streamlet<Asset> assets = bac.assetsFun.apply(period.from);
        return runner.backTest(bac.backAllocator, period, assets);
    }).collect(As::streamlet2);
    String content0 = // 
    Read.bytes(// 
    Paths.get("src/main/java/" + getClass().getName().replace('.', '/') + ".java")).collect(// 
    As::utf8decode).map(// 
    Chars::toString).collect(As::joined);
    String content1 = ParseUtil.fit(content0, "// BEGIN", "// END")[1];
    System.out.println(content1);
    System.out.println(runner.conclude(simulationByKey));
    return true;
}
Also used : Read(suite.streamlet.Read) Streamlet2(suite.streamlet.Streamlet2) Object_(suite.util.Object_) Trade_(suite.trade.Trade_) ExecutableProgram(suite.util.RunUtil.ExecutableProgram) Chars(suite.primitive.Chars) Fun(suite.util.FunUtil.Fun) RunUtil(suite.util.RunUtil) Wildcard(suite.parser.Wildcard) ParseUtil(suite.util.ParseUtil) Pair(suite.adt.pair.Pair) ConfigurationImpl(suite.trade.data.ConfigurationImpl) BackAllocConfiguration(suite.trade.backalloc.BackAllocConfiguration) Streamlet(suite.streamlet.Streamlet) Time(suite.trade.Time) BackAllocConfigurations(suite.trade.backalloc.BackAllocConfigurations) Paths(java.nio.file.Paths) Configuration(suite.trade.data.Configuration) As(suite.streamlet.As) Simulate(suite.trade.backalloc.BackAllocTester.Simulate) Ints_(suite.primitive.Ints_) Asset(suite.trade.Asset) Assoc(suite.node.io.Operator.Assoc) TimeRange(suite.trade.TimeRange) Time(suite.trade.Time) Object_(suite.util.Object_) As(suite.streamlet.As) Simulate(suite.trade.backalloc.BackAllocTester.Simulate) BackAllocConfigurations(suite.trade.backalloc.BackAllocConfigurations) Streamlet(suite.streamlet.Streamlet) BackAllocConfiguration(suite.trade.backalloc.BackAllocConfiguration) Pair(suite.adt.pair.Pair)

Example 7 with Time

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

the class HongKongGovernment method queryWeather.

public Map<String, DataSource> queryWeather() {
    long t0 = Time.of(2000, 1, 1).epochSec();
    long tx = Time.today().epochSec();
    LongsBuilder ts = new LongsBuilder();
    FloatsBuilder fs0 = new FloatsBuilder();
    FloatsBuilder fs1 = new FloatsBuilder();
    for (long t = t0; t < tx; t += 86400l) {
        Time time = Time.ofEpochSec(t);
        String html = // 
        Singleton.me.storeCache.http(// 
        "http://www.hko.gov.hk/cgi-bin/hko/yes.pl" + "?year=" + // 
        time.year() + "&month=" + // 
        time.month() + "&day=" + // 
        time.dayOfMonth() + // 
        "&language=english&B1=Confirm#").collect(As::string);
        String data = ParseUtil.fit(html, "<pre>", "</pre>")[1];
        ts.append(t);
        fs0.append(getFloatValue(data, "Maximum Air Temperature", "C"));
        fs1.append(getFloatValue(data, "Rainfall", "mm"));
    }
    long[] ts_ = ts.toLongs().toArray();
    return // 
    Map.ofEntries(// 
    entry("hko.TEMP", DataSource.of(ts_, fs0.toFloats().toArray())), entry("hko.RAIN", DataSource.of(ts_, fs1.toFloats().toArray())));
}
Also used : As(suite.streamlet.As) LongsBuilder(suite.primitive.Longs.LongsBuilder) Time(suite.trade.Time) FloatsBuilder(suite.primitive.Floats.FloatsBuilder)

Example 8 with Time

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

the class Yahoo method tableUrl.

public String tableUrl(String symbol, TimeRange period) {
    Time frDate = period.from;
    Time toDate = period.to;
    return // 
    "https://chart.finance.yahoo.com/table.csv" + "?s=" + // 
    encode(symbol) + "&a=" + frDate.month() + "&b=" + frDate.dow() + "&c=" + // 
    frDate.year() + "&d=" + toDate.month() + "&e=" + toDate.dow() + "&f=" + // 
    toDate.year() + // 
    "&g=d" + "&ignore=.csv";
}
Also used : Time(suite.trade.Time)

Example 9 with Time

use of suite.trade.Time 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 10 with Time

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

Aggregations

Time (suite.trade.Time)13 Read (suite.streamlet.Read)6 Streamlet (suite.streamlet.Streamlet)6 Map (java.util.Map)5 As (suite.streamlet.As)5 Asset (suite.trade.Asset)5 Trade_ (suite.trade.Trade_)5 Configuration (suite.trade.data.Configuration)5 HashMap (java.util.HashMap)4 List (java.util.List)4 Entry (java.util.Map.Entry)4 Pair (suite.adt.pair.Pair)4 Streamlet2 (suite.streamlet.Streamlet2)4 DataSource (suite.trade.data.DataSource)4 Object_ (suite.util.Object_)4 AlignKeyDataSource (suite.trade.data.DataSource.AlignKeyDataSource)3 Fail (suite.util.Fail)3 Fun (suite.util.FunUtil.Fun)3 InputStream (java.io.InputStream)2 Files (java.nio.file.Files)2