小白使用问题,如何通过接口取某只股票的前20个交易日那天的价格呢?

新手专区
标签: #<Tag:0x00007f6082110ac8>

(lzh41764176) #1

以此计算区间涨跌幅。
df = D.history_data(instruments=[‘000300.SHA’], start_date=‘2017-01-01’, end_date=‘2017-01-20’,
fields=[‘open’, ‘high’, ‘low’, ‘close’, ‘volume’, ‘amount’])


(大胡子) #2
def get_data(table_name, instruments, date, direction, days, fields):
    
    assert isinstance(date, str)  
    assert isinstance(direction, str)
    assert isinstance(table_name, str)
    
    if direction == 'farward':
        new_date = pd.to_datetime(date) - datetime.timedelta(days)
    elif direction == 'backward':
        new_date = pd.to_datetime(date) - datetime.timedelta(-1*days)
    new_date = new_date.strftime('%Y-%m-%d')
    
    if direction == 'backward':
        df = DataSource(table_name).read(instruments,date,new_date,fields)
    elif direction == 'farward':
        df = DataSource(table_name).read(instruments,new_date,date,fields)
        
    return df 

举例:
向后取

向前取

不过这里是按自然日取的,你是想按自然日还是交易日呢?


(大胡子) #3

如果是按交易日的话,可以参考以下代码:

def get_data(table_name, instruments, date, direction, days, fields):
    
    assert isinstance(date, str)  
    assert isinstance(direction, str)
    assert isinstance(table_name, str)
    
    dt = D.trading_days('CN')
    dl = dt['date'].map(lambda x:x.strftime('%Y-%m-%d')).tolist()
    
    while True:
        try:
            if direction == 'backward':
                ix = dl.index(date) - 1
            if direction == 'farward':
                ix = dl.index(date) + 1
            break
        except ValueError:
            if direction == 'backward':
                date = pd.to_datetime(date) - datetime.timedelta(-1)
            if direction == 'farward':
                date = pd.to_datetime(date) - datetime.timedelta(1)
                
            date = date.strftime('%Y-%m-%d')
        
    if direction == 'backward':
        new_date = dl[ix+days]
        df = DataSource(table_name).read(instruments, date, new_date,fields)
    elif direction == 'farward':
        new_date = dl[ix-days]
        df = DataSource(table_name).read(instruments,new_date, date,fields)
    
    assert len(df) == days 
     
    return df 

向前取7个交易日数据:

向后取7个交易日数据:


(lzh41764176) #4

非常感谢!