Exemplo n.º 1
0
def simulate(strategy_name,
             portfolio,
             start_date,
             end_date,
             output="~/.quant/simulation.h5",
             strategy_params="{}"):
    """A simple simulator that simulates a strategy that only makes
    decisions at closing.  Only BUY and SELL orders are supported.  Orders
    are only good for the next day.

    A price type of MARKET is executed at the open price the next day.

    A price type of MARKET_ON_CLOSE is executed at the close price the next day.

    A price type of LIMIT will be executed at the LIMIT price the next day if LIMIT
    is between the low and high prices of the day.

    A price type of STOP will be executed at the STOP price the next day if STOP
    is between the low and high prices of the day.

    A price type of STOP_LIMIT will be executed at the LIMIT price the next day if STOP
    is between the low and high prices of the day.
    """

    outputFile = openOutputFile(output)
    # Get some of the tables from the output file
    order_tbl = outputFile.getNode("/Orders")
    postion_tbl = outputFile.getNode("/Position")
    performance_tbl = outputFile.getNode("/Performance")

    start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
    end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
    # Start the simulation at closing of the previous trading day
    now = getPrevTradingDay(start_date)

    try:
        position = initialize_position(portfolio, now)

        # Pre-cache some info to make the simulation faster
        ticker = MARKET["^DJI"].updateHistory(start_date, end_date)
        for symbol in position.keys():
            if symbol != '$':
                MARKET[symbol].updateHistory(start=start_date, end=end_date)
        days = (end_date - start_date).days

        # Initialize the strategy
        params = yaml.load(strategy_params)
        strategy_clazz = load_strategy(strategy_name)
        strategy = strategy_clazz(start_date, end_date, position, MARKET,
                                  params, outputFile)

        p = ProgressBar(maxValue=days, totalWidth=80)
        print "Starting Simulation"

        while now <= end_date:

            # Write the initial position to the database
            write_position(postion_tbl, position, now)
            write_performance(performance_tbl, position, now)

            # Remember 'now' is after closing, so the strategy
            # can use any information from 'now' or earlier
            orders = strategy.evaluate(now, position, MARKET)

            # Go to the next day to evalute the orders
            now += ONE_DAY
            while not isTradingDay(now):
                now += ONE_DAY
                p.performWork(1)
                continue

            # Execute orders
            execute_orders(order_tbl, position, now, orders)

            # Flush the data to disk
            outputFile.flush()
            p.performWork(1)
            print p, '\r',

        p.updateAmount(p.max)
        print p, '\r',
        print '\n'  # End the progress bar here before calling finalize
        orders = strategy.finalize()
    finally:
        outputFile.close()
Exemplo n.º 2
0
def simulate(strategy_name, portfolio, start_date, end_date, output="~/.quant/simulation.h5", strategy_params="{}"):
    """A simple simulator that simulates a strategy that only makes
    decisions at closing.  Only BUY and SELL orders are supported.  Orders
    are only good for the next day.

    A price type of MARKET is executed at the open price the next day.

    A price type of MARKET_ON_CLOSE is executed at the close price the next day.

    A price type of LIMIT will be executed at the LIMIT price the next day if LIMIT
    is between the low and high prices of the day.

    A price type of STOP will be executed at the STOP price the next day if STOP
    is between the low and high prices of the day.

    A price type of STOP_LIMIT will be executed at the LIMIT price the next day if STOP
    is between the low and high prices of the day.
    """

    outputFile = openOutputFile(output)
    # Get some of the tables from the output file
    order_tbl = outputFile.getNode("/Orders")
    postion_tbl = outputFile.getNode("/Position")
    performance_tbl = outputFile.getNode("/Performance")
        
    start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
    end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
    # Start the simulation at closing of the previous trading day
    now = getPrevTradingDay(start_date)

    try:
        position = initialize_position(portfolio, now)

        # Pre-cache some info to make the simulation faster
        ticker = MARKET["^DJI"].updateHistory(start_date, end_date)
        for symbol in position.keys():
            if symbol != '$':
                MARKET[symbol].updateHistory(start=start_date, end=end_date)
        days = (end_date - start_date).days
        
        # Initialize the strategy
        params = yaml.load(strategy_params)
        strategy_clazz = load_strategy(strategy_name)
        strategy = strategy_clazz(start_date, end_date, position, MARKET, params, outputFile)

        p = ProgressBar(maxValue=days, totalWidth=80)
        print "Starting Simulation"

        while now <= end_date:

            # Write the initial position to the database
            write_position(postion_tbl, position, now)
            write_performance(performance_tbl, position, now)
            
            # Remember 'now' is after closing, so the strategy
            # can use any information from 'now' or earlier
            orders = strategy.evaluate(now, position, MARKET)
               
            # Go to the next day to evalute the orders
            now += ONE_DAY
            while not isTradingDay(now):
                now += ONE_DAY
                p.performWork(1)
                continue
            
            # Execute orders
            execute_orders(order_tbl, position, now, orders)

            # Flush the data to disk
            outputFile.flush()
            p.performWork(1)
            print p, '\r',

        p.updateAmount(p.max)
        print p, '\r',
        print '\n' # End the progress bar here before calling finalize
        orders = strategy.finalize()
    finally:
        outputFile.close()
