please predict close from OHLC data using stable_baselines3 DDPG and gymnasium not gym
Assistant
To predict the closing price from OHLC data using the DDPG (Deep Deterministic Policy Gradient) algorithm in the stable_baselines3 library along with gymnasium, you'll need to follow a structured approach to set up your environment, define the problem, and train your model. Below are the key steps and a basic outline to help you implement this:
Prerequisites
Install Required Libraries:
Make sure you have installed stable-baselines3, gymnasium, and other necessary packages like numpy and pandas.
import numpy as np
import pandas as pd
from stable_baselines3 import DDPG
from stable_baselines3.common.noise import NormalActionNoise
from gymnasium import Env
from gymnasium.spaces import Box
Define a Custom Gymnasium Environment
You need to create a custom environment that represents your OHLC data and allows the agent to interact with it:
model.learn(total_timesteps=10000) # You can adjust the number of timesteps
Use the Model
After training, you can use the model to predict:
python
obs = env.reset()
for _ in range(len(ohlc_data) - window_size):
action, _states = model.predict(obs, deterministic=True)
obs, rewards, dones, info = env.step(action)
if dones:
break
Important Notes
Data Splitting: Ensure you split your data into training and testing sets to validate the performance.
Reward Function: Customize the reward function to better suit your needs and improve model performance.
Parameter Tuning: The DDPG model and action noise parameters should be tuned for optimal performance.
This example provides a framework. You'll still need to adjust various components to suit your specific use case, such as the data handling, reward structure, and model parameters.
User
File "C:\ProgramData\anaconda3\envs\test1\lib\site-packages\stable_baselines3\common\monitor.py", line 83, in reset
return self.env.reset(**kwargs)
TypeError: OHLCKEnv.reset() got an unexpected keyword argument 'seed'
Assistant
The error you're encountering is due to the new gymnasium API changes, where reset methods can optionally accept a seed keyword argument for reproducibility. To resolve this issue, you need to update the reset method in your custom environment to handle these keyword arguments. You can modify the reset method of your OHLCKEnv class as follows:
python
class OHLCKEnv(Env):
def __init__(self, data, window_size):
super(OHLCKEnv, self).__init__()
self.data = data
self.window_size = window_size
self.current_step = 0
# Define action and observation space
self.action_space = Box(low=-1, high=1, shape=(1,), dtype=np.float32)
self.observation_space = Box(low=-np.inf, high=np.inf, shape=(window_size, 4), dtype=np.float32)
def reset(self, *, seed=None, options=None):
# Seed the environment for reproducibility
if seed is not None:
np.random.seed(seed)
self.current_step = 0
return self._next_observation(), {}
def _next_observation(self):
obs = self.data.iloc[self.current_step:self.current_step + self.window_size].values
return obs
def step(self, action):
reward = self._take_action(action)
self.current_step += 1
done = self.current_step >= len(self.data) - self.window_size
obs = self._next_observation() if not done else np.zeros(self.observation_space.shape)
return obs, reward, done, {"info": "Additional info, if needed"}
def _take_action(self, action):
current_price = self.data.iloc[self.current_step + self.window_size - 1, 3] # Closing price
predicted_price = current_price + action[0]
# Reward calculation can be customized
reward = -abs(predicted_price - current_price)
return reward
User
File "C:\ProgramData\anaconda3\envs\test1\lib\site-packages\stable_baselines3\common\vec_env\dummy_vec_env.py", line 108, in _save_obs
self.buf_obs[key][env_idx] = obs
ValueError: could not broadcast input array from shape (50,8) into shape (50,4)
Assistant
The error you're encountering indicates a mismatch between the expected shape of the observation and the actual shape that is being returned by your environment. The model expects an observation with a certain shape, but your environment is providing an observation with a different shape. Let’s address this step by step.
Steps to Resolve the Shape Mismatch:
Check your DataFrame Columns: Ensure that your OHLC data DataFrame (ohlc_data) is structured correctly. It should only include the necessary OHLC columns. If there are any additional columns, make sure they are appropriately filtered.
Ensure Consistent Observation Space:
Double-check the dimensions of the observations you are returning from your environment. Specifically, you need to ensure that the shape of the observations aligns with what you declare in the observation space.
Adjust Observation Space and Response:
Update the _next_observation function so that it returns an observation with the expected shape (as declared in self.observation_space).
Here’s how you can revise the code assuming you only want to use OHLC data:
there are Date Open High Low Close Adj Close Volume Close_normalized columns in csv file.
predict stack market price using DDPG
Assistant
When dealing with time series data such as stock market prices, you need to ensure that your environment and model are set up correctly to predict future prices. Since you have additional columns in your dataset, let's focus on relevant ones for modeling: Open, High, Low, Close, Volume, and possibly Close_normalized if it's a normalized version of the Close price used as a target for predictions. Here’s how you can structure your environment and DDPG model setup:
Steps for Setting Up the Environment and Model
Filter Relevant Columns: You will need to filter out only the relevant columns from your dataset for observation and computation.
Modify Environment: Ensure that your custom gymnasium environment is correctly processing observations and aligns the observation space with the data features you wish to include.
Use stable_baselines3 for DDPG: Set up a DDPG agent to interact with your environment.
Let's proceed with the implementation:
Implementation Steps:
Define the Custom Gymnasium Environment
Given the columns in your dataset, we assume that the target prediction is related to the Close or Close_normalized column. Here’s how you can define the custom environment:
python
User
there are Date Open High. Low. Close. Adj Close. Volume. Close_normalized columns in csv file.
predict stack market price using DDPG
Assistant
Predicting stock market prices using DDPG with your dataset involves creating a custom environment using gymnasium, setting up a DDPG agent with stable_baselines3, and processing your data adequately. Here’s a step-by-step implementation guide based on the information you provided.
Step 1: Data Preparation
First, load and preprocess your data. Focus on columns relevant to predicting prices. You might normalize them or use features like 'Close_normalized'.
python
import pandas as pd
# Load the dataset
df = pd.read_csv('your_ohlc_data.csv')
# Ensure relevant columns are used (this may include normalizing them if not done already)
relevant_columns = ['Open', 'High', 'Low', 'Close', 'Volume', 'Close_normalized']
ohlc_data = df[relevant_columns]
Step 2: Define a Custom Gym Environment
Create a custom environment that returns observations and computes rewards based on the prediction of the Close or Close_normalized price. Adjust the environment to handle input and output shapes correctly.
python
import numpy as np
from gymnasium import Env
from gymnasium.spaces import Box
class StockTradingEnv(Env):
def __init__(self, data, window_size):
super(StockTradingEnv, self).__init__()
self.data = data
self.window_size = window_size
self.current_step = 0
# Define action and observation space
self.action_space = Box(low=-1, high=1, shape=(1,), dtype=np.float32)
self.observation_space = Box(low=-np.inf, high=np.inf, shape=(window_size, len(relevant_columns)), dtype=np.float32)
def reset(self, *, seed=None, options=None):
self.current_step = 0
if seed is not None:
np.random.seed(seed)
return self._next_observation(), {}
def _next_observation(self):
obs = self.data.iloc[self.current_step:self.current_step + self.window_size].values
return obs
def step(self, action):
# Calculate the predicted price as current close price adjusted by the taken action
current_price = self.data.iloc[self.current_step + self.window_size - 1]['Close']
predicted_price = current_price + action[0]
# Reward is the negative of the absolute difference between current and predicted prices
reward = -abs(predicted_price - current_price)
self.current_step += 1
done = self.current_step >= len(self.data) - self.window_size
obs = self._next_observation() if not done else np.zeros(self.observation_space.shape)
return obs, reward, done, {}
User
there are Date Open High, Low, Close, Adj_ Close, Volume, Close_normalized columns in csv file.
predict stack market price using DDPG
Assistant
Predicting stock market prices using DDPG (Deep Deterministic Policy Gradient) involves creating a custom reinforcement learning environment using the available data and training a model to predict future prices. Below is a step-by-step guide with implementations that make use of your dataset, which includes Date, Open, High, Low, Close, Adj Close, Volume, and Close_normalized.
Step 1: Data Preparation
Start by loading and preparing your data, making sure to focus on relevant columns for the model.
python
import pandas as pd
# Load your dataset
df = pd.read_csv('your_ohlc_data.csv')
# Select relevant columns for the environment
# Here we assume you want to predict 'Close' using given data features
ohlc_data = df[['Open', 'High', 'Low', 'Close', 'Volume', 'Close_normalized']]
Step 2: Define a Custom Gymnasium Environment
Create a custom environment to handle the interaction with the data. The environment will provide observations to the agent and compute rewards based on the agent's predictions.
python
User
model = DDPG("MlpPolicy", env, action_noise=action_noise, verbose=1)
model.learn(total_timesteps=10000) # You can adjust the number of timesteps
File "C:\ProgramData\anaconda3\envs\test1\lib\site-packages\stable_baselines3\common\monitor.py", line 94, in step
observation, reward, terminated, truncated, info = self.env.step(action)
ValueError: not enough values to unpack (expected 5, got 4)
Assistant
The error you're encountering is due to a mismatch between the Gym API changes and how your custom environment's step method is structured. The newer versions of Gym environments return a tuple of five elements: (observation, reward, terminated, truncated, info). Your custom environment needs to comply with this structure.
To fix this, update your step method to return both the terminated and truncated flags. In most cases, if you do not need a separate truncated condition (like episode truncation due to time limits), you can set it to False or consider it within your logic.
Updated step Method:
Here's how you can modify your step method in the StockTradingEnv environment to handle this correctly:
python
class StockTradingEnv(Env):
def __init__(self, data, window_size):
super(StockTradingEnv, self).__init__()
self.data = data
self.window_size = window_size
self.current_step = 0
# Define the action and observation space
self.action_space = Box(low=-1, high=1, shape=(1,), dtype=np.float32)
self.observation_space = Box(low=-np.inf, high=np.inf, shape=(window_size, len(self.data.columns)), dtype=np.float32)
def reset(self, *, seed=None, options=None):
self.current_step = 0
if seed is not None:
np.random.seed(seed)
return self._next_observation(), {}
def _next_observation(self):
# Fetch the sliding window of data for observations
return self.data.iloc[self.current_step:self.current_step + self.window_size].values
def step(self, action):
current_close = self.data.iloc[self.current_step + self.window_size - 1]['Close']
predicted_close = current_close + action[0]
reward = -abs(predicted_close - self.data.iloc[self.current_step + self.window_size]['Close'])
self.current_step += 1
done = self.current_step >= len(self.data) - self.window_size
obs = self._next_observation() if not done else np.zeros(self.observation_space.shape)
# Return terminated and truncated flags
terminated = done
truncated = False # If you don't have a specific truncation condition, keep it as False
return obs, reward, terminated, truncated, {}
def render(self, mode='human'):
print(f"Step: {self.current_step}")
The error you're encountering is related to the differences between interacting with environments directly through Gymnasium APIs and using vectorized environments (VecEnv) provided by Stable Baselines3 (SB3). Let's resolve this by ensuring you're using the correct interface for the environment type.
Understanding the Issue
Gymnasium Environment Reset: When you use Gymnasium directly, the reset method returns a tuple with an observation and additional info: obs, info = env.reset().
Stable Baselines3 VecEnv Reset: When using SB3 with VecEnv, the reset method returns only the observation: obs = vec_env.reset().
Solution for Your Case
If you're using Stable Baselines3 (SB3), it typically operates with its VecEnv structures, especially for training. Here’s how you can adjust your code for both scenarios:
Method 1: Train Using a VecEnv
Create a Vectorized Environment:
Use SB3 DummyVecEnv for single-environment vectorization. Note this will require a slight change in your training and evaluation code.
python
from stable_baselines3.common.env_util import make_vec_env
# Create a vectorized environment
env = make_vec_env(lambda: StockTradingEnv(ohlc_data, window_size), n_envs=1)
Training the Model:
Remain the same as before:
python
model = DDPG("MlpPolicy", env, action_noise=action_noise, verbose=1)
model.learn(total_timesteps=10000)
Using the Model for Prediction:
Remember to handle observations as a vectorized environment will return non-tuple observations:
python
obs = env.reset()
done = False
while not done:
# Get the action from the trained model
action, _states = model.predict(obs, deterministic=True)
# Take a step in the environment using the chosen action
obs, reward, done, _ = env.step(action)
print(f"Action: {action}, Reward: {reward}")
User
class StockTradingEnv(Env):
def init(self, data, window_size):
super(StockTradingEnv, self).init()
self.data = data
self.window_size = window_size
self.current_step = 0
what is Env?
Assistant
The Env in your class definition refers to the base class from the gymnasium (or gym) library, which is used for creating custom reinforcement learning environments. This base class provides the essential structure and methods that any environment must implement to interact correctly with an RL agent. Here's a brief overview of its purpose and the common methods it defines:
Purpose of Env Base Class
The Env class serves as the blueprint for creating environments in which reinforcement learning agents can interact. By inheriting from this class, you ensure that your custom environment adheres to the expected interface, allowing it to communicate with various reinforcement learning algorithms easily. The class defines methods that standardize the way environments work, making it possible to integrate them with frameworks like Stable Baselines3 and other RL libraries.
Core Methods in Env Class
__init__:
This method is where you set up your environment-specific variables, such as setting the initial state, defining action and observation spaces, and potentially loading any necessary data.
reset():
Used to reset the environment to an initial state at the start of each episode. This method returns the initial observation from the environment. In newer versions of Gym and Gymnasium, it typically returns a tuple (observation, info), where info can be additional details about the reset if needed.
step(action):
Takes an action as input, applies it to the environment, and returns a tuple of (next_observation, reward, done, info). Here, done is a boolean indicating whether the episode has terminated, and info can provide additional debugging information or metadata.
render(mode='human'):
Optionally, this method is implemented to visualize the state of the environment. It can help in debugging and understanding how the agent interacts with the environment.
close():
Cleans up and releases any resources the environment may have acquired. It's often used to close any render windows or terminate processes that were started during the environment's lifecycle.
Example Usage
By subclassing , your environment will inherit these methods, which you can then override and implement to suit your specific case, as in your . This involves initializing your environment with the necessary data, defining how the environment should respond to actions, and managing its state through observations and rewards. Here's a minimal conceptual example:
Seed Argument: The reset method now accepts a seed keyword argument to set the seed for the environment, which helps with reproducibility. This follows the updated API specification in gymnasium.
Returning Tuple: The reset method now returns a tuple, typically in the form (observation, info). Even if you don't need to return any specific info, you should return an empty dictionary {} for compatibility with newer APIs.
Testing Your Environment:
Make sure you test the environment to confirm it works with stable_baselines3 setup and handling of optional keyword arguments in methods:
python
env = OHLCKEnv(ohlc_data, window_size)
obs, info = env.reset()
By making these adjustments, your environment should work seamlessly with the stable_baselines3 library and gymnasium.
Additional Considerations:
Data Verification: Ensure you've loaded the data correctly and that it matches the expected structure. Before initializing the environment, you could print the shape of the data and sample rows to verify.
Testing: After making changes, test your environment independently to verify the shape of the observations:
python
env = OHLCKEnv(ohlc_data, window_size)
obs, info = env.reset()
print("Observation Shape:", obs.shape) # Should be (window_size, 4)
By ensuring that the observation space and the data align properly, this should resolve the broadcasting error you're encountering.
import numpy as np
import pandas as pd
from stable_baselines3 import DDPG
from stable_baselines3.common.noise import NormalActionNoise
from gymnasium import Env
from gymnasium.spaces import Box
class StockTradingEnv(Env):
def __init__(self, data, window_size):
super(StockTradingEnv, self).__init__()
# Filter relevant columns
self.data = data[['Open', 'High', 'Low', 'Close', 'Volume']]
self.window_size = window_size
self.current_step = 0
# Define action and observation space
self.action_space = Box(low=-1, high=1, shape=(1,), dtype=np.float32)
self.observation_space = Box(low=-np.inf, high=np.inf, shape=(window_size, self.data.shape[1]), dtype=np.float32)
def reset(self, *, seed=None, options=None):
self.current_step = 0
if seed is not None:
np.random.seed(seed)
return self._next_observation(), {}
def _next_observation(self):
return self.data.iloc[self.current_step:self.current_step + self.window_size].values
def step(self, action):
current_price = self.data.iloc[self.current_step + self.window_size - 1]['Close']
# Calculate predicted price as the current price plus the action taken
predicted_price = current_price + action[0]
# Reward calculation using the inverse of the error (making assumptions here)
reward = -np.abs(predicted_price - current_price) # Minimize prediction error
self.current_step += 1
done = self.current_step >= len(self.data) - self.window_size
obs = self._next_observation() if not done else np.zeros(self.observation_space.shape)
return obs, reward, done, {}
# Action noise for exploration
n_actions = env.action_space.shape[-1]
action_noise = NormalActionNoise(mean=np.zeros(n_actions), sigma=0.1 * np.ones(n_actions))
# Initialize DDPG model
model = DDPG("MlpPolicy", env, action_noise=action_noise, verbose=1)
# Train the model
model.learn(total_timesteps=10000)
Using the Model for Prediction
Once trained, you can use your model to predict:
python
obs, info = env.reset()
for _ in range(len(ohlc_data) - window_size):
action, _states = model.predict(obs, deterministic=True)
obs, rewards, dones, info = env.step(action)
if dones:
break
Notes:
Data Normalization/Scaling: Consider normalizing your input features (like prices and volume) for better performance.
Reward Function: You should ensure the reward function aligns with your overall goal. The inverse of the absolute error is a simple start but may not be optimal for specific tasks.
Training Validation: Split your data into training and testing sets to validate your model's performance.
These steps provide a basic implementation, you may need to further refine and customize the components based on specific features or characteristics of your dataset and objectives.
Step 3: Initialize and Train the DDPG Model
Configure and train your DDPG model using the custom environment.
python
from stable_baselines3 import DDPG
from stable_baselines3.common.noise import NormalActionNoise
# Initialize the environment
window_size = 50
env = StockTradingEnv(ohlc_data, window_size)
# Configure the action noise for exploration
n_actions = env.action_space.shape[-1]
action_noise = NormalActionNoise(mean=np.zeros(n_actions), sigma=0.1 * np.ones(n_actions))
# Initialize the DDPG model
model = DDPG("MlpPolicy", env, action_noise=action_noise, verbose=1)
# Train the model
model.learn(total_timesteps=10000)
Step 4: Use the Trained Model for Predictions
Simulate predictions using your trained model.
python
obs, info = env.reset()
done = False
while not done:
# Get the action from the trained model
action, _states = model.predict(obs, deterministic=True)
# Take a step in the environment using the chosen action
obs, reward, done, _ = env.step(action)
print(f"Predicted Action: {action}, Reward: {reward}")
Important Considerations:
Feature Engineering: Depending on your objective, further feature engineering might improve predictive performance (e.g., adding technical indicators).
Data Normalization: Ensure features are normalized/scaled to ensure that DDPG performs well, especially during training and optimization.
Evaluation: Split your data into training and testing sets to adequately evaluate the model's performance. Use metrics like MAE (Mean Absolute Error) to judge prediction accuracy.
Hyperparameter Tuning: Experiment with DDPG's hyperparameters and the action noise to optimize the results.
This setup serves as a foundation. Depending on your specific use case and data, additional adjustments and refinements will be necessary to achieve optimal performance.
import numpy as np
from gymnasium import Env
from gymnasium.spaces import Box
class StockTradingEnv(Env):
def __init__(self, data, window_size):
super(StockTradingEnv, self).__init__()
self.data = data
self.window_size = window_size
self.current_step = 0
# Define the action and observation space
# Predicted close price adjustment
self.action_space = Box(low=-1, high=1, shape=(1,), dtype=np.float32)
# Observation space with relevant columns
self.observation_space = Box(low=-np.inf, high=np.inf, shape=(window_size, len(self.data.columns)), dtype=np.float32)
def reset(self, *, seed=None, options=None):
self.current_step = 0
if seed is not None:
np.random.seed(seed)
return self._next_observation(), {}
def _next_observation(self):
# Fetch the sliding window of data for observations
return self.data.iloc[self.current_step:self.current_step + self.window_size].values
def step(self, action):
# Fetch current close price
current_close = self.data.iloc[self.current_step + self.window_size - 1]['Close']
# Calculate the predicted close price adjustment
predicted_close = current_close + action[0]
# Reward is based on the absolute error from actual to predicted close price
reward = -abs(predicted_close - self.data.iloc[self.current_step + self.window_size]['Close'])
self.current_step += 1
done = self.current_step >= len(self.data) - self.window_size
obs = self._next_observation() if not done else np.zeros(self.observation_space.shape)
return obs, reward, done, {}
def render(self, mode='human'):
print(f"Step: {self.current_step}")
Step 3: Initialize and Train the DDPG Model
Setup and train the DDPG model for making future price predictions.
python
from stable_baselines3 import DDPG
from stable_baselines3.common.noise import NormalActionNoise
# Define window size (e.g., 50 days or data points)
window_size = 50
# Initialize the custom environment
env = StockTradingEnv(ohlc_data, window_size)
# Configure action noise
n_actions = env.action_space.shape[-1]
action_noise = NormalActionNoise(mean=np.zeros(n_actions), sigma=0.1 * np.ones(n_actions))
# Initialize the DDPG model
model = DDPG("MlpPolicy", env, action_noise=action_noise, verbose=1)
# Train the model
model.learn(total_timesteps=10000)
Step 4: Use the Trained Model for Making Predictions
Once your model is trained, use it to make predictions on your data.
python
obs, info = env.reset()
while True:
# Use the trained model to predict actions
action, _ = model.predict(obs, deterministic=True)
# Step through the environment with the chosen action
obs, reward, done, _ = env.step(action)
# Print predicted action and reward
print(f"Predicted Action: {action}, Reward: {reward}")
if done:
break
Final Considerations:
Feature Engineering: Depending on your problem, you might want to add more features or preprocess the features, such as using technical indicators.
Normalization: Ensure consistent data normalization, as it can critically influence model training and predictions.
Evaluation: Evaluate your model effectively with data splitting, checking performance on unseen data, and refining based on those evaluations.
Hyperparameter Tuning: Adjust hyperparameters such as learning rate, noise sigma, etc., to stabilize the training process and potentially improve results.
This approach outlines the basics. Depending on your dataset specifics, additional tuning and testing are necessary to fully capitalize on DDPG's capability in this context.
Key Points:
Terminated vs. Truncated:
Terminated refers to whether the episode has ended, commonly on reaching a goal or failing a task.
Truncated is used to indicate a cut-off or time-out, which you may use if you impose a maximum number of steps per episode outside usual termination logic.
Returning Correct Tuple: Ensure the step method returns a tuple with five values: (obs, reward, terminated, truncated, info).
These changes make your environment compliant with the latest Gym API specifications, preventing errors related to tuple unpacking in the step method. Adjust other parts of your environment logic to handle these concepts appropriately, based on your requirements.
Method 2: Direct Gym (Non-VecEnv Approach)
If you prefer not to use VecEnv (e.g., for simplicity in understanding):
Initialize and Reset Directly (Non-VecEnv Style):
Treat it as a regular Gym environment, ensuring no vectorization happens:
python
env = StockTradingEnv(ohlc_data, window_size)
Adjust Predict and Reset in Your Evaluation/Prediction Code:
If testing without VecEnv, account for the additional information:
python
obs, info = env.reset()
done = False
while not done:
action, _states = model.predict(obs, deterministic=True)
obs, reward, terminated, truncated, _ = env.step(action)
done = terminated or truncated
print(f"Action: {action}, Reward: {reward}")
Key Takeaways:
When using VecEnv with SB3 during training and running the model, ensure you handle observations without unpacking.
If you stick to the direct Gym interface (non-VecEnv), account for tuple unpacking in resets, separating observations from additional info.
Adopting VecEnv is beneficial for parallel experiments or when using environments designed for multi-instance execution scenarios.
These approaches should help you correctly configure and run models using SB3 with or without vectorized environments, based on your use case.
Env
StockTradingEnv
python
from gymnasium import Env
from gymnasium.spaces import Discrete, Box
import numpy as np
class MyCustomEnv(Env):
def __init__(self):
super(MyCustomEnv, self).__init__()
# Define action and observation space
self.action_space = Discrete(2) # Example: Two possible actions
self.observation_space = Box(low=0, high=1, shape=(3,), dtype=np.float32) # Example: 3D observation
def reset(self):
# Reset the state of the environment to an initial state
return np.array([0.0, 0.0, 0.0], dtype=np.float32), {}
def step(self, action):
# Perform the action and update the environment's state
next_state = np.random.rand(3)
reward = 1.0 # Example reward
done = False
return next_state, reward, done, {}
def render(self, mode='human'):
print("Rendering environment state")
def close(self):
print("Cleaning up resources")
# Instantiate and use the custom environment
env = MyCustomEnv()
This understanding provides the foundation for creating environments that can work seamlessly with reinforcement learning algorithms, facilitating tasks like training and evaluation in complex scenarios like stock trading.