tensortrade 1.0.0b0__py3-none-any.whl → 1.0.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tensortrade/__init__.py +23 -16
- tensortrade/agents/__init__.py +7 -7
- tensortrade/agents/a2c_agent.py +239 -237
- tensortrade/agents/agent.py +52 -49
- tensortrade/agents/dqn_agent.py +375 -202
- tensortrade/agents/parallel/__init__.py +5 -5
- tensortrade/agents/parallel/parallel_dqn_agent.py +172 -170
- tensortrade/agents/parallel/parallel_dqn_model.py +85 -83
- tensortrade/agents/parallel/parallel_dqn_optimizer.py +96 -90
- tensortrade/agents/parallel/parallel_dqn_trainer.py +97 -95
- tensortrade/agents/parallel/parallel_queue.py +95 -92
- tensortrade/agents/replay_memory.py +54 -52
- tensortrade/core/__init__.py +6 -6
- tensortrade/core/base.py +167 -173
- tensortrade/core/clock.py +48 -48
- tensortrade/core/component.py +129 -129
- tensortrade/core/context.py +182 -182
- tensortrade/core/exceptions.py +211 -211
- tensortrade/core/registry.py +45 -45
- tensortrade/data/__init__.py +1 -1
- tensortrade/data/cdd.py +152 -151
- tensortrade/env/__init__.py +2 -2
- tensortrade/env/default/__init__.py +96 -89
- tensortrade/env/default/actions.py +428 -399
- tensortrade/env/default/informers.py +14 -16
- tensortrade/env/default/observers.py +475 -284
- tensortrade/env/default/renderers.py +787 -586
- tensortrade/env/default/rewards.py +360 -240
- tensortrade/env/default/stoppers.py +33 -33
- tensortrade/env/generic/__init__.py +22 -22
- tensortrade/env/generic/components/__init__.py +13 -13
- tensortrade/env/generic/components/action_scheme.py +54 -54
- tensortrade/env/generic/components/informer.py +45 -45
- tensortrade/env/generic/components/observer.py +59 -59
- tensortrade/env/generic/components/renderer.py +86 -86
- tensortrade/env/generic/components/reward_scheme.py +44 -44
- tensortrade/env/generic/components/stopper.py +46 -46
- tensortrade/env/generic/environment.py +211 -163
- tensortrade/feed/__init__.py +5 -5
- tensortrade/feed/api/__init__.py +5 -5
- tensortrade/feed/api/boolean/__init__.py +44 -44
- tensortrade/feed/api/boolean/operations.py +20 -20
- tensortrade/feed/api/float/__init__.py +49 -48
- tensortrade/feed/api/float/accumulators.py +199 -199
- tensortrade/feed/api/float/imputation.py +40 -40
- tensortrade/feed/api/float/operations.py +233 -233
- tensortrade/feed/api/float/ordering.py +105 -105
- tensortrade/feed/api/float/utils.py +140 -140
- tensortrade/feed/api/float/window/__init__.py +3 -3
- tensortrade/feed/api/float/window/ewm.py +459 -452
- tensortrade/feed/api/float/window/expanding.py +189 -185
- tensortrade/feed/api/float/window/rolling.py +227 -217
- tensortrade/feed/api/generic/__init__.py +4 -4
- tensortrade/feed/api/generic/imputation.py +51 -51
- tensortrade/feed/api/generic/operators.py +118 -121
- tensortrade/feed/api/generic/reduce.py +119 -119
- tensortrade/feed/api/generic/warmup.py +54 -54
- tensortrade/feed/api/string/__init__.py +44 -43
- tensortrade/feed/api/string/operations.py +135 -131
- tensortrade/feed/core/__init__.py +3 -3
- tensortrade/feed/core/accessors.py +30 -30
- tensortrade/feed/core/base.py +634 -584
- tensortrade/feed/core/feed.py +120 -59
- tensortrade/feed/core/methods.py +37 -37
- tensortrade/feed/core/mixins.py +23 -23
- tensortrade/feed/core/operators.py +174 -174
- tensortrade/oms/__init__.py +2 -2
- tensortrade/oms/exchanges/__init__.py +1 -1
- tensortrade/oms/exchanges/exchange.py +176 -164
- tensortrade/oms/instruments/__init__.py +5 -5
- tensortrade/oms/instruments/exchange_pair.py +44 -44
- tensortrade/oms/instruments/instrument.py +161 -161
- tensortrade/oms/instruments/quantity.py +321 -318
- tensortrade/oms/instruments/trading_pair.py +58 -58
- tensortrade/oms/orders/__init__.py +13 -13
- tensortrade/oms/orders/broker.py +129 -125
- tensortrade/oms/orders/create.py +312 -312
- tensortrade/oms/orders/criteria.py +218 -218
- tensortrade/oms/orders/order.py +368 -368
- tensortrade/oms/orders/order_listener.py +62 -62
- tensortrade/oms/orders/order_spec.py +102 -102
- tensortrade/oms/orders/trade.py +159 -159
- tensortrade/oms/services/__init__.py +2 -2
- tensortrade/oms/services/execution/__init__.py +4 -4
- tensortrade/oms/services/execution/simulated.py +197 -183
- tensortrade/oms/services/slippage/__init__.py +21 -21
- tensortrade/oms/services/slippage/random_slippage_model.py +56 -56
- tensortrade/oms/services/slippage/slippage_model.py +46 -46
- tensortrade/oms/wallets/__init__.py +20 -20
- tensortrade/oms/wallets/ledger.py +92 -92
- tensortrade/oms/wallets/portfolio.py +330 -329
- tensortrade/oms/wallets/wallet.py +376 -365
- tensortrade/stochastic/__init__.py +12 -12
- tensortrade/stochastic/processes/brownian_motion.py +55 -55
- tensortrade/stochastic/processes/cox.py +103 -103
- tensortrade/stochastic/processes/fbm.py +88 -88
- tensortrade/stochastic/processes/gbm.py +129 -129
- tensortrade/stochastic/processes/heston.py +281 -281
- tensortrade/stochastic/processes/merton.py +91 -91
- tensortrade/stochastic/processes/ornstein_uhlenbeck.py +113 -113
- tensortrade/stochastic/utils/__init__.py +2 -2
- tensortrade/stochastic/utils/helpers.py +180 -179
- tensortrade/stochastic/utils/parameters.py +172 -172
- tensortrade/version.py +1 -1
- tensortrade-1.0.4.dist-info/METADATA +65 -0
- tensortrade-1.0.4.dist-info/RECORD +114 -0
- {tensortrade-1.0.0b0.dist-info → tensortrade-1.0.4.dist-info}/WHEEL +1 -1
- {tensortrade-1.0.0b0.dist-info → tensortrade-1.0.4.dist-info/licenses}/LICENSE +200 -200
- tensortrade-1.0.0b0.dist-info/METADATA +0 -74
- tensortrade-1.0.0b0.dist-info/RECORD +0 -114
- {tensortrade-1.0.0b0.dist-info → tensortrade-1.0.4.dist-info}/top_level.txt +0 -0
tensortrade/__init__.py
CHANGED
|
@@ -1,16 +1,23 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
from . import
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
1
|
+
import sys
|
|
2
|
+
|
|
3
|
+
if sys.version_info < (3, 12):
|
|
4
|
+
raise RuntimeError(
|
|
5
|
+
f"TensorTrade requires Python 3.12 or higher. "
|
|
6
|
+
f"You are using Python {sys.version_info.major}.{sys.version_info.minor}."
|
|
7
|
+
)
|
|
8
|
+
|
|
9
|
+
from . import core
|
|
10
|
+
from . import data
|
|
11
|
+
from . import feed
|
|
12
|
+
from tensortrade.oms import (
|
|
13
|
+
orders,
|
|
14
|
+
wallets,
|
|
15
|
+
instruments,
|
|
16
|
+
exchanges,
|
|
17
|
+
services
|
|
18
|
+
)
|
|
19
|
+
from . import env
|
|
20
|
+
from . import stochastic
|
|
21
|
+
from . import agents
|
|
22
|
+
|
|
23
|
+
from .version import __version__
|
tensortrade/agents/__init__.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
from .agent import Agent
|
|
2
|
-
from .replay_memory import ReplayMemory
|
|
3
|
-
|
|
4
|
-
from .dqn_agent import DQNAgent, DQNTransition
|
|
5
|
-
from .a2c_agent import A2CAgent, A2CTransition
|
|
6
|
-
|
|
7
|
-
from .parallel import ParallelDQNAgent
|
|
1
|
+
from .agent import Agent
|
|
2
|
+
from .replay_memory import ReplayMemory
|
|
3
|
+
|
|
4
|
+
from .dqn_agent import DQNAgent, DQNTransition
|
|
5
|
+
from .a2c_agent import A2CAgent, A2CTransition
|
|
6
|
+
|
|
7
|
+
from .parallel import ParallelDQNAgent
|
tensortrade/agents/a2c_agent.py
CHANGED
|
@@ -1,237 +1,239 @@
|
|
|
1
|
-
# Copyright 2019 The TensorTrade Authors.
|
|
2
|
-
#
|
|
3
|
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
-
# you may not use this file except in compliance with the License.
|
|
5
|
-
# You may obtain a copy of the License at
|
|
6
|
-
#
|
|
7
|
-
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
-
#
|
|
9
|
-
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
-
# See the License for the specific language governing permissions and
|
|
13
|
-
# limitations under the License
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
"""
|
|
17
|
-
References:
|
|
18
|
-
- http://inoryy.com/post/tensorflow2-deep-reinforcement-learning/#agent-interface
|
|
19
|
-
"""
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
import random
|
|
23
|
-
import numpy as np
|
|
24
|
-
import tensorflow as tf
|
|
25
|
-
|
|
26
|
-
from collections import namedtuple
|
|
27
|
-
|
|
28
|
-
from tensortrade.agents import Agent, ReplayMemory
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
self.
|
|
43
|
-
|
|
44
|
-
self.
|
|
45
|
-
|
|
46
|
-
self.
|
|
47
|
-
|
|
48
|
-
self.
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
tf.keras.layers.
|
|
55
|
-
tf.keras.layers.Conv1D(filters=
|
|
56
|
-
tf.keras.layers.MaxPooling1D(pool_size=2),
|
|
57
|
-
tf.keras.layers.
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
tf.keras.layers.Dense(
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
state
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
1
|
+
# Copyright 2019 The TensorTrade Authors.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
"""
|
|
17
|
+
References:
|
|
18
|
+
- http://inoryy.com/post/tensorflow2-deep-reinforcement-learning/#agent-interface
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from deprecated import deprecated
|
|
22
|
+
import random
|
|
23
|
+
import numpy as np
|
|
24
|
+
import tensorflow as tf
|
|
25
|
+
|
|
26
|
+
from collections import namedtuple
|
|
27
|
+
|
|
28
|
+
from tensortrade.agents import Agent, ReplayMemory
|
|
29
|
+
from datetime import datetime
|
|
30
|
+
|
|
31
|
+
A2CTransition = namedtuple('A2CTransition', ['state', 'action', 'reward', 'done', 'value'])
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@deprecated(version='1.0.4', reason="Builtin agents are being deprecated in favor of external implementations (ie: Ray)")
|
|
35
|
+
class A2CAgent(Agent):
|
|
36
|
+
|
|
37
|
+
def __init__(self,
|
|
38
|
+
env: 'TradingEnvironment',
|
|
39
|
+
shared_network: tf.keras.Model = None,
|
|
40
|
+
actor_network: tf.keras.Model = None,
|
|
41
|
+
critic_network: tf.keras.Model = None):
|
|
42
|
+
self.env = env
|
|
43
|
+
self.n_actions = env.action_space.n
|
|
44
|
+
self.observation_shape = env.observation_space.shape
|
|
45
|
+
|
|
46
|
+
self.shared_network = shared_network or self._build_shared_network()
|
|
47
|
+
self.actor_network = actor_network or self._build_actor_network()
|
|
48
|
+
self.critic_network = critic_network or self._build_critic_network()
|
|
49
|
+
|
|
50
|
+
self.env.agent_id = self.id
|
|
51
|
+
|
|
52
|
+
def _build_shared_network(self):
|
|
53
|
+
network = tf.keras.Sequential([
|
|
54
|
+
tf.keras.layers.InputLayer(input_shape=self.observation_shape),
|
|
55
|
+
tf.keras.layers.Conv1D(filters=64, kernel_size=6, padding="same", activation="tanh"),
|
|
56
|
+
tf.keras.layers.MaxPooling1D(pool_size=2),
|
|
57
|
+
tf.keras.layers.Conv1D(filters=32, kernel_size=3, padding="same", activation="tanh"),
|
|
58
|
+
tf.keras.layers.MaxPooling1D(pool_size=2),
|
|
59
|
+
tf.keras.layers.Flatten()
|
|
60
|
+
])
|
|
61
|
+
|
|
62
|
+
return network
|
|
63
|
+
|
|
64
|
+
def _build_actor_network(self):
|
|
65
|
+
actor_head = tf.keras.Sequential([
|
|
66
|
+
tf.keras.layers.Dense(50, activation='relu'),
|
|
67
|
+
tf.keras.layers.Dense(self.n_actions, activation='relu')
|
|
68
|
+
])
|
|
69
|
+
|
|
70
|
+
return tf.keras.Sequential([self.shared_network, actor_head])
|
|
71
|
+
|
|
72
|
+
def _build_critic_network(self):
|
|
73
|
+
critic_head = tf.keras.Sequential([
|
|
74
|
+
tf.keras.layers.Dense(50, activation='relu'),
|
|
75
|
+
tf.keras.layers.Dense(25, activation='relu'),
|
|
76
|
+
tf.keras.layers.Dense(1, activation='relu')
|
|
77
|
+
])
|
|
78
|
+
|
|
79
|
+
return tf.keras.Sequential([self.shared_network, critic_head])
|
|
80
|
+
|
|
81
|
+
def restore(self, path: str, **kwargs):
|
|
82
|
+
actor_filename: str = kwargs.get('actor_filename', None)
|
|
83
|
+
critic_filename: str = kwargs.get('critic_filename', None)
|
|
84
|
+
|
|
85
|
+
if not actor_filename or not critic_filename:
|
|
86
|
+
raise ValueError(
|
|
87
|
+
'The `restore` method requires a directory `path`, a `critic_filename`, and an `actor_filename`.')
|
|
88
|
+
|
|
89
|
+
self.actor_network = tf.keras.models.load_model(path + actor_filename)
|
|
90
|
+
self.critic_network = tf.keras.models.load_model(path + critic_filename)
|
|
91
|
+
|
|
92
|
+
def save(self, path: str, **kwargs):
|
|
93
|
+
episode: int = kwargs.get('episode', None)
|
|
94
|
+
|
|
95
|
+
if episode:
|
|
96
|
+
suffix = self.id[:7] + "__" + datetime.now().strftime("%Y%m%d_%H%M%S") + ".hdf5"
|
|
97
|
+
actor_filename = "actor_network__" + suffix
|
|
98
|
+
critic_filename = "critic_network__" + suffix
|
|
99
|
+
else:
|
|
100
|
+
actor_filename = "actor_network__" + self.id[:7] + "__" + datetime.now().strftime("%Y%m%d_%H%M%S") + ".hdf5"
|
|
101
|
+
critic_filename = "critic_network__" + self.id[:7] + "__" + datetime.now().strftime("%Y%m%d_%H%M%S") + ".hdf5"
|
|
102
|
+
|
|
103
|
+
self.actor_network.save(path + actor_filename)
|
|
104
|
+
self.critic_network.save(path + critic_filename)
|
|
105
|
+
|
|
106
|
+
def get_action(self, state: np.ndarray, **kwargs) -> int:
|
|
107
|
+
threshold: float = kwargs.get('threshold', 0)
|
|
108
|
+
|
|
109
|
+
rand = random.random()
|
|
110
|
+
|
|
111
|
+
if rand < threshold:
|
|
112
|
+
return np.random.choice(self.n_actions)
|
|
113
|
+
else:
|
|
114
|
+
logits = self.actor_network(state[None, :], training=False)
|
|
115
|
+
return tf.squeeze(tf.squeeze(tf.random.categorical(logits, 1), axis=-1), axis=-1)
|
|
116
|
+
|
|
117
|
+
def _apply_gradient_descent(self,
|
|
118
|
+
memory: ReplayMemory,
|
|
119
|
+
batch_size: int,
|
|
120
|
+
learning_rate: float,
|
|
121
|
+
discount_factor: float,
|
|
122
|
+
entropy_c: float,):
|
|
123
|
+
huber_loss = tf.keras.losses.Huber()
|
|
124
|
+
wsce_loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
|
|
125
|
+
optimizer = tf.keras.optimizers.Adam(lr=learning_rate)
|
|
126
|
+
|
|
127
|
+
transitions = memory.tail(batch_size)
|
|
128
|
+
batch = A2CTransition(*zip(*transitions))
|
|
129
|
+
|
|
130
|
+
states = tf.convert_to_tensor(batch.state)
|
|
131
|
+
actions = tf.convert_to_tensor(batch.action)
|
|
132
|
+
rewards = tf.convert_to_tensor(batch.reward, dtype=tf.float32)
|
|
133
|
+
dones = tf.convert_to_tensor(batch.done)
|
|
134
|
+
values = tf.convert_to_tensor(batch.value)
|
|
135
|
+
|
|
136
|
+
returns = []
|
|
137
|
+
exp_weighted_return = 0
|
|
138
|
+
|
|
139
|
+
for reward, done in zip(rewards[::-1], dones[::-1]):
|
|
140
|
+
exp_weighted_return = reward + discount_factor * exp_weighted_return * (1 - int(done))
|
|
141
|
+
returns += [exp_weighted_return]
|
|
142
|
+
|
|
143
|
+
returns = returns[::-1]
|
|
144
|
+
|
|
145
|
+
with tf.GradientTape() as tape:
|
|
146
|
+
state_values = self.critic_network(states)
|
|
147
|
+
critic_loss_value = huber_loss(returns, state_values)
|
|
148
|
+
|
|
149
|
+
gradients = tape.gradient(critic_loss_value, self.critic_network.trainable_variables)
|
|
150
|
+
optimizer.apply_gradients(zip(gradients, self.critic_network.trainable_variables))
|
|
151
|
+
|
|
152
|
+
with tf.GradientTape() as tape:
|
|
153
|
+
returns = tf.reshape(returns, [batch_size, 1])
|
|
154
|
+
advantages = returns - values
|
|
155
|
+
|
|
156
|
+
actions = tf.cast(actions, tf.int32)
|
|
157
|
+
logits = self.actor_network(states)
|
|
158
|
+
policy_loss_value = wsce_loss(actions, logits, sample_weight=advantages)
|
|
159
|
+
|
|
160
|
+
probs = tf.nn.softmax(logits)
|
|
161
|
+
entropy_loss_value = tf.keras.losses.categorical_crossentropy(probs, probs)
|
|
162
|
+
policy_total_loss_value = policy_loss_value - entropy_c * entropy_loss_value
|
|
163
|
+
|
|
164
|
+
gradients = tape.gradient(policy_total_loss_value,
|
|
165
|
+
self.actor_network.trainable_variables)
|
|
166
|
+
optimizer.apply_gradients(zip(gradients, self.actor_network.trainable_variables))
|
|
167
|
+
|
|
168
|
+
def train(self,
|
|
169
|
+
n_steps: int = None,
|
|
170
|
+
n_episodes: int = None,
|
|
171
|
+
save_every: int = None,
|
|
172
|
+
save_path: str = None,
|
|
173
|
+
callback: callable = None,
|
|
174
|
+
**kwargs) -> float:
|
|
175
|
+
batch_size: int = kwargs.get('batch_size', 128)
|
|
176
|
+
discount_factor: float = kwargs.get('discount_factor', 0.9999)
|
|
177
|
+
learning_rate: float = kwargs.get('learning_rate', 0.0001)
|
|
178
|
+
eps_start: float = kwargs.get('eps_start', 0.9)
|
|
179
|
+
eps_end: float = kwargs.get('eps_end', 0.05)
|
|
180
|
+
eps_decay_steps: int = kwargs.get('eps_decay_steps', 200)
|
|
181
|
+
entropy_c: int = kwargs.get('entropy_c', 0.0001)
|
|
182
|
+
memory_capacity: int = kwargs.get('memory_capacity', 1000)
|
|
183
|
+
|
|
184
|
+
memory = ReplayMemory(memory_capacity, transition_type=A2CTransition)
|
|
185
|
+
episode = 0
|
|
186
|
+
steps_done = 0
|
|
187
|
+
total_reward = 0
|
|
188
|
+
stop_training = False
|
|
189
|
+
|
|
190
|
+
if n_steps and not n_episodes:
|
|
191
|
+
n_episodes = np.iinfo(np.int32).max
|
|
192
|
+
|
|
193
|
+
print('==== AGENT ID: {} ===='.format(self.id))
|
|
194
|
+
|
|
195
|
+
while episode < n_episodes and not stop_training:
|
|
196
|
+
state = self.env.reset()
|
|
197
|
+
done = False
|
|
198
|
+
|
|
199
|
+
print('==== EPISODE ID ({}/{}): {} ===='.format(episode + 1,
|
|
200
|
+
n_episodes,
|
|
201
|
+
self.env.episode_id))
|
|
202
|
+
|
|
203
|
+
while not done:
|
|
204
|
+
threshold = eps_end + (eps_start - eps_end) * np.exp(-steps_done / eps_decay_steps)
|
|
205
|
+
action = self.get_action(state, threshold=threshold)
|
|
206
|
+
next_state, reward, done, _ = self.env.step(action)
|
|
207
|
+
|
|
208
|
+
value = self.critic_network(state[None, :], training=False)
|
|
209
|
+
value = tf.squeeze(value, axis=-1)
|
|
210
|
+
|
|
211
|
+
memory.push(state, action, reward, done, value)
|
|
212
|
+
|
|
213
|
+
state = next_state
|
|
214
|
+
total_reward += reward
|
|
215
|
+
steps_done += 1
|
|
216
|
+
|
|
217
|
+
if len(memory) < batch_size:
|
|
218
|
+
continue
|
|
219
|
+
|
|
220
|
+
self._apply_gradient_descent(memory,
|
|
221
|
+
batch_size,
|
|
222
|
+
learning_rate,
|
|
223
|
+
discount_factor,
|
|
224
|
+
entropy_c)
|
|
225
|
+
|
|
226
|
+
if n_steps and steps_done >= n_steps:
|
|
227
|
+
done = True
|
|
228
|
+
stop_training = True
|
|
229
|
+
|
|
230
|
+
is_checkpoint = save_every and episode % save_every == 0
|
|
231
|
+
|
|
232
|
+
if save_path and (is_checkpoint or episode == n_episodes):
|
|
233
|
+
self.save(save_path, episode=episode)
|
|
234
|
+
|
|
235
|
+
episode += 1
|
|
236
|
+
|
|
237
|
+
mean_reward = total_reward / steps_done
|
|
238
|
+
|
|
239
|
+
return mean_reward
|
tensortrade/agents/agent.py
CHANGED
|
@@ -1,49 +1,52 @@
|
|
|
1
|
-
# Copyright 2019 The TensorTrade Authors.
|
|
2
|
-
#
|
|
3
|
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
-
# you may not use this file except in compliance with the License.
|
|
5
|
-
# You may obtain a copy of the License at
|
|
6
|
-
#
|
|
7
|
-
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
-
#
|
|
9
|
-
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
-
# See the License for the specific language governing permissions and
|
|
13
|
-
# limitations under the License
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
from
|
|
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
|
-
|
|
1
|
+
# Copyright 2019 The TensorTrade Authors.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
from deprecated import deprecated
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
|
|
20
|
+
from abc import ABCMeta, abstractmethod
|
|
21
|
+
|
|
22
|
+
from tensortrade.core import Identifiable
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@deprecated(version='1.0.4', reason="Builtin agents are being deprecated in favor of external implementations (ie: Ray)")
|
|
26
|
+
class Agent(Identifiable, metaclass=ABCMeta):
|
|
27
|
+
|
|
28
|
+
@abstractmethod
|
|
29
|
+
def restore(self, path: str, **kwargs):
|
|
30
|
+
"""Restore the agent from the file specified in `path`."""
|
|
31
|
+
raise NotImplementedError()
|
|
32
|
+
|
|
33
|
+
@abstractmethod
|
|
34
|
+
def save(self, path: str, **kwargs):
|
|
35
|
+
"""Save the agent to the directory specified in `path`."""
|
|
36
|
+
raise NotImplementedError()
|
|
37
|
+
|
|
38
|
+
@abstractmethod
|
|
39
|
+
def get_action(self, state: np.ndarray, **kwargs) -> int:
|
|
40
|
+
"""Get an action for a specific state in the environment."""
|
|
41
|
+
raise NotImplementedError()
|
|
42
|
+
|
|
43
|
+
@abstractmethod
|
|
44
|
+
def train(self,
|
|
45
|
+
n_steps: int = None,
|
|
46
|
+
n_episodes: int = 10000,
|
|
47
|
+
save_every: int = None,
|
|
48
|
+
save_path: str = None,
|
|
49
|
+
callback: callable = None,
|
|
50
|
+
**kwargs) -> float:
|
|
51
|
+
"""Train the agent in the environment and return the mean reward."""
|
|
52
|
+
raise NotImplementedError()
|