Search in sources :

Example 6 with TimeSeries

use of org.ta4j.core.TimeSeries in project ta4j by ta4j.

the class StrategyAnalysis method main.

public static void main(String[] args) {
    // Getting the time series
    TimeSeries series = CsvTradesLoader.loadBitstampSeries();
    // Building the trading strategy
    Strategy strategy = MovingMomentumStrategy.buildStrategy(series);
    // Running the strategy
    TimeSeriesManager seriesManager = new TimeSeriesManager(series);
    TradingRecord tradingRecord = seriesManager.run(strategy);
    /*
          Analysis criteria
         */
    // Total profit
    TotalProfitCriterion totalProfit = new TotalProfitCriterion();
    System.out.println("Total profit: " + totalProfit.calculate(series, tradingRecord));
    // Number of bars
    System.out.println("Number of bars: " + new NumberOfBarsCriterion().calculate(series, tradingRecord));
    // Average profit (per bar)
    System.out.println("Average profit (per bar): " + new AverageProfitCriterion().calculate(series, tradingRecord));
    // Number of trades
    System.out.println("Number of trades: " + new NumberOfTradesCriterion().calculate(series, tradingRecord));
    // Profitable trades ratio
    System.out.println("Profitable trades ratio: " + new AverageProfitableTradesCriterion().calculate(series, tradingRecord));
    // Maximum drawdown
    System.out.println("Maximum drawdown: " + new MaximumDrawdownCriterion().calculate(series, tradingRecord));
    // Reward-risk ratio
    System.out.println("Reward-risk ratio: " + new RewardRiskRatioCriterion().calculate(series, tradingRecord));
    // Total transaction cost
    System.out.println("Total transaction cost (from $1000): " + new LinearTransactionCostCriterion(1000, 0.005).calculate(series, tradingRecord));
    // Buy-and-hold
    System.out.println("Buy-and-hold: " + new BuyAndHoldCriterion().calculate(series, tradingRecord));
    // Total profit vs buy-and-hold
    System.out.println("Custom strategy profit vs buy-and-hold strategy profit: " + new VersusBuyAndHoldCriterion(totalProfit).calculate(series, tradingRecord));
}
Also used : TimeSeries(org.ta4j.core.TimeSeries) TradingRecord(org.ta4j.core.TradingRecord) TimeSeriesManager(org.ta4j.core.TimeSeriesManager) MovingMomentumStrategy(ta4jexamples.strategies.MovingMomentumStrategy) Strategy(org.ta4j.core.Strategy)

Example 7 with TimeSeries

use of org.ta4j.core.TimeSeries in project ta4j by ta4j.

the class CandlestickChart method createAdditionalDataset.

/**
 * Builds an additional JFreeChart dataset from a ta4j time series.
 * @param series a time series
 * @return an additional dataset
 */
private static TimeSeriesCollection createAdditionalDataset(TimeSeries series) {
    ClosePriceIndicator indicator = new ClosePriceIndicator(series);
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    org.jfree.data.time.TimeSeries chartTimeSeries = new org.jfree.data.time.TimeSeries("Btc price");
    for (int i = 0; i < series.getBarCount(); i++) {
        Bar bar = series.getBar(i);
        chartTimeSeries.add(new Second(new Date(bar.getEndTime().toEpochSecond() * 1000)), indicator.getValue(i).toDouble());
    }
    dataset.addSeries(chartTimeSeries);
    return dataset;
}
Also used : Bar(org.ta4j.core.Bar) TimeSeries(org.ta4j.core.TimeSeries) Second(org.jfree.data.time.Second) TimeSeriesCollection(org.jfree.data.time.TimeSeriesCollection) ClosePriceIndicator(org.ta4j.core.indicators.helpers.ClosePriceIndicator) Date(java.util.Date)

Example 8 with TimeSeries

use of org.ta4j.core.TimeSeries in project ta4j by ta4j.

the class CandlestickChart method main.

