Skip to content

Commit

Permalink
[pre-commit.ci] pre-commit autoupdate (#325)
Browse files Browse the repository at this point in the history
* [pre-commit.ci] pre-commit autoupdate

updates:
- [github.com/psf/black: 23.12.1 → 24.1.1](psf/black@23.12.1...24.1.1)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
pre-commit-ci[bot] authored Jan 31, 2024
1 parent ec3cf09 commit 484217c
Show file tree
Hide file tree
Showing 34 changed files with 125 additions and 53 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@ repos:
- id: reorder-python-imports
args: [--py37-plus]
- repo: https://github.com/psf/black
rev: 23.12.1
rev: 24.1.1
hooks:
- id: black
1 change: 1 addition & 0 deletions agents/elegantrl_models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
DRL models from ElegantRL: https://github.com/AI4Finance-Foundation/ElegantRL
"""

from __future__ import annotations

import torch
Expand Down
1 change: 1 addition & 0 deletions meta/env_execution_optimizing/liquidation/ddpg_agent.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Source: https://github.com/AI4Finance-Foundation/Liquidation-Analysis-using-Multi-Agent-Reinforcement-Learning-ICML-2019/blob/master/syntheticChrissAlmgren.py"""

"""Paper: Multi-agent reinforcement learning for liquidation strategy analysis accepted by ICML 2019 AI in Finance: Applications and Infrastructure for Multi-Agent Learning. (https://arxiv.org/abs/1906.11046)"""
import copy
import random
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Source: https://github.com/AI4Finance-Foundation/Liquidation-Analysis-using-Multi-Agent-Reinforcement-Learning-ICML-2019/blob/master/syntheticChrissAlmgren.py"""

"""Paper: Multi-agent reinforcement learning for liquidation strategy analysis accepted by ICML 2019 AI in Finance: Applications and Infrastructure for Multi-Agent Learning. (https://arxiv.org/abs/1906.11046)"""
import collections
import random
Expand Down
1 change: 1 addition & 0 deletions meta/env_execution_optimizing/liquidation/model.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Source: https://github.com/AI4Finance-Foundation/Liquidation-Analysis-using-Multi-Agent-Reinforcement-Learning-ICML-2019/blob/master/syntheticChrissAlmgren.py"""

"""Paper: Multi-agent reinforcement learning for liquidation strategy analysis accepted by ICML 2019 AI in Finance: Applications and Infrastructure for Multi-Agent Learning. (https://arxiv.org/abs/1906.11046)"""
import numpy as np
import torch
Expand Down
1 change: 1 addition & 0 deletions meta/env_execution_optimizing/liquidation/utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Source: https://github.com/AI4Finance-Foundation/Liquidation-Analysis-using-Multi-Agent-Reinforcement-Learning-ICML-2019/blob/master/syntheticChrissAlmgren.py"""

"""Paper: Multi-agent reinforcement learning for liquidation strategy analysis accepted by ICML 2019 AI in Finance: Applications and Infrastructure for Multi-Agent Learning. (https://arxiv.org/abs/1906.11046)"""
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Source: https://github.com/microsoft/qlib/tree/high-freq-execution/examples/trade/"""

# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import functools
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Source: https://github.com/microsoft/qlib/tree/high-freq-execution/examples/trade/"""

# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import sys
Expand Down
1 change: 1 addition & 0 deletions meta/env_future_trading/env_future_trading_wt.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Use WonderTrader Simulator"""

"""https://github.com/drlgistics/Wt4ElegantRL"""
from meta.env_future_trading.wt4elegantrl.envs_simple_cta import SimpleCTAEnv
from meta.env_future_trading.wt4elegantrl.envs_simple_cta import (
Expand Down
4 changes: 3 additions & 1 deletion meta/env_future_trading/wt4elegantrl/assessments.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,9 @@ def finish(self):
# gamma = np.round(np.nanprod(np.array(self.__reward__)+1, axis=0)-1, 5)
# gamma = self.__assets__[-1]/max(self.__assets__)-1
# gamma = self.__assets__[-1]/self.init_assets-1
self.__reward__.append(gamma) # 在结束的时候把过程奖励做处理,作为整个训练的奖励
self.__reward__.append(
gamma
) # 在结束的时候把过程奖励做处理,作为整个训练的奖励
self.__done__ = True

@property
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,10 @@ def debug(count):
obs, reward, done, info = env.step(action)
n += 1
# print('action:', action, 'obs:', obs, 'reward:', reward, 'done:', done)
print("第%s次训练完成,执行%s步, 奖励%s, 盈亏%s。" % (i, n, reward, env.assets))
print(
"第%s次训练完成,执行%s步, 奖励%s, 盈亏%s。"
% (i, n, reward, env.assets)
)
env.close()

@command()
Expand Down
12 changes: 6 additions & 6 deletions meta/env_future_trading/wt4elegantrl/elegantrl/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,12 @@ def __init__(
self.get_obj_critic = None

self.criterion = torch.nn.SmoothL1Loss()
self.cri = (
self.cri_target
) = self.if_use_cri_target = self.cri_optim = self.ClassCri = None
self.act = (
self.act_target
) = self.if_use_act_target = self.act_optim = self.ClassAct = None
self.cri = self.cri_target = self.if_use_cri_target = self.cri_optim = (
self.ClassCri
) = None
self.act = self.act_target = self.if_use_act_target = self.act_optim = (
self.ClassAct
) = None

assert isinstance(gpu_id, int)
assert isinstance(env_num, int)
Expand Down
6 changes: 3 additions & 3 deletions meta/env_future_trading/wt4elegantrl/elegantrl/replay.py
Original file line number Diff line number Diff line change
Expand Up @@ -380,9 +380,9 @@ def update_ids(self, data_ids, prob=10): # 10 is max_prob
self.now_len += (ids >= self.now_len).sum()

upper_step = self.depth - 1
self.prob_ary[
ids
] = prob # here, ids means the indices of given children (maybe the right ones or left ones)
self.prob_ary[ids] = (
prob # here, ids means the indices of given children (maybe the right ones or left ones)
)
p_ids = (ids - 1) // 2

while upper_step: # propagate the change through tree
Expand Down
24 changes: 15 additions & 9 deletions meta/env_future_trading/wt4elegantrl/elegantrl/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,9 +282,11 @@ def update_buffer(_traj_list):

if if_save and not if_overwrite:
agent.save_or_load_agent("%s/best/" % (cwd), if_save=True)
buffer.save_or_load_history(
"%s/best/" % (cwd), if_save=True
) if agent.if_off_policy else None
(
buffer.save_or_load_history("%s/best/" % (cwd), if_save=True)
if agent.if_off_policy
else None
)

if_train = not (
(if_allow_break and if_reach_goal)
Expand Down Expand Up @@ -508,12 +510,16 @@ def comm_network_optim(self, agent, learner_id):
avg_update_net(agent.cri, data[2], device) if data[2] else None
avg_update_optim(agent.cri_optim, data[3], device)

avg_update_net(
agent.act_target, data[4], device
) if agent.if_use_act_target else None
avg_update_net(
agent.cri_target, data[5], device
) if agent.if_use_cri_target else None
(
avg_update_net(agent.act_target, data[4], device)
if agent.if_use_act_target
else None
)
(
avg_update_net(agent.cri_target, data[5], device)
if agent.if_use_cri_target
else None
)

def run0(self, args, comm_eva, comm_exp, learner_id=0):
# print(f'| os.getpid()={os.getpid()} PipeLearn.run, {learner_id}')
Expand Down
4 changes: 3 additions & 1 deletion meta/env_future_trading/wt4elegantrl/wtpy/CtaContext.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ def __init__(self, id: int, stra, wrapper: WtWrapper, engine):
self.__wrapper__ = wrapper # 底层接口转换器
self.__id__ = id # 策略ID
self.__bar_cache__ = dict() # K线缓存
self.__tick_cache__ = dict() # tTick缓存,每次都重新去拉取,这个只做中转用,不在python里维护副本
self.__tick_cache__ = (
dict()
) # tTick缓存,每次都重新去拉取,这个只做中转用,不在python里维护副本
self.__sname__ = stra.name()
self.__engine__ = engine # 交易环境
self.__pos_cache__ = None
Expand Down
4 changes: 3 additions & 1 deletion meta/env_future_trading/wt4elegantrl/wtpy/HftContext.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ def __init__(self, id: int, stra, wrapper: WtWrapper, engine):
self.__wrapper__ = wrapper # 底层接口转换器
self.__id__ = id # 策略ID
self.__bar_cache__ = dict() # K线缓存
self.__tick_cache__ = dict() # Tick缓存,每次都重新去拉取,这个只做中转用,不在python里维护副本
self.__tick_cache__ = (
dict()
) # Tick缓存,每次都重新去拉取,这个只做中转用,不在python里维护副本
self.__ordque_cache__ = dict() # 委托队列缓存,用法同__tick_cache__
self.__orddtl_cache__ = dict() # 逐笔委托缓存,用法同__tick_cache__
self.__trans_cache__ = dict() # 逐笔成交缓存,用法同__tick_cache__
Expand Down
4 changes: 3 additions & 1 deletion meta/env_future_trading/wt4elegantrl/wtpy/SelContext.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ def __init__(self, id: int, stra, wrapper: WtWrapper, engine):
self.__wrapper__ = wrapper # 底层接口转换器
self.__id__ = id # 策略ID
self.__bar_cache__ = dict() # K线缓存
self.__tick_cache__ = dict() # tTick缓存,每次都重新去拉取,这个只做中转用,不在python里维护副本
self.__tick_cache__ = (
dict()
) # tTick缓存,每次都重新去拉取,这个只做中转用,不在python里维护副本
self.__sname__ = stra.name()
self.__engine__ = engine # 交易环境
self.__pos_cache__ = None
Expand Down
14 changes: 11 additions & 3 deletions meta/env_future_trading/wt4elegantrl/wtpy/apps/WtBtAnalyst.py
Original file line number Diff line number Diff line change
Expand Up @@ -796,17 +796,25 @@ def trading_analyze(workbook: Workbook, df_closes, df_funds, capital=500000):
worksheet.write_column("B40", s.values(), value_format)

worksheet.write_row("A49", ["连续交易系列统计"], title_format)
worksheet.write_row("A51", ["连续盈利次数", "出现次数", "每个序列的平均收益"], index_format)
worksheet.write_row(
"A51", ["连续盈利次数", "出现次数", "每个序列的平均收益"], index_format
)
worksheet.write_column("A52", f_result["连续次数"], value_format)
worksheet.write_column("B52", f_result["出现次数"], value_format)
worksheet.write_column("C52", f_result["每个序列平均收益"], value_format)

win_cnt = len(f_result)
next_row = win_cnt + 52
worksheet.write_row("A%d" % next_row, ["连续亏损次数", "出现次数", "每个序列的平均亏损"], index_format)
worksheet.write_row(
"A%d" % next_row,
["连续亏损次数", "出现次数", "每个序列的平均亏损"],
index_format,
)
worksheet.write_column("A%d" % (next_row + 1), f_2_result["连续次数"], value_format)
worksheet.write_column("B%d" % (next_row + 1), f_2_result["出现次数"], value_format)
worksheet.write_column("C%d" % (next_row + 1), f_2_result["每个序列平均亏损"], value_format)
worksheet.write_column(
"C%d" % (next_row + 1), f_2_result["每个序列平均亏损"], value_format
)

# 这里开始画图
next_row += len(f_2_result) + 3
Expand Down
36 changes: 22 additions & 14 deletions meta/env_future_trading/wt4elegantrl/wtpy/apps/WtHotPicker.py
Original file line number Diff line number Diff line change
Expand Up @@ -576,24 +576,30 @@ def notify(
for exchg in hot_changes:
for pid in hot_changes[exchg]:
item = hot_changes[exchg][pid][-1]
content += "品种%s.%s的主力合约已切换,下个交易日(%s)生效, %s -> %s\n" % (
exchg,
pid,
dtStr,
item["from"],
item["to"],
content += (
"品种%s.%s的主力合约已切换,下个交易日(%s)生效, %s -> %s\n"
% (
exchg,
pid,
dtStr,
item["from"],
item["to"],
)
)

content += "\n"
for exchg in sec_changes:
for pid in sec_changes[exchg]:
item = sec_changes[exchg][pid][-1]
content += "品种%s.%s的次主力合约已切换,下个交易日(%s)生效, %s -> %s\n" % (
exchg,
pid,
dtStr,
item["from"],
item["to"],
content += (
"品种%s.%s的次主力合约已切换,下个交易日(%s)生效, %s -> %s\n"
% (
exchg,
pid,
dtStr,
item["from"],
item["to"],
)
)

msg_mp = MIMEMultipart()
Expand Down Expand Up @@ -910,7 +916,8 @@ def merge_switch_list(self, total, exchg, switch_list):
else:
total[exchg][pid].extend(switch_list[pid])
logging.info(
"[%s]品种%s主力切换规则追加%d条" % (exchg, pid, len(switch_list[pid]))
"[%s]品种%s主力切换规则追加%d条"
% (exchg, pid, len(switch_list[pid]))
)
bChanged = True
return bChanged, total
Expand Down Expand Up @@ -1060,7 +1067,8 @@ def execute_increment(
lastDate = str(marker["date"])
if lastDate >= endDate.strftime("%Y%m%d"):
logging.info(
"上次更新日期%s大于结束日期%s,退出更新" % (lastDate, endDate.strftime("%Y%m%d"))
"上次更新日期%s大于结束日期%s,退出更新"
% (lastDate, endDate.strftime("%Y%m%d"))
)
exit()
elif lastDate != "0":
Expand Down
11 changes: 8 additions & 3 deletions meta/env_future_trading/wt4elegantrl/wtpy/monitor/WatchDog.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,9 @@ def applyConf(self, appConf: dict):
url=self._mq_url, logger=self.__logger__
)
self._evt_receiver.run()
self.__logger__.info("应用%s开始接收%s的通知信息" % (self._id, self._mq_url))
self.__logger__.info(
"应用%s开始接收%s的通知信息" % (self._id, self._mq_url)
)

def getConf(self):
self._lock.acquire()
Expand Down Expand Up @@ -168,7 +170,8 @@ def is_running(self, pids) -> bool:
)
self._evt_receiver.run()
self.__logger__.info(
"应用%s开始接收%s的通知信息" % (self._id, self._mq_url)
"应用%s开始接收%s的通知信息"
% (self._id, self._mq_url)
)
except:
pass
Expand All @@ -188,7 +191,9 @@ def run(self):
url=self._mq_url, logger=self.__logger__, sink=self
)
self._evt_receiver.run()
self.__logger__.info("应用%s开始接收%s的通知信息" % (self._id, self._mq_url))
self.__logger__.info(
"应用%s开始接收%s的通知信息" % (self._id, self._mq_url)
)

try:
fullPath = os.path.join(self.__info__["folder"], self.__info__["param"])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
LastEditors: Wesley
LastEditTime: 2021-09-02 14:18:50
"""

import datetime
import hashlib
import json
Expand Down
9 changes: 7 additions & 2 deletions meta/env_future_trading/wt4elegantrl/wtpy/monitor/WtMonSvr.py
Original file line number Diff line number Diff line change
Expand Up @@ -782,7 +782,9 @@ def cmd_login():
usrInf["loginip"] = request.remote_addr
usrInf["logintime"] = now.strftime("%Y/%m/%d %H:%M:%S")

exptime = now + datetime.timedelta(minutes=360) # 360分钟令牌超时
exptime = now + datetime.timedelta(
minutes=360
) # 360分钟令牌超时
session["userinfo"] = usrInf
session["expiretime"] = exptime.replace(
tzinfo=pytz.timezone("UTC")
Expand Down Expand Up @@ -1704,7 +1706,10 @@ def cmd_del_app():
if len(id) == 0:
ret = {"result": -1, "message": "组合ID不能为空"}
elif self.__data_mgr__.has_group(id):
ret = {"result": -2, "message": "该调度任务是策略组合,请从组合管理删除"}
ret = {
"result": -2,
"message": "该调度任务是策略组合,请从组合管理删除",
}
elif not self._dog.has_app(id):
ret = {"result": -3, "message": "该调度任务不存在"}
elif self._dog.isRunning(id):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
LastEditors: Wesley
LastEditTime: 2021-08-16 17:29:42
"""

from .WtBtMon import WtBtMon
from .WtLogger import WtLogger
from .WtMonSvr import WtMonSvr
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
LastEditors: Wesley
LastEditTime: 2021-08-13 15:35:59
"""

import os
from ctypes import c_char_p
from ctypes import cdll
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
LastEditors: Wesley
LastEditTime: 2021-08-13 15:32:23
"""

import platform


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,9 @@ def on_stra_get_tick(
addr = addressof(curTick.contents) # 获取内存地址
ticks = [None] * count # 预先分配list的长度
for idx in range(count):
realTick = WTSTickStruct.from_address(addr) # 从内存中直接解析成WTSTickStruct
realTick = WTSTickStruct.from_address(
addr
) # 从内存中直接解析成WTSTickStruct
tick = dict()
tick["time"] = realTick.action_date * 1000000000 + realTick.action_time
tick["open"] = realTick.open
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
LastEditors: Wesley
LastEditTime: 2021-08-13 15:34:36
"""

import os
from ctypes import c_bool
from ctypes import c_char_p
Expand Down
Loading

0 comments on commit 484217c

Please sign in to comment.