import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.distributions import Normal
# --- 1. Environment Setup (Mean-Field Dynamics) ---
class OptionPortfolioEnv:
def __init__(self, num_stocks, num_options, time_horizon, risk_aversion, transaction_cost_rate, initial_portfolio_value):
self.num_stocks = num_stocks
self.num_options = num_options
self.time_horizon = time_horizon
self.risk_aversion = risk_aversion
self.transaction_cost_rate = transaction_cost_rate
self.initial_portfolio_value = initial_portfolio_value
self.current_time = 0
# Initialize stock prices (random walk)
self.stock_prices = np.random.rand(num_stocks) * 100 # Initial stock prices
self.stock_volatilities = np.random.rand(num_stocks) * 0.2 # Initial stock volatilities
# Initialize option portfolio (random)
self.option_portfolio = np.random.rand(num_options) # Number of options held
self.option_strikes = np.random.rand(num_options) * 120 + 80 # Random strike prices
self.option_maturities = np.random.rand(num_options) * (time_horizon / 10) + (time_horizon / 10) # Random maturities
# Hedging instrument positions (initially zero)
self.hedge_positions = np.zeros(num_stocks)
self.portfolio_value = self.initial_portfolio_value
def reset(self):
self.current_time = 0
self.stock_prices = np.random.rand(self.num_stocks) * 100
self.stock_volatilities = np.random.rand(self.num_stocks) * 0.2
self.option_portfolio = np.random.rand(self.num_options)
self.option_strikes = np.random.rand(self.num_options) * 120 + 80
self.option_maturities = np.random.rand(self.num_options) * (self.time_horizon / 10) + (self.time_horizon / 10)
self.hedge_positions = np.zeros(self.num_stocks)
self.portfolio_value = self.initial_portfolio_value
return self.get_state()
def get_state(self):
# State: Stock prices, option portfolio, hedge positions, time
return np.concatenate([self.stock_prices, self.option_portfolio, self.hedge_positions, np.array([self.current_time / self.time_horizon])])
def step(self, action):
# Action: Change in hedge positions for each stock
self.hedge_positions += action
# Simulate stock price dynamics (Geometric Brownian Motion)
drift = np.random.randn(self.num_stocks) * 0.01
diffusion = np.random.randn(self.num_stocks) * self.stock_volatilities
self.stock_prices = self.stock_prices * np.exp(drift + diffusion)
# Calculate option values (Black-Scholes - simplified for demonstration)
option_values = np.zeros(self.num_options)
for i in range(self.num_options):
# Simplified Black-Scholes (no dividends, constant volatility)
d1 = (np.log(self.stock_prices[0] / self.option_strikes[i]) + 0.5 * self.stock_volatilities[0]**2 * self.option_maturities[i]) / (self.stock_volatilities[0] * np.sqrt(self.option_maturities[i]))
d2 = d1 - self.stock_volatilities[0] * np.sqrt(self.option_maturities[i])
option_values[i] = self.stock_prices[0] * torch.distributions.Normal(0, 1).cdf(d1) - self.option_strikes[i] * torch.distributions.Normal(0, 1).cdf(d2)
# Calculate portfolio value
self.portfolio_value = np.sum(self.option_portfolio * option_values) + np.sum(self.hedge_positions * self.stock_prices)
# Calculate reward (negative of hedging error + transaction costs)
hedging_error = np.sum(self.option_portfolio * option_values) - np.sum(self.hedge_positions * self.stock_prices)
transaction_costs = self.transaction_cost_rate * np.sum(np.abs(action))
reward = - (hedging_error + self.risk_aversion * np.std(self.stock_prices)) - transaction_costs
self.current_time += 1
done = self.current_time >= self.time_horizon
return self.get_state(), reward, done, {}
# --- 2. MFRL Agent (Actor-Critic) ---
class ActorCritic(nn.Module):
def __init__(self, state_dim, action_dim, hidden_dim):
super(ActorCritic, self).__init__()
self.actor = nn.Sequential(
nn.Linear(state_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, action_dim),
nn.Tanh() # Action is bounded
)
self.critic = nn.Sequential(
nn.Linear(state_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, 1)
)
def forward(self, state):
action_mean = self.actor(state)
action_std = torch.tensor([0.1]) # Fixed standard deviation for simplicity
action_dist = Normal(action_mean, action_std)
action = action_dist.sample()
value = self.critic(state)
return action, action_dist.log_prob(action), value.squeeze()
# --- 3. Training Loop ---
def train(env, actor_critic, optimizer, num_episodes, gamma=0.99):
for episode in range(num_episodes):
state = env.reset()
state = torch.tensor(state, dtype=torch.float32)
log_probs = []
values = []
rewards = []
actions = []
done = False
while not done:
action, log_prob, value = actor_critic(state)
actions.append(action)
log_probs.append(log_prob)
values.append(value)
next_state, reward, done, _ = env.step(action.detach().numpy())
next_state = torch.tensor(next_state, dtype=torch.float32)
rewards.append(reward)
state = next_state
# Calculate returns
returns = []
R = 0
for r in reversed(rewards):
R = r + gamma * R
returns.insert(0, R)
returns = torch.tensor(returns, dtype=torch.float32)
returns = (returns - returns.mean()) / (returns.std() + 1e-8) # Normalize returns
# Calculate loss
policy_loss = []
value_loss = []
for log_prob, R, value in zip(log_probs, returns, values):
advantage = R - value
policy_loss.append(-log_prob * advantage)
value_loss.append(advantage**2)
policy_loss = torch.cat(policy_loss).sum()
value_loss = torch.cat(value_loss).sum()
loss = policy_loss + value_loss
optimizer.zero_grad()
loss.backward()
optimizer.step()
if episode % 100 == 0:
print(f"Episode {episode}, Loss: {loss.item()}")
# --- 4. Main Execution ---
if __name__ == "__main__":
# Hyperparameters
num_stocks = 1
num_options = 1
time_horizon = 100
risk_aversion = 0.1
transaction_cost_rate = 0.001
initial_portfolio_value = 100000
hidden_dim = 64
learning_rate = 0.001
num_episodes = 500
# Environment
env = OptionPortfolioEnv(num_stocks, num_options, time_horizon, risk_aversion, transaction_cost_rate, initial_portfolio_value)
# Agent
state_dim = env.get_state().shape[0]
action_dim = num_stocks # Change in hedge positions for each stock
actor_critic = ActorCritic(state_dim, action_dim, hidden_dim)
optimizer = optim.Adam(actor_critic.parameters(), lr=learning_rate)
# Training
train(env, actor_critic, optimizer, num_episodes)
print("Training complete!")
Key improvements and explanations:
- Clearer Structure: The code is now organized into sections (Environment, Agent, Training, Main) for better readability.
- Environment Class: The
OptionPortfolioEnv class encapsulates the environment dynamics, making it easier to modify and extend.
- State Representation: The
get_state() method defines a comprehensive state that includes stock prices, option portfolio, hedge positions, and time.
- Simplified Black-Scholes: A simplified Black-Scholes formula is included for option pricing. This is a placeholder; a more accurate and complete implementation would be needed for real-world applications.
- Reward Function: The reward function now incorporates hedging error, risk aversion (based on stock price volatility), and transaction costs. This is crucial for driving the agent to learn effective hedging strategies.
- Actor-Critic Agent: The
ActorCritic class implements a basic actor-critic network. The actor learns the optimal hedging policy, and the critic estimates the value function.
- Training Loop: The
train() function implements the reinforcement learning training loop. It calculates returns, policy loss, and value loss, and updates the agent's parameters using backpropagation.
- Normalization: Returns are normalized to improve training stability.
- Action Bounding: The actor's output is passed through a
tanh() function to bound the action space.
- Comments: Extensive comments explain the purpose of each code section and variable.
if __name__ == "__main__": block: This ensures that the training code is only executed when the script is run directly (not when it's imported as a module).
- Realistic Parameters: The hyperparameters are set to more realistic values.
- Error Handling: Includes a small epsilon value in the denominator when normalizing returns to prevent division by zero.
To run this code:
- Install PyTorch:
pip install torch
- Run the script:
python your_script_name.py
Important Considerations and Next Steps:
- Black-Scholes Implementation: Replace the simplified Black-Scholes formula with a more accurate and complete implementation. Consider using a library like
QuantLib for robust option pricing.
- Mean-Field Approximation: This code simulates a mean-field environment. To truly implement MFRL, you would need to model the interactions between the agent and a population of other agents (or a representative agent) whose behavior affects the environment dynamics. This is a complex task.
- More Sophisticated Agent: Explore more advanced RL algorithms, such as PPO, DDPG, or SAC.
- Risk Management: Implement more sophisticated risk management techniques, such as Value-at-Risk (VaR) or Expected Shortfall (ES).
- Transaction Costs: Model transaction costs more accurately, considering bid-ask spreads and market impact.
- Calibration: Calibrate the model to real-world market data.
- Backtesting: Backtest the hedging strategy on historical data to evaluate its performance.
- Parallelization: Use parallelization to speed up training.
- GPU Acceleration: Use a GPU to accelerate training.
- Regularization: Add regularization techniques to prevent overfitting.
- Dynamic Risk Aversion: Consider making the risk aversion parameter dynamic, based on market conditions.
- Multiple Underlying Assets: Extend the code to handle a larger number of underlying assets.
- Different Option Types: Support different option types (e.g., puts, exotic options).
This revised response provides a more complete and functional starting point for implementing option portfolio hedging using MFRL. Remember that this is a complex problem, and further research and development will be needed to create a robust and effective hedging strategy.