Search in sources :

Example 6 with Asset

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

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

the class BackAllocBackTestTest method testBackTestSingle.

@Test
public void testBackTestSingle() {
    Asset asset = cfg.queryCompany("0945.HK");
    BackAllocator backAllocator = new MovingAvgMeanReversionBackAllocator().backAllocator();
    assertGrowth(out(runner.backTest(backAllocator, period, Read.each(asset))));
}
Also used : MovingAvgMeanReversionBackAllocator(suite.trade.backalloc.strategy.MovingAvgMeanReversionBackAllocator) PmamrBackAllocator(suite.trade.backalloc.strategy.PmamrBackAllocator) Asset(suite.trade.Asset) MovingAvgMeanReversionBackAllocator(suite.trade.backalloc.strategy.MovingAvgMeanReversionBackAllocator) Test(org.junit.Test)

Example 8 with Asset

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

the class HkexTest method testList.

@Test
public void testList() {
    List<Asset> companies = hkex.queryCompanies().toList();
    System.out.println(companies);
    for (Asset company : companies) System.out.println(// 
    "+ \"\\n" + company.symbol + "|" + // 
    company.name + "|" + // 
    company.lotSize + "|" + // 
    company.marketCap + "\" //");
    String name = // 
    Read.from(// 
    companies).filter(// 
    fixie -> String_.equals(fixie.symbol, "0005.HK")).uniqueResult().name;
    assertTrue(name.equals("HSBC Holdings plc"));
}
Also used : Asset(suite.trade.Asset) Test(org.junit.Test)

Example 9 with Asset

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

Example 10 with Asset

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

the class DailyMain method pairs.

public BackAllocConfiguration pairs(String symbol0, String symbol1) {
    Streamlet<Asset> assets = Read.each(symbol0, symbol1).map(cfg::queryCompany).collect(As::streamlet);
    BackAllocator backAllocator = BackAllocatorOld.me.pairs(cfg, symbol0, symbol1).unleverage();
    return new BackAllocConfiguration(time -> assets, backAllocator);
}
Also used : BackAllocator(suite.trade.backalloc.BackAllocator) As(suite.streamlet.As) Asset(suite.trade.Asset) BackAllocConfiguration(suite.trade.backalloc.BackAllocConfiguration)

Aggregations

Asset (suite.trade.Asset)10 As (suite.streamlet.As)5 Streamlet (suite.streamlet.Streamlet)4 Map (java.util.Map)3 Read (suite.streamlet.Read)3 Time (suite.trade.Time)3 TimeRange (suite.trade.TimeRange)3 Trade (suite.trade.Trade)3 Trade_ (suite.trade.Trade_)3 BackAllocConfiguration (suite.trade.backalloc.BackAllocConfiguration)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Set (java.util.Set)2 Test (org.junit.Test)2 Pair (suite.adt.pair.Pair)2 SerializedStoreCache (suite.os.SerializedStoreCache)2 Streamlet2 (suite.streamlet.Streamlet2)2