Search in sources :

Example 1 with BuySellStrategy

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

ArrayList (java.util.ArrayList)1 Asset (suite.trade.Asset)1 TimeRange (suite.trade.TimeRange)1 Trade (suite.trade.Trade)1 DataSource (suite.trade.data.DataSource)1 BuySellStrategy (suite.trade.singlealloc.BuySellStrategy)1 SingleAllocBackTest (suite.trade.singlealloc.SingleAllocBackTest)1 Strategos (suite.trade.singlealloc.Strategos)1