So far we have looked at the trading simulation functionality which was using the historic stock data to evaluate strategies on a single stock or a portfolio of stocks.

In this document we want to demonstrate how to do trading with actual data.

We still use the PaperTrader to demonstrate the basic logic

Setup

We add the necessary jars and import all relevant packages:

%classpath config resolver maven-public https://software.pschatzmann.ch/repository/maven-public/
%%classpath add mvn 
ch.pschatzmann:investor:0.9-SNAPSHOT
ch.pschatzmann:jupyter-jdk-extensions:0.0.1-SNAPSHOT

Added new repo: maven-public
// imports for the investor framwork
import ch.pschatzmann.dates._;
import ch.pschatzmann.stocks._;
import ch.pschatzmann.stocks.data.universe._;
import ch.pschatzmann.stocks.input._;
import ch.pschatzmann.stocks.accounting._;
import ch.pschatzmann.stocks.accounting.kpi._;
import ch.pschatzmann.stocks.execution._;
import ch.pschatzmann.stocks.execution.fees._;
import ch.pschatzmann.stocks.execution.price._;
import ch.pschatzmann.stocks.parameters._;
import ch.pschatzmann.stocks.strategy._;
import ch.pschatzmann.stocks.strategy.optimization._;
import ch.pschatzmann.stocks.strategy.allocation._;
import ch.pschatzmann.stocks.strategy.selection._;
import ch.pschatzmann.stocks.integration._;
import ch.pschatzmann.stocks.integration.ChartData.FieldName._;
import ch.pschatzmann.stocks.strategy.OptimizedStrategy.Schedule._;

// java
import java.util.stream.Collectors;
import java.util._;
import java.lang._;
import java.util.function.Consumer;
import scala.collection.JavaConverters

/// jupyter custom displayer
import ch.pschatzmann.display.Displayers

import ch.pschatzmann.dates._
import ch.pschatzmann.stocks._
import ch.pschatzmann.stocks.data.universe._
import ch.pschatzmann.stocks.input._
import ch.pschatzmann.stocks.accounting._
import ch.pschatzmann.stocks.accounting.kpi._
import ch.pschatzmann.stocks.execution._
import ch.pschatzmann.stocks.execution.fees._
import ch.pschatzmann.stocks.execution.price._
import ch.pschatzmann.stocks.parameters._
import ch.pschatzmann.stocks.strategy._
import ch.pschatzmann.stocks.strategy.optimization._
import ch.pschatzmann.stocks.strategy.allocation._
import ch.pschatzmann.stocks.strategy.selection._
import ch.pschatzmann.stocks.integration._
import ch.pschatzmann.stocks.integration.ChartData.FieldName._
import ch.pschatzmann.stocks.strategy.OptimizedStrategy.Schedule._
import java.util.stream...

Trading with One Single Strategy

Here is the first example with one defined strategy:
– We use a ManagedAccount in order to make sure that the transactions can be saved and reloaded when we restart the functionality at a later date.
– We need to set up the StrategyExecutor first.
– Then we can feed it to the ScheduledExecutor and schedule the job with a cron expression.

Cron Syntax

The detailed description of the quartz cron syntax can be found at http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html. E.g. ff we an it to run every 10 minutes we would specify “0 0/8 * * * ?”
In our example we execute the strategy every day at 8am GMT.

var account = new ManagedAccount("648-11017-A", "USD", 100000.00, new Date(), new PerTradeFees(6.95))
var trader = new PaperTrader(account);
var strategyExecutor = new StrategyExecutor(trader);
var apple = new StockData(new StockID("AAPL", "NASDAQ"), new YahooReader());
strategyExecutor.addStrategy(new RSI2Strategy(apple));

// schedule the future execution 
var scheduledExecutor = new ScheduledExecutor(strategyExecutor)
scheduledExecutor.schedule("0 0 8 * * ?"); 

The scheduled trading has been stopped
The trading has been scheduled....





null

Trading a Porfolio of Strategies

In our second example we use the StrategySelector/StockSelector that we got to know in the Selection Chapter.

To trade a porfolio of strategies is using the same flow as above:

var periods = Context.getDateRanges("2016-01-01","2017-01-01");
var account = new ManagedAccount("648-11017-B", "USD", 100000.00, periods.get(0).getStart(), new PerTradeFees(6.95))
var strategies = TradingStrategyFactory.list()
var trader = new PaperTrader(account);
var allocationStrategy = new DistributedAllocationStrategy(trader);
var executor = new StrategyExecutor(trader, allocationStrategy);
var portfolioUniverse =  new EdgarUniverse(2016, Arrays.asList(0.2, 0.5, 0.8, 1.0), 10, Arrays.asList("NetIncomeLoss"), true)                                
var strategySelector = new StrategySelector(account, strategies, periods.get(0), KPI.AbsoluteReturn)
var stockSelector = new StockSelector(strategySelector)
var reader = new YahooReader() 
var result = stockSelector.getSelection(10, portfolioUniverse, reader)
executor.setStrategies(result.getStrategies(reader));

var scheduledExecutor = new ScheduledExecutor(executor)
scheduledExecutor.schedule("0 0 8 * * ?"); 

scheduledExecutor.stop()
The scheduled trading has been stopped
The trading has been scheduled....
The scheduled trading has been stopped





null

Trading a Porfolio of Strategies II

In our last example we show a more dynamic example which recalculates the Strategy Executor and Universe with each year change. To achieve this we overwrite the getExecutor() method in a new custom MyScheduledExecutor subclass:

 class MyScheduledExecutor() extends ScheduledExecutor() {
    var currentYear:Integer = null;

    override def getExecutor: StrategyExecutor = {
        var year = Context.getYear(new Date())
        var executor = super.getExecutor()
        if (year!=currentYear) {
            System.out.println("Defining new executor");
            var periods = Context.getDateRanges((year-2)+"-01-01",(year-1)+"-01-01");
            var account = new ManagedAccount("648-11017", "USD", 100000.00, periods.get(0).getStart(), new PerTradeFees(6.95))
            var strategies = TradingStrategyFactory.list()
            var trader = new PaperTrader(account);
            var allocationStrategy = new DistributedAllocationStrategy(trader);
            executor = new StrategyExecutor(trader, allocationStrategy);
            var portfolioUniverse =  new EdgarUniverse(year-2, Arrays.asList(0.2, 0.5, 0.8, 1.0), 10, Arrays.asList("NetIncomeLoss"), true)                                
            var strategySelector = new StrategySelector(account, strategies, periods.get(0), KPI.AbsoluteReturn)
            var stockSelector = new StockSelector(strategySelector)
            var reader = new YahooReader() 
            var result = stockSelector.getSelection(10, portfolioUniverse, reader)
            executor.setStrategies(result.getStrategies(reader));
            setExecutor(executor)
            currentYear = year
        }
        return executor
    }
 }

var scheduledExecutor = new MyScheduledExecutor()
scheduledExecutor.schedule("0 0 8 * * ?"); 

Defining new executor
The scheduled trading has been stopped
The trading has been scheduled....





null

Checking the Result

If there are any trades the system creates a file with the list of transactions in the ‘trades’ subdirectory. The latest updated account information can be found in the ‘accounts’ directory.

We can also determine the trasactions from the account which is available in the executor:

Displayers.display(scheduledExecutor.getAccount().getTransactions())
stockID date quantity requestedPrice filledPrice fees comment id status requestedPriceType buyOrSell impactOnCash active
Key Value
ticker Cash
exchange Account
2016-01-01 0 0 0 0 2feaf27c-9439-4957-b81d-2fa0f1b8d163 Planned CashTransfer NA 100000 true

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *