How to get a close price from last day or from previous days?

How can I query close prices from last trading day or any days before?

Thanks

ZP

Comments

  • ptunneyptunney Posts: 246
    edited April 2018

    In backtesting there are two ways to access close prices, md.stat.prev_close and through the bars.

    See the following code for an example...

    from cloudquant.interfaces import Strategy
    
    class Test_PreviousClose(Strategy):
        @classmethod
        def is_symbol_qualified(cls, symbol, md, service, account):
            if symbol=="SPY":
                print symbol,round(md.stat.prev_close,2)
                bars=md.bar.daily(start=-10)
                print "The bars variable is a list of lists and contains 16 lists",len(bars) 
                print "The close prices are one of those lists and it has 10 entries",len(bars.close)
                for i in range(1,(len(bars.close))):
                        print -i,service.time_to_string(bars.timestamp[-i],'%Y-%m-%d'),round(bars.close[-i],2)
            return False
    

    At the moment the values they return can differ if a symbol has split or had a dividend.

    Try the following code on 2018-03-20 to see three symbols that have split and how the previous close price from stat differs from the adjusted previous close price in the bars...

    from cloudquant.interfaces import Strategy
    
    class Test_Previous_Close2(Strategy):
        @classmethod
        def is_symbol_qualified(cls, symbol, md, service, account):
            if md.stat.split_ratio!=1.0:
                print md.stat.split_ratio
                print symbol,round(md.stat.prev_close,2)
                bars=md.bar.daily(start=-10)
                print "The bars variable is a list of lists and contains 16 lists",len(bars) 
                print "The close prices are one of those lists and it has 10 entries",len(bars.close)
                for i in range(1,(len(bars.close))):
                        print -i,service.time_to_string(bars.timestamp[-i],'%Y-%m-%d'),round(bars.close[-i],2)
            return False
    

    In live-trading or forward-testing there are two variables available md.stat.prev_close (which is adjusted) and md.stat.unadjusted_prev_close.

    Hope this helps!

    Paul

Sign In or Register to comment.