|
| 1 | +""" |
| 2 | +This code is taken and slightly modified from: |
| 3 | +https://www.tensortrade.org/en/latest/agents/overview.html#ray |
| 4 | +""" |
| 5 | +import numpy as np |
| 6 | +from ray import tune |
| 7 | +from ray.tune.registry import register_env |
| 8 | +import tensortrade.env.default as default |
| 9 | +from tensortrade.feed.core import DataFeed, Stream |
| 10 | +from tensortrade.oms.instruments import Instrument |
| 11 | +from tensortrade.oms.exchanges import Exchange |
| 12 | +from tensortrade.oms.services.execution.simulated import execute_order |
| 13 | +from tensortrade.oms.wallets import Wallet, Portfolio |
| 14 | + |
| 15 | + |
| 16 | +USD = Instrument("USD", 2, "U.S. Dollar") |
| 17 | +TTC = Instrument("TTC", 8, "TensorTrade Coin") |
| 18 | + |
| 19 | + |
| 20 | +def create_env(config): |
| 21 | + x = np.arange(0, 2*np.pi, 2*np.pi / 1000) |
| 22 | + p = Stream.source(50*np.sin(3*x) + 100, |
| 23 | + dtype="float").rename("USD-TTC") |
| 24 | + |
| 25 | + coinbase = Exchange("coinbase", service=execute_order)( |
| 26 | + p |
| 27 | + ) |
| 28 | + |
| 29 | + cash = Wallet(coinbase, 100000 * USD) |
| 30 | + asset = Wallet(coinbase, 0 * TTC) |
| 31 | + |
| 32 | + portfolio = Portfolio(USD, [ |
| 33 | + cash, |
| 34 | + asset |
| 35 | + ]) |
| 36 | + |
| 37 | + feed = DataFeed([ |
| 38 | + p, |
| 39 | + p.rolling(window=10).mean().rename("fast"), |
| 40 | + p.rolling(window=50).mean().rename("medium"), |
| 41 | + p.rolling(window=100).mean().rename("slow"), |
| 42 | + p.log().diff().fillna(0).rename("lr") |
| 43 | + ]) |
| 44 | + |
| 45 | + reward_scheme = default.rewards.SimpleProfit() |
| 46 | + |
| 47 | + action_scheme = default.actions.BSH( |
| 48 | + cash=cash, |
| 49 | + asset=asset |
| 50 | + ) |
| 51 | + |
| 52 | + env = default.create( |
| 53 | + feed=feed, |
| 54 | + portfolio=portfolio, |
| 55 | + action_scheme=action_scheme, |
| 56 | + reward_scheme=reward_scheme, |
| 57 | + window_size=config["window_size"], |
| 58 | + max_allowed_loss=0.6 |
| 59 | + ) |
| 60 | + return env |
| 61 | + |
| 62 | +register_env("TradingEnv", create_env) |
| 63 | + |
| 64 | + |
| 65 | +analysis = tune.run( |
| 66 | + "PPO", |
| 67 | + stop={ |
| 68 | + "episode_reward_mean": 500 |
| 69 | + }, |
| 70 | + config={ |
| 71 | + "env": "TradingEnv", |
| 72 | + "env_config": { |
| 73 | + "window_size": 25 |
| 74 | + }, |
| 75 | + "ignore_worker_failures": True, |
| 76 | + "num_workers": 60, |
| 77 | + "num_gpus": 0, |
| 78 | + "observation_filter": "MeanStdFilter", |
| 79 | + }, |
| 80 | + checkpoint_freq=5 |
| 81 | +) |
0 commit comments