def simulate(MARKET, CONFIG, strategy_name, portfolio, start_date, end_date, output="~/.quant/simulation.h5", strategy_params="{}"):
    """A simple simulator that simulates a strategy that only makes
    decisions at closing.  Only BUY and SELL orders are supported.  Orders
    are only good for the next day.

    A price type of MARKET is executed at the open price the next day.

    A price type of MARKET_ON_CLOSE is executed at the close price the next day.

    A price type of LIMIT will be executed at the LIMIT price the next day if LIMIT
    is between the low and high prices of the day.

    A price type of STOP will be executed at the STOP price the next day if STOP
    is between the low and high prices of the day.

    A price type of STOP_LIMIT will be executed at the LIMIT price the next day if STOP
    is between the low and high prices of the day.
    """

    outputFile = openOutputFile(output)
    # Get some of the tables from the output file
    order_tbl = outputFile.getNode("/Orders")
    postion_tbl = outputFile.getNode("/Position")
    performance_tbl = outputFile.getNode("/Performance")
        
    start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
    end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
    # Start the simulation at closing of the previous trading day
    print start_date 
    now = getPrevTradingDay(MARKET, start_date)
    try:
        position = initialize_position(CONFIG, portfolio, now)
        for instrument, p in position.items():
            if instrument != '$':
                quote = MARKET[instrument][now]
                if quote == None:
                    return
        # Pre-cache some info to make the simulation faster
        '''
        ticker = MARKET["399001.sz"].updateHistory(start_date, end_date)
        for symbol in position.keys():
            if symbol != '$':
                MARKET[symbol].updateHistory(start=start_date, end=end_date)
        '''
        days = (end_date - start_date).days
        
        # Initialize the strategy
        params = yaml.load(strategy_params)
        imp.acquire_lock()
        strategy_clazz = load_strategy(strategy_name)
        imp.release_lock()
        print 'jinxiaoyi'
        strategy = strategy_clazz(start_date, end_date, position, MARKET, params, outputFile)
        p = ProgressBar(maxValue=days, totalWidth=80)
        print "Starting Simulation %s" % portfolio
        # Write the initial position to the database
        write_position(MARKET,postion_tbl, position, now)
        write_performance(MARKET,performance_tbl, position, now)
        while now <= end_date:
            #print now
            # Remember 'now' is after closing, so the strategy
            # can use any information from 'now' or earlier
            #orders = strategy.evaluate(now, position, MARKET)
            # Go to the next day to evalute the orders          
            while 1:
                orders = strategy.evaluate(now, position, MARKET)
                if orders == 'outdate':
                    outputFile.close()
                    return
                if orders == None:
                    now += ONE_DAY
                    p.performWork(1)
                else:
                    break
            # Execute orders
            execute_orders(MARKET, order_tbl, position, now, orders)
            write_position(MARKET, postion_tbl, position, now)
            write_performance(MARKET, performance_tbl, position, now)
            now += ONE_DAY
            # Flush the data to disk
            outputFile.flush()
            p.performWork(1)
            #print p, '\r'
            
        p.updateAmount(p.max)
        #print p, '\r',
        #print '\r\n' # End the progress bar here before calling finalize
        orders = strategy.finalize()
    finally:
        outputFile.close()