Repository navigation
Expand file tree
/
Copy pathenv.py
More file actions
95 lines (75 loc) · 2.84 KB
/
Copy pathenv.py
File metadata and controls
95 lines (75 loc) · 2.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from typing import Union
from ..backtest.executor import BaseExecutor
from .interpreter import StateInterpreter, ActionInterpreter
from ..utils import init_instance_by_config
from .interpreter import BaseInterpreter
class BaseRLEnv:
"""Base environment for reinforcement learning"""
def reset(self, **kwargs):
raise NotImplementedError("reset is not implemented!")
def step(self, action):
"""
step method of rl env
Parameters
----------
action :
action from rl policy
Returns
-------
env state to rl policy
"""
raise NotImplementedError("step is not implemented!")
class QlibRLEnv:
"""qlib-based RL env"""
def __init__(
self,
executor: BaseExecutor,
):
"""
Parameters
----------
executor : BaseExecutor
qlib multi-level/single-level executor, which can be regarded as gamecore in RL
"""
self.executor = executor
def reset(self, **kwargs):
self.executor.reset(**kwargs)
class QlibIntRLEnv(QlibRLEnv):
"""(Qlib)-based RL (Env) with (Interpreter)"""
def __init__(
self,
executor: BaseExecutor,
state_interpreter: Union[dict, StateInterpreter],
action_interpreter: Union[dict, ActionInterpreter],
):
"""
Parameters
----------
state_interpreter : Union[dict, StateInterpreter]
interpretor that interprets the qlib execute result into rl env state.
action_interpreter : Union[dict, ActionInterpreter]
interpretor that interprets the rl agent action into qlib order list
"""
super(QlibIntRLEnv, self).__init__(executor=executor)
self.state_interpreter = init_instance_by_config(state_interpreter, accept_types=StateInterpreter)
self.action_interpreter = init_instance_by_config(action_interpreter, accept_types=ActionInterpreter)
def step(self, action):
"""
step method of rl env, it run as following step:
- Use `action_interpreter.interpret` method to interpret the agent action into order list
- Execute the order list with qlib executor, and get the executed result
- Use `state_interpreter.interpret` method to interpret the executed result into env state
Parameters
----------
action :
action from rl policy
Returns
-------
env state to rl policy
"""
_interpret_decision = self.action_interpreter.interpret(action=action)
_execute_result = self.executor.execute(trade_decision=_interpret_decision)
_interpret_state = self.state_interpreter.interpret(execute_result=_execute_result)
return _interpret_state