public static void main(String[] args) {
    /*
          Getting time series
         */
    TimeSeries series = CsvTradesLoader.loadBitstampSeries();
    /*
          Creating the OHLC dataset
         */
    OHLCDataset ohlcDataset = createOHLCDataset(series);
    /*
          Creating the additional dataset
         */
    TimeSeriesCollection xyDataset = createAdditionalDataset(series);
    /*
          Creating the chart
         */
    JFreeChart chart = ChartFactory.createCandlestickChart("Bitstamp BTC price", "Time", "USD", ohlcDataset, true);
    // Candlestick rendering
    CandlestickRenderer renderer = new CandlestickRenderer();
    renderer.setAutoWidthMethod(CandlestickRenderer.WIDTHMETHOD_SMALLEST);
    XYPlot plot = chart.getXYPlot();
    plot.setRenderer(renderer);
    // Additional dataset
    int index = 1;
    plot.setDataset(index, xyDataset);
    plot.mapDatasetToRangeAxis(index, 0);
    XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer(true, false);
    renderer2.setSeriesPaint(index, Color.blue);
    plot.setRenderer(index, renderer2);
    // Misc
    plot.setRangeGridlinePaint(Color.lightGray);
    plot.setBackgroundPaint(Color.white);
    NumberAxis numberAxis = (NumberAxis) plot.getRangeAxis();
    numberAxis.setAutoRangeIncludesZero(false);
    plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
    /*
          Displaying the chart
         */
    displayChart(chart);
}
Also used : OHLCDataset(org.jfree.data.xy.OHLCDataset) TimeSeries(org.ta4j.core.TimeSeries) NumberAxis(org.jfree.chart.axis.NumberAxis) XYPlot(org.jfree.chart.plot.XYPlot) TimeSeriesCollection(org.jfree.data.time.TimeSeriesCollection) XYLineAndShapeRenderer(org.jfree.chart.renderer.xy.XYLineAndShapeRenderer) CandlestickRenderer(org.jfree.chart.renderer.xy.CandlestickRenderer) JFreeChart(org.jfree.chart.JFreeChart)

Example 9 with TimeSeries

use of org.ta4j.core.TimeSeries in project ta4j by ta4j.

the class IndicatorsToChart method buildChartTimeSeries.

/**
 * Builds a JFreeChart time series from a Ta4j time series and an indicator.
 * @param barseries the ta4j time series
 * @param indicator the indicator
 * @param name the name of the chart time series
 * @return the JFreeChart time series
 */
private static org.jfree.data.time.TimeSeries buildChartTimeSeries(TimeSeries barseries, Indicator<Decimal> indicator, String name) {
    org.jfree.data.time.TimeSeries chartTimeSeries = new org.jfree.data.time.TimeSeries(name);
    for (int i = 0; i < barseries.getBarCount(); i++) {
        Bar bar = barseries.getBar(i);
        chartTimeSeries.add(new Day(Date.from(bar.getEndTime().toInstant())), indicator.getValue(i).doubleValue());
    }
    return chartTimeSeries;
}
Also used : Bar(org.ta4j.core.Bar) TimeSeries(org.ta4j.core.TimeSeries) Day(org.jfree.data.time.Day)

Example 10 with TimeSeries

use of org.ta4j.core.TimeSeries in project ta4j by ta4j.

the class IndicatorsToCsv method main.

