Environment (RL)

TradingEnv

class qtrade.env.TradingEnv(data: DataFrame, cash: float = 10000, commission: Commission | None = None, margin_ratio: float = 1.0, trade_on_close: bool = True, window_size: int = 10, max_steps=3000, random_start: bool = False, action_scheme: ActionScheme | None = None, reward_scheme: RewardScheme | None = None, observer_scheme: ObserverScheme | None = None, render_mode: str | None = 'human', verbose: bool = False)[源代码]

基类:Env

自定义的 Gymnasium 交易环境, 使用 Position 类管理持仓

close()[源代码]

After the user has finished using the environment, close contains the code necessary to "clean up" the environment.

This is critical for closing rendering windows, database or HTTP connections. Calling close on an already closed environment has no effect and won't raise an error.

property closed_trades: tuple[Trade, ...]

Get the closed trades.

property current_time

Get the current time.

property data: DataFrame

Get the market data, can only see data up to the current index.

property filled_orders: tuple[Order, ...]

Get the filled orders.

get_trade_history() DataFrame[源代码]

Trade-by-trade DataFrame across all assets.

metadata: dict[str, Any] = {'render_fps': 12, 'render_modes': ['human', 'rgb_array']}
pause_rendering()[源代码]
plot(filename=None)[源代码]
property position: Position

Get the current position.

render(mode=None)[源代码]

Compute the render frames as specified by render_mode during the initialization of the environment.

The environment's metadata render modes (env.metadata["render_modes"]) should contain the possible ways to implement the render modes. In addition, list versions for most render modes is achieved through gymnasium.make which automatically applies a wrapper to collect rendered frames.

备注

As the render_mode is known during __init__, the objects used to render the environment state should be initialised in __init__.

By convention, if the render_mode is:

  • None (default): no render is computed.

  • "human": The environment is continuously rendered in the current display or terminal, usually for human consumption. This rendering should occur during step() and render() doesn't need to be called. Returns None.

  • "rgb_array": Return a single frame representing the current state of the environment. A frame is a np.ndarray with shape (x, y, 3) representing RGB values for an x-by-y pixel image.

  • "ansi": Return a strings (str) or StringIO.StringIO containing a terminal-style text representation for each time step. The text can include newlines and ANSI escape sequences (e.g. for colors).

  • "rgb_array_list" and "ansi_list": List based version of render modes are possible (except Human) through the wrapper, gymnasium.wrappers.RenderCollection that is automatically applied during gymnasium.make(..., render_mode="rgb_array_list"). The frames collected are popped after render() is called or reset().

备注

Make sure that your class's metadata "render_modes" key includes the list of supported modes.

在 0.25.0 版本发生变更: The render function was changed to no longer accept parameters, rather these parameters should be specified in the environment initialised, i.e., gymnasium.make("CartPole-v1", render_mode="human")

reset(seed: int | None = None, options: dict | None = None)[源代码]

Resets the environment to an initial internal state, returning an initial observation and info.

This method generates a new starting state often with some randomness to ensure that the agent explores the state space and learns a generalised policy about the environment. This randomness can be controlled with the seed parameter otherwise if the environment already has a random number generator and reset() is called with seed=None, the RNG is not reset.

Therefore, reset() should (in the typical use case) be called with a seed right after initialization and then never again.

For Custom environments, the first line of reset() should be super().reset(seed=seed) which implements the seeding correctly.

在 v0.25 版本发生变更: The return_info parameter was removed and now info is expected to be returned.

参数:
  • seed (optional int) -- The seed that is used to initialize the environment's PRNG (np_random) and the read-only attribute np_random_seed. If the environment does not already have a PRNG and seed=None (the default option) is passed, a seed will be chosen from some source of entropy (e.g. timestamp or /dev/urandom). However, if the environment already has a PRNG and seed=None is passed, the PRNG will not be reset and the env's np_random_seed will not be altered. If you pass an integer, the PRNG will be reset even if it already exists. Usually, you want to pass an integer right after the environment has been initialized and then never again. Please refer to the minimal example above to see this paradigm in action.

  • options (optional dict) -- Additional information to specify how the environment is reset (optional, depending on the specific environment)

Returns:
  • observation (ObsType) -- Observation of the initial state. This will be an element of observation_space (typically a numpy array) and is analogous to the observation returned by step().

  • info (dictionary) -- This dictionary contains auxiliary information complementing observation. It should be analogous to the info returned by step().

save_rendering(filepath)[源代码]
show_stats()[源代码]
step(action)[源代码]

Run one timestep of the environment's dynamics using the agent actions.

When the end of an episode is reached (terminated or truncated), it is necessary to call reset() to reset this environment's state for the next episode.

在 0.26 版本发生变更: The Step API was changed removing done in favor of terminated and truncated to make it clearer to users when the environment had terminated or truncated which is critical for reinforcement learning bootstrapping algorithms.

参数:

action (ActType) -- an action provided by the agent to update the environment state.

Returns:
  • observation (ObsType) -- An element of the environment's observation_space as the next observation due to the agent actions. An example is a numpy array containing the positions and velocities of the pole in CartPole.

  • reward (SupportsFloat) -- The reward as a result of taking the action.

  • terminated (bool) -- Whether the agent reaches the terminal state (as defined under the MDP of the task) which can be positive or negative. An example is reaching the goal state or moving into the lava from the Sutton and Barto Gridworld. If true, the user needs to call reset().

  • truncated (bool) -- Whether the truncation condition outside the scope of the MDP is satisfied. Typically, this is a timelimit, but could also be used to indicate an agent physically going out of bounds. Can be used to end the episode prematurely before a terminal state is reached. If true, the user needs to call reset().

  • info (dict) -- Contains auxiliary diagnostic information (helpful for debugging, learning, and logging). This might, for instance, contain: metrics that describe the agent's performance state, variables that are hidden from observations, or individual reward terms that are combined to produce the total reward. In OpenAI Gym <v26, it contains "TimeLimit.truncated" to distinguish truncation and termination, however this is deprecated in favour of returning terminated and truncated variables.

  • done (bool) -- (Deprecated) A boolean value for if the episode has ended, in which case further step() calls will return undefined results. This was removed in OpenAI Gym v26 in favor of terminated and truncated attributes. A done signal may be emitted for different reasons: Maybe the task underlying the environment was solved successfully, a certain timelimit was exceeded, or the physics simulation has entered an invalid state.

Action / Reward / Observer Schemes

class qtrade.env.ActionScheme[源代码]
abstract property action_space: Space

The action space of the TradingEnv. (Space, read-only)

abstract get_orders(action: Any, env: TradingEnv) list[Order][源代码]

Returns a list of orders to be executed based on the action.

class qtrade.env.RewardScheme[源代码]
abstract get_reward(env: TradingEnv) float[源代码]

Calculate the reward based on the current environment state.

reset() None[源代码]

Resets the reward scheme.

class qtrade.env.ObserverScheme[源代码]

Abstract base class for observation schemes.

abstract get_observation(env: TradingEnv) Any[源代码]

Generates an observation from the environment.

参数:

env (TradingEnv) -- The trading environment instance.

Returns:

Any -- The observation data.

abstract property observation_space: Space

Defines the observation space.

Returns:

Space -- The observation space of the environment.