量化交易之python篇 - 读取、解析、存入json文件(封装版)

import json

class JsonOperator:
    """
     操作 json文件 的 类
    """

    @staticmethod
    def load_jsonfile(filename=""):
        if "" == filename:
            exception = Exception("Error: filename is empty")
            raise exception
        else:
            with open(filename, "r", encoding="utf-8") as fp:
                return json.load(fp=fp)

    @staticmethod
    def write_jsonfile(content=None, filename=""):
        if "" == filename:
            exception = Exception("Error: filename is empty")
            raise exception
        else:
            with open(filename, "w", encoding="utf-8") as fp:
                json.dump(content, fp=fp, ensure_ascii=False, indent=4)  # 参数indent: json文件按格式写入, 距行首空4格;


def get_newData_with_sumPosition(first_dic=None, second_dic=None):
    new_dic = {}
    for (key, value) in first_dic.items():
        value['pos'] = first_dic[key]['pos'] + second_dic[key]['pos']
        new_dic[key] = value
    return new_dic


def main_function():
    # json数据源文件
    cta_hla_filename = "cta_strategy_data_2503023_hla.json"
    cta_hsr_filename = "cta_strategy_data_2503023_hsr.json"

    # 写入目标文件
    cta_target_filename = "cta_strategy_data_2503023_sum.json"

    # 读取json文件数据
    cta_hla_dic = JsonOperator().load_jsonfile(filename=cta_hla_filename)
    cta_hsr_dic = JsonOperator().load_jsonfile(filename=cta_hsr_filename)

    # 获取新的要写入json文件的数据
    new_dic = get_newData_with_sumPosition(cta_hla_dic, cta_hsr_dic)

    # 写入目标文件夹
    JsonOperator().write_jsonfile(content=new_dic, filename=cta_target_filename)


if __name__ == '__main__':
    main_function()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值