Search in sources :

Example 11 with Streamlet

use of suite.streamlet.Streamlet 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 12 with Streamlet

use of suite.streamlet.Streamlet in project suite by stupidsing.

the class Google method quote_.

private synchronized Map<String, Float> quote_(Streamlet<String> symbols) {
    if (0 < symbols.size()) {
        URL url = To.url(// 
        "http://finance.google.com/finance/info?client=ig&q=HKEX%3A" + symbols.sort(Object_::compare).map(this::fromSymbol).collect(As.joinedBy(",")));
        JsonNode json = Rethrow.ex(() -> {
            try (InputStream is = HttpUtil.get(url).out.collect(To::inputStream)) {
                for (int i = 0; i < 4; i++) is.read();
                return mapper.readTree(is);
            }
        });
        return // 
        Read.from(// 
        json).map2(json_ -> toSymbol(json_.get("t").textValue()), // 
        json_ -> Float.parseFloat(json_.get("l").textValue().replace(",", ""))).toMap();
    } else
        return new HashMap<>();
}
Also used : HttpUtil(suite.http.HttpUtil) Outlet(suite.streamlet.Outlet) Read(suite.streamlet.Read) Singleton(suite.node.util.Singleton) Object_(suite.util.Object_) URL(java.net.URL) Trade_(suite.trade.Trade_) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Set(java.util.Set) HashMap(java.util.HashMap) To(suite.util.To) ArrayList(java.util.ArrayList) List(java.util.List) Streamlet(suite.streamlet.Streamlet) Fixie(suite.adt.pair.Fixie) Rethrow(suite.util.Rethrow) Map(java.util.Map) Fixie3(suite.adt.pair.Fixie_.Fixie3) As(suite.streamlet.As) JsonNode(com.fasterxml.jackson.databind.JsonNode) Collections(java.util.Collections) Fail(suite.util.Fail) InputStream(java.io.InputStream) InputStream(java.io.InputStream) JsonNode(com.fasterxml.jackson.databind.JsonNode) To(suite.util.To) Object_(suite.util.Object_) URL(java.net.URL)

Example 13 with Streamlet

use of suite.streamlet.Streamlet 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 14 with Streamlet

use of suite.streamlet.Streamlet 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 15 with Streamlet

use of suite.streamlet.Streamlet in project suite by stupidsing.

the class ParseUtil method split.

public static Streamlet<String> split(String in, String name) {
    char[] chars = in.toCharArray();
    int length = chars.length;
    return new Streamlet<>(() -> Outlet.of(new Source<String>() {

        private int pos = 0;

        public String source() {
            if (pos < length) {
                Segment segment = searchPosition(chars, Segment.of(pos, length), name, Assoc.LEFT, true);
                int pos0 = pos;
                int end;
                if (segment != null) {
                    end = segment.start;
                    pos = segment.end;
                } else
                    end = pos = length;
                return new String(chars, pos0, end);
            } else
                return null;
        }
    }));
}
Also used : Streamlet(suite.streamlet.Streamlet) Source(suite.util.FunUtil.Source) Segment(suite.text.Segment)

Aggregations

Streamlet (suite.streamlet.Streamlet)17 Read (suite.streamlet.Read)13 List (java.util.List)11 Map (java.util.Map)10 As (suite.streamlet.As)10 To (suite.util.To)9 Set (java.util.Set)8 Pair (suite.adt.pair.Pair)8 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)7 Time (suite.trade.Time)7 InputStream (java.io.InputStream)6 TimeRange (suite.trade.TimeRange)6 Fail (suite.util.Fail)6 String_ (suite.util.String_)6 Streamlet2 (suite.streamlet.Streamlet2)5 Trade_ (suite.trade.Trade_)5 JsonNode (com.fasterxml.jackson.databind.JsonNode)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)4 URL (java.net.URL)4