python读取持仓数据_定量交易的Python部分——读取、解析并存储在JSON文件中(新建类属性、合约模型类、头寸模型类),量化,之,python,篇,存入,json,新增,持仓...

该博客介绍了如何使用Python读取、解析和存储持仓数据到JSON文件。通过定义装饰器、合约模型类和持仓模型类,实现异常处理、数据转换和文件操作。内容包括读取JSON文件、合并多个文件持仓、按倍数调整持仓以及清空持仓等功能。
摘要由CSDN通过智能技术生成

import json

import math

"""

处理异常的装饰器类

"""

class DecorateExcept:

def __init__(self, function):

self.function = function

def __call__(self, *args, **kwargs):

try:

function_result = self.function(*args, **kwargs)

except FileNotFoundError as result: # filename文件 没找到

print("Error: file is not fount %s" % result)

except AttributeError as result:

print("Error: %s" % result)

except Exception as result:

print("unkown Error: %s" % result)

else:

return function_result

"""

合约模型类

"""

class PositionModel:

_position_key = "pos"

_entryprice_key = "entryprice"

_target_position_key = "target_pos"

def __init__(self, position_dictionary):

if PositionModel._position_key in position_dictionary.keys():

self.lots = position_dictionary[PositionModel._position_key]

else:

self.lots = None

if PositionModel._entryprice_key in position_dictionary.keys():

self.entry_price = position_dictionary[PositionModel._entryprice_key]

else:

self.entry_price = None

if PositionModel._target_position_key in position_dictionary.keys():

self.target_position = position_dictionary[PositionModel._target_position_key]

else:

self.target_position = None

def model_to_dictionary(self):

empty_dictionary = {}

if self.lots is not None:

empty_dictionary[PositionModel._position_key] = self.lots

if self.entry_price is not None:

empty_dictionary[PositionModel._entryprice_key] = self.entry_price

if self.target_position is not None:

empty_dictionary[PositionModel._target_position_key] = self.target_position

return empty_dictionary

class ContractModel:

def __init__(self, contract_name, position_model):

self.name = contract_name

self._position_model = position_model

@property

def position_model(self):

return self._position_model

@position_model.setter

def position_model(self, position_model):

self._position_model = position_model

@position_model.getter

def position_model(self):

return self._position_model

@classmethod

def dictionary_to_models(cls, data_dictionary):

contract_models = []

for contract_name, position_dictionary in data_dictionary.items():

contract_model = ContractModel(contract_name=contract_name,

position_model=PositionModel(position_dictionary=position_dictionary))

contract_models.append(contract_model)

return contract_models

@classmethod

def models_to_dictionary(cls, *models):

empty_dictionary = {}

for model in models:

empty_dictionary[model.name] = model.position_model.model_to_dictionary()

return empty_dictionary

"""

持仓json文件操作类

"""

class PositionJsonOperator:

"""

操作 json文件 的 类

ps: 使用时, 需要导入 json、math库

"""

_read_type = "r"

_write_type = "w"

_utf_8_encoding = "utf-8"

# ------------------ public part ------------------

@classmethod

def tqz_load_jsonfile(cls, filename=None):

if filename is None:

exception = Exception("Error: filename is None")

raise exception

else:

return cls._writeReadFile_except_operation(filename=filename, operation_type=cls._read_type)

@classmethod

def tqz_write_jsonfile(cls, content=None, filename=None):

if filename is None:

exception = Exception("Error: filename is None")

raise exception

else:

cls._writeReadFile_except_operation(filename=filename, content=content, operation_type=cls._write_type)

@classmethod

def tqz_sum_position_all_jsonfile(cls, *jsonfile_list, target_jsonfile):

"""

加总多个 json文件的 持仓, 并写入新的目标json文件中

:param jsonfile_list: 字符串数组

:param target_jsonfile: 要存入的 json文件名

"""

jsonfile_content_list = []

[jsonfile_content_list.append(cls.tqz_load_jsonfile(jsonfile)) for jsonfile in jsonfile_list]

content_dic = cls._sum_position_all_keyValueNotFound_except_operation(dic_list=jsonfile_content_list)