public static void main(String[] args) {
    /*
          Getting time series
         */
    TimeSeries series = CsvTradesLoader.loadBitstampSeries();
    /*
          Creating indicators
         */
    // Close price
    ClosePriceIndicator closePrice = new ClosePriceIndicator(series);
    // Typical price
    TypicalPriceIndicator typicalPrice = new TypicalPriceIndicator(series);
    // Price variation
    PriceVariationIndicator priceVariation = new PriceVariationIndicator(series);
    // Simple moving averages
    SMAIndicator shortSma = new SMAIndicator(closePrice, 8);
    SMAIndicator longSma = new SMAIndicator(closePrice, 20);
    // Exponential moving averages
    EMAIndicator shortEma = new EMAIndicator(closePrice, 8);
    EMAIndicator longEma = new EMAIndicator(closePrice, 20);
    // Percentage price oscillator
    PPOIndicator ppo = new PPOIndicator(closePrice, 12, 26);
    // Rate of change
    ROCIndicator roc = new ROCIndicator(closePrice, 100);
    // Relative strength index
    RSIIndicator rsi = new RSIIndicator(closePrice, 14);
    // Williams %R
    WilliamsRIndicator williamsR = new WilliamsRIndicator(series, 20);
    // Average true range
    ATRIndicator atr = new ATRIndicator(series, 20);
    // Standard deviation
    StandardDeviationIndicator sd = new StandardDeviationIndicator(closePrice, 14);
    /*
          Building header
         */
    StringBuilder sb = new StringBuilder("timestamp,close,typical,variation,sma8,sma20,ema8,ema20,ppo,roc,rsi,williamsr,atr,sd\n");
    /*
          Adding indicators values
         */
    final int nbBars = series.getBarCount();
    for (int i = 0; i < nbBars; i++) {
        sb.append(series.getBar(i).getEndTime()).append(',').append(closePrice.getValue(i)).append(',').append(typicalPrice.getValue(i)).append(',').append(priceVariation.getValue(i)).append(',').append(shortSma.getValue(i)).append(',').append(longSma.getValue(i)).append(',').append(shortEma.getValue(i)).append(',').append(longEma.getValue(i)).append(',').append(ppo.getValue(i)).append(',').append(roc.getValue(i)).append(',').append(rsi.getValue(i)).append(',').append(williamsR.getValue(i)).append(',').append(atr.getValue(i)).append(',').append(sd.getValue(i)).append('\n');
    }
    /*
          Writing CSV file
         */
    BufferedWriter writer = null;
    try {
        writer = new BufferedWriter(new FileWriter("indicators.csv"));
        writer.write(sb.toString());
    } catch (IOException ioe) {
        Logger.getLogger(IndicatorsToCsv.class.getName()).log(Level.SEVERE, "Unable to write CSV file", ioe);
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}
Also used : TimeSeries(org.ta4j.core.TimeSeries) FileWriter(java.io.FileWriter) IOException(java.io.IOException) PriceVariationIndicator(org.ta4j.core.indicators.helpers.PriceVariationIndicator) ClosePriceIndicator(org.ta4j.core.indicators.helpers.ClosePriceIndicator) BufferedWriter(java.io.BufferedWriter) TypicalPriceIndicator(org.ta4j.core.indicators.helpers.TypicalPriceIndicator) StandardDeviationIndicator(org.ta4j.core.indicators.statistics.StandardDeviationIndicator)

Aggregations

TimeSeries (org.ta4j.core.TimeSeries)48 MockTimeSeries (org.ta4j.core.mocks.MockTimeSeries)30 Test (org.junit.Test)24 ClosePriceIndicator (org.ta4j.core.indicators.helpers.ClosePriceIndicator)16 BaseTradingRecord (org.ta4j.core.BaseTradingRecord)12 TradingRecord (org.ta4j.core.TradingRecord)11 Bar (org.ta4j.core.Bar)9 Before (org.junit.Before)7 ArrayList (java.util.ArrayList)5 MockBar (org.ta4j.core.mocks.MockBar)5 BaseTimeSeries (org.ta4j.core.BaseTimeSeries)4 ZonedDateTime (java.time.ZonedDateTime)3 TimeSeriesCollection (org.jfree.data.time.TimeSeriesCollection)3 Strategy (org.ta4j.core.Strategy)3 BitfinexApiBroker (com.github.jnidzwetzki.bitfinex.v2.BitfinexApiBroker)2 BitfinexCandlestickSymbol (com.github.jnidzwetzki.bitfinex.v2.entity.symbol.BitfinexCandlestickSymbol)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 JFreeChart (org.jfree.chart.JFreeChart)2 XYPlot (org.jfree.chart.plot.XYPlot)2 TimeSeriesManager (org.ta4j.core.TimeSeriesManager)2