沪深股票的复权计算(复权因子的应用)--代码实现

对复权因子的介绍可参考
通过计算复权因子求得当日前一天收盘价,并存储在MongoDB数据库中
代码实现

def fill_au_factor_pre_close(begin_date,end_date):
    """
    为daily数据集填充
    1、复权因子au_factor,复权因子计算方式:au_factor= hfq_close/close
    2、pre_close = close(-1) * au_factor(-1)/au_factor
    :param begin_date:开始日期
    :param end_date:结束日期
    """
    all_codes = get_all_codes()

    for code in all_codes:
        hfq_daily_cursor = DB_CONN['daily_hfq'].find(
            {'code':code,'date':{'$gte':begin_date,'$lte':end_date},'index':False},
            sort=[('date',ASCENDING)],
            projection={'date':True,'close':True}
        )
    date_hfq_close_dict = dict([(x['date'],x['close']) for x in hfq_daily_cursor])

    daily_cursor = DB_CONN['daily'].find(
        {'code':code,'date':{'$gte':begin_date,'$lte':end_date},'index':False},
        sort=[('date',ASCENDING)],
        projection={'date':True,'close':True}
    )

    last_close = -1
    last_au_factor = -1
    
    update_requests = []
    for daily in daily_cursor:
        date = daily['date']
        try:
            close = daily['close']
            doc = dict()

            #复权因子 = 当日后复权价格/当日的实际价格
            au_factor = round(date_hfq_close_dict['date']/close,2)
            doc['au_factor'] = au_factor
            #当日前收价=前一日实际收盘价 * 前一日复权因子/当日复权因子
            if last_au_factor != -1 and last_close != -1:
                pre_close = last_close * last_au_factor / au_factor
                doc['pre_close'] = round(pre_close,2)
            last_close = close
            last_au_factor = au_factor
            
            update_requests.append(
                UpdateOne(
                    {'code':code,'date':date,'index':False},
                    {'$set':doc}
                )
            )
        except:
            print('计算复权因子时发生错误,股票代码:%s,日期:%s' %(code,date),flush=True)
            #恢复成初始值,防止出错
            last_close = -1
            last_au_factor = -1
        if len(update_requests)>0:
            update_result = DB_CONN['daily'].bulk_write(update_requests,ordered=False)
            print('填充复权因子和前收,股票:%s ,更新:%4d条'%(code,update_result.modified_count),flush=False)

posted @ 2020-04-26 22:40  牛犁heart  阅读(1238)  评论(0编辑  收藏  举报