cls.tqz_write_jsonfile(content=content_dic, filename=target_jsonfile)

@classmethod

def tqz_multi_position_all(cls, *jsonfile_list, multi):

"""

按倍数调整 多个json文件的 持仓

:param jsonfile_list: 需要调整持仓的 json文件数组

:param multi: 倍数

"""

[cls._multi_position(source_jsonfile=jsonfile, multi=multi) for jsonfile in jsonfile_list]

@classmethod

def tqz_empty_position_all(cls, *jsonfile_list):

"""

清空 多个json文件的 持仓

:param jsonfile_list: 需要清空的 json文件数组

"""

cls.tqz_multi_position_all(*jsonfile_list, multi=0)

# ------------------ private part ------------------

@classmethod

def _multi_position(cls, source_jsonfile, multi):

source_content = cls.tqz_load_jsonfile(filename=source_jsonfile)

source_content = cls._multi_position_keyValueNotFound_except_operation(source_content=source_content,

multi=multi)

cls.tqz_write_jsonfile(content=source_content, filename=source_jsonfile)

@classmethod

def _empty_position(cls, source_jsonfile):

cls._multi_position(source_jsonfile=source_jsonfile, multi=0)

# ------------------ except operation part ------------------

@classmethod

@DecorateExcept

def _writeReadFile_except_operation(cls, filename=None, content=None, operation_type="r"):

if cls._read_type == operation_type:

with open(filename, operation_type, encoding=cls._utf_8_encoding) as fp:

return json.load(fp=fp)

elif cls._write_type == operation_type:

with open(filename, operation_type, encoding=cls._utf_8_encoding) as fp:

json.dump(content, fp=fp, ensure_ascii=False, indent=4) # 参数indent: json文件按格式写入, 距行首空4格;

@classmethod

@DecorateExcept

def _sum_position_all_keyValueNotFound_except_operation(cls, dic_list=None):

new_json_contract_models = []

new_json_contract_names = []

all_json_contract_models = []

if dic_list is not None:

[all_json_contract_models.append(ContractModel.dictionary_to_models(data_dictionary=dic)) for dic in

dic_list]

for contract_models in all_json_contract_models:

for contract_model in contract_models:

if contract_model.name not in new_json_contract_names:

new_json_contract_models.append(

ContractModel(contract_name=contract_model.name, position_model=contract_model.position_model))

new_json_contract_names.append(contract_model.name)

else:

find_contract_model = cls._find_contract_model(*new_json_contract_models,

model_name=contract_model.name)

contract_model.position_model.lots += find_contract_model.position_model.lots

return ContractModel.models_to_dictionary(*new_json_contract_models)

@classmethod

def _find_contract_model(cls, *contract_models, model_name):

for contract_model in contract_models:

if contract_model.name == model_name:

return contract_model

return None

@classmethod

@DecorateExcept

def _multi_position_keyValueNotFound_except_operation(cls, source_content=None, multi=1):

all_json_contract_models = []

if source_content is not None:

[all_json_contract_models.append(ContractModel(contract_name=contract_name, position_model=PositionModel(

position_dictionary=position_dictionary))) for contract_name, position_dictionary in

source_content.items()]

for contract_model in all_json_contract_models:

if contract_model.position_model.lots > 0:

contract_model.position_model.lots = math.floor(contract_model.position_model.lots * multi)

else:

contract_model.position_model.lots = math.floor(-1 * contract_model.position_model.lots * multi) * -1

return ContractModel.models_to_dictionary(*all_json_contract_models)

"""

测试模块

"""

def _main_engine():

list = ["symbol_2.json", "symbol_3.json", "symbol_4.json", "symbol_5.json"]

target_jsonfile = "test.json"

PositionJsonOperator.tqz_sum_position_all_jsonfile(*list, target_jsonfile=target_jsonfile)

# PositionJsonOperator.tqz_multi_position_all(target_jsonfile, multi=1)

# PositionJsonOperator.tqz_empty_position_all(target_jsonfile)

if __name__ == '__main__':

_main_engine()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值