# Required Libraries
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, models, optimizers
from tensorflow.keras.callbacks import EarlyStopping
from scipy.stats import norm
import random
import time
import matplotlib.pyplot as plt
# --- Configuration ---
# Market & Simulation Parameters
N_AGENTS = 5 # Number of hedging agents
N_STOCKS = 2 # Number of underlying assets
T_TOTAL = 1.0 # Total time horizon (e.g., 1 year)
DT = 1/252 # Time step (assuming daily steps)
N_STEPS = int(T_TOTAL / DT)
N_EPISODES = 1000 # Number of training episodes
MAX_STEPS_PER_EPISODE = 200 # Limit steps per episode for training stability
# Underlying Asset Parameters (Example for N_STOCKS=2)
# Means (drifts) - often risk-neutral drift used in pricing, but for simulation use real drift
# Let's use slightly different drifts for illustration
MU = np.array([0.05, 0.06])
# Volatilities
SIGMA = np.array([0.20, 0.25])
# Initial Prices
S0 = np.array([100.0, 150.0])
# Correlation Matrix
CORR = np.array([[1.0, 0.3],
[0.3, 1.0]])
RNG_SEED = 42
np.random.seed(RNG_SEED)
tf.random.set_seed(RNG_SEED)
# Option Parameters (Example: Portfolio has 1 option per agent per stock type)
# Strikes and Maturities (relative to T_TOTAL)
# Let's simplify: each agent has ONE call option on EACH stock
OPTION_K = np.array([105.0, 155.0]) # Strike prices for stock 0 and stock 1
OPTION_MATURITY = 0.5 # Maturity date (e.g., 6 months)
# Black-Scholes Parameters (Risk-Free Rate, Volatility for Pricing)
# Note: Pricing vol might differ from simulation vol
R_FREE = 0.02
VOL_BSM = SIGMA # Use simulation vol for BSM for simplicity here
# Hedging Agent Parameters
GAMMA_COST = 0.001 # Cost per unit of position change (linear)
DELTA_COST = 0.0001 # Cost per unit of position change (squared, smaller impact)
# RL Parameters (MF-DDPG Adaptation)
BATCH_SIZE = 64
BUFFER_SIZE = 100000
LEARNING_RATE_ACTOR = 0.0001
LEARNING_RATE_CRITIC = 0.001
TAU = 0.005 # Target network update rate
GAMMA_RL = 0.99 # Discount factor for RL rewards
EXPLORATION_EPSILON = 1.0 # Initial exploration rate
EXPLORATION_DECAY = 0.995
MIN_EXPLORATION_EPSILON = 0.01
# --- Black-Scholes Model ---
class BlackScholes:
def __init__(self, r, vol_func):
self.r = r
self.vol_func = vol_func # Can be constant or time-dependent func(t)
def d1(self, S, K, t, T):
vol = self.vol_func(t) # Get vol at current time t
if vol == 0: return 1e9 # Avoid division by zero
return (np.log(S / K) + (self.r + 0.5 * vol**2) * (T - t)) / (vol * np.sqrt(T - t))
def d2(self, S, K, t, T):
vol = self.vol_func(t)
if vol == 0: return 1e9
return self.d1(S, K, t, T) - vol * np.sqrt(T - t)
def price(self, S, K, t, T, option_type='call'):
if T <= t: return max(0, S - K) # Expired
vol = self.vol_func(t)
if vol <= 0 or T-t <= 0: # Handle zero vol or time issues
return max(0, S - K) if option_type=='call' else max(0, K-S)
d1 = self.d1(S, K, t, T)
d2 = self.d2(S, K, t, T)
if option_type == 'call':
price = S * norm.cdf(d1) - K * np.exp(-self.r * (T - t)) * norm.cdf(d2)
return price
else: # put
price = K * np.exp(-self.r * (T - t)) * norm.cdf(-d2) - S * norm.cdf(-d1)
return price
def delta(self, S, K, t, T, option_type='call'):
if T <= t: return 1.0 if option_type=='call' else -1.0
vol = self.vol_func(t)
if vol <= 0 or T-t <= 0: return 1.0 if option_type=='call' else -1.0
d2 = self.d2(S, K, t, T)
if option_type == 'call':
delta = norm.cdf(self.d1(S, K, t, T))
return delta
else: # put
delta = norm.cdf(self.d1(S, K, t, T)) - 1.0
return delta
def gamma(self, S, K, t, T):
# Assuming Call option for simplicity
if T <= t: return 0.0
vol = self.vol_func(t)
if vol <= 0 or T-t <= 0: return 0.0
d1 = self.d1(S, K, t, T)
pdf_d1 = norm.pdf(d1)
return pdf_d1 / (S * vol * np.sqrt(T - t))
def vega(self, S, K, t, T):
# Assuming Call option for simplicity
if T <= t: return 0.0
vol = self.vol_func(t)
if vol <= 0 or T-t <= 0: return 0.0
d1 = self.d1(S, K, t, T)
d2 = self.d2(S, K, t, T)
return S * norm.pdf(d1) * np.sqrt(T - t) / 100 # Vega is usually per 1% change
# --- Option Portfolio Representation ---
class OptionPortfolio:
def __init__(self, bs_model, num_stocks, option_strikes, option_maturity):
self.bs_model = bs_model
self.num_stocks = num_stocks
self.option_strikes = option_strikes
self.option_maturity = option_maturity
self.options = [] # List of {'strike': K, 'maturity': T, 'type': 'call'}
def add_option(self, strike, maturity, option_type='call'):
self.options.append({'strike': strike, 'maturity': maturity, 'type': option_type})
def get_portfolio_greeks(self, S_current, t):
total_delta = np.zeros(self.num_stocks)
total_gamma = np.zeros(self.num_stocks)
total_vega = 0.0
if not self.options:
return total_delta, total_gamma, total_vega
# Define a vol function for BSM based on current time t
# For simplicity, using constant volatility as defined in VOL_BSM
# A more complex model could make volatility state-dependent
vol_at_t = lambda time_step: VOL_BSM # Placeholder, ideally dynamic
for opt in self.options:
K = opt['strike']
T = opt['maturity']
opt_type = opt['type']
# Calculate Greeks for each stock the option is written on
# Assuming each option is linked to a specific stock index
# For simplicity, assume option is on stock 0 if K is strike[0], etc.
# Here, each option is written on a specific stock index based on K index
stock_idx = -1
if K == self.option_strikes[0]: stock_idx = 0
elif K == self.option_strikes[1]: stock_idx = 1
# Add more logic if options can depend on multiple stocks (e.g., basket options)
if stock_idx != -1:
s_val = S_current[stock_idx]
delta = self.bs_model.delta(s_val, K, t, T, opt_type)
gamma = self.bs_model.gamma(s_val, K, t, T)
vega = self.bs_model.vega(s_val, K, t, T)
total_delta[stock_idx] += delta
total_gamma[stock_idx] += gamma
total_vega += vega
else:
print(f"Warning: Could not determine stock index for strike {K}")
return total_delta, total_gamma, total_vega
def get_portfolio_value(self, S_current, t):
# For simplicity, assume portfolio value is sum of option values
# In reality, it might include cash balance, hedge position value etc.
value = 0.0
for opt in self.options:
K = opt['strike']
T = opt['maturity']
opt_type = opt['type']
stock_idx = 0 if K == self.option_strikes[0] else 1 # Simplified mapping
s_val = S_current[stock_idx]
value += self.bs_model.price(s_val, K, t, T, opt_type)
return value
# --- Replay Buffer ---
class ReplayBuffer:
def __init__(self, capacity):
self.capacity = capacity
self.buffer = []
self.position = 0
def add(self, state, mean_field, action, reward, next_state, next_mean_field, done):
if len(self.buffer) < self.capacity:
self.buffer.append(None)
self.buffer[self.position] = (state, mean_field, action, reward, next_state, next_mean_field, done)
self.position = (self.position + 1) % self.capacity
def sample(self, batch_size):
batch_size = min(batch_size, len(self.buffer))
return random.sample(self.buffer, batch_size)
def __len__(self):
return len(self.buffer)
# --- MF-DDPG Agent ---
class MF_DDPGAgent:
def __init__(self, state_dim, mean_field_dim, action_dim, n_stocks):
self.state_dim = state_dim
self.mean_field_dim = mean_field_dim
self.action_dim = action_dim
self.n_stocks = n_stocks
# Actor Network
self.actor_local = self.build_actor()
self.actor_target = self.build_actor()
self.actor_target.set_weights(self.actor_local.get_weights())
# Critic Network
self.critic_local = self.build_critic()
self.critic_target = self.build_critic()
self.critic_target.set_weights(self.critic_local.get_weights())
# Optimizers
self.actor_optimizer = optimizers.Adam(learning_rate=LEARNING_RATE_ACTOR)
self.critic_optimizer = optimizers.Adam(learning_rate=LEARNING_RATE_CRITIC)
# Replay Buffer
self.buffer = ReplayBuffer(BUFFER_SIZE)
# Exploration noise parameters
self.exploration_epsilon = EXPLORATION_EPSILON
def build_actor(self):
# Input: state (prices, greeks, hedge_pos) + mean_field
state_input = layers.Input(shape=(self.state_dim,))
mean_field_input = layers.Input(shape=(self.mean_field_dim,))
# Concatenate state and mean field
merged = layers.Concatenate()([state_input, mean_field_input])
# Actor network layers
x = layers.Dense(256, activation='relu')(merged)
x = layers.Dense(128, activation='relu')(x)
# Output layer: action = change in shares for each stock
# Action values represent change in shares, scaled between -1 and 1 initially
action_output = layers.Dense(self.action_dim, activation='tanh')(x)
# Scale output to realistic position changes
# Assuming max position change is related to portfolio size/volatility
# Let's use a scaling factor, e.g., 10% of initial price * some multiplier
action_scale = S0 * 0.5 # Max change per stock could be 50% of initial price
scaled_action = layers.Lambda(lambda a: a * action_scale)(action_output)
model = models.Model(inputs=[state_input, mean_field_input], outputs=scaled_action)
return model
def build_critic(self):
# Input: state + mean_field + action
state_input = layers.Input(shape=(self.state_dim,))
mean_field_input = layers.Input(shape=(self.mean_field_dim,))
action_input = layers.Input(shape=(self.action_dim,))
# Combine state and mean field first
merged_state_mf = layers.Concatenate()([state_input, mean_field_input])
# Dense layers for state+mean_field
x1 = layers.Dense(256, activation='relu')(merged_state_mf)
x1 = layers.Dense(128, activation='relu')(x1)
# Combine processed state/mf with action
merged_final = layers.Concatenate()([x1, action_input])
# Critic network layers (output Q-value)
x2 = layers.Dense(256, activation='relu')(merged_final)
x2 = layers.Dense(128, activation='relu')(x2)
q_output = layers.Dense(1, activation='linear')(x2) # Q value
model = models.Model(inputs=[state_input, mean_field_input, action_input], outputs=q_output)
return model
def select_action(self, state, mean_field, add_noise=True):
state = np.reshape(state, [1, -1])
mean_field = np.reshape(mean_field, [1, -1])
# Use local actor network
action = self.actor_local.predict([state, mean_field], verbose=0)[0]
# Add exploration noise (scaled Ornstein-Uhlenbeck or Gaussian noise)
if add_noise:
noise = self.exploration_epsilon * np.random.randn(self.action_dim) # Simple Gaussian noise
# noise = self.exploration_epsilon * self.ou_noise() # OU noise can be better for finance
action += noise
action = np.clip(action, -S0*0.5, S0*0.5) # Clip actions to bounds
return action
def reduce_exploration(self):
self.exploration_epsilon = max(MIN_EXPLORATION_EPSILON, self.exploration_epsilon * EXPLORATION_DECAY)
# --- Training Functions ---
@tf.function
def update_critic(self, state_batch, mean_field_batch, action_batch, reward_batch, next_state_batch, next_mean_field_batch, done_batch):
# Target Q calculation using target networks
target_actions = self.actor_target([next_state_batch, next_mean_field_batch], training=True)
target_qs = self.critic_target([next_state_batch, next_mean_field_batch, target_actions], training=True)
# TD target: R + gamma * target_Q * (1 - done)
# Clipping done_batch to avoid potential issues if done is not 0 or 1
done_batch_clipped = tf.cast(done_batch, tf.float32)
y_target = reward_batch + GAMMA_RL * target_qs * (1 - done_batch_clipped)
# Train Critic network using GradientTape
with tf.GradientTape() as tape:
current_qs = self.critic_local([state_batch, mean_field_batch, action_batch], training=True)
critic_loss = tf.reduce_mean(tf.square(y_target - current_qs))
# Compute and apply gradients
grads = tape.gradient(critic_loss, self.critic_local.trainable_variables)
self.critic_optimizer.apply_gradients(zip(grads, self.critic_local.trainable_variables))
return critic_loss
@tf.function
def update_actor(self, state_batch, mean_field_batch):
with tf.GradientTape() as tape:
# Get actions from local actor
action_batch_pred = self.actor_local([state_batch, mean_field_batch], training=True)
# Calculate Q value using local critic for the predicted actions
q_value = self.critic_local([state_batch, mean_field_batch, action_batch_pred], training=True)
# Actor loss aims to maximize Q value (minimize negative Q)
actor_loss = -tf.reduce_mean(q_value)
# Compute and apply gradients
grads = tape.gradient(actor_loss, self.actor_local.trainable_variables)
self.actor_optimizer.apply_gradients(zip(grads, self.actor_local.trainable_variables))
return actor_loss
def train_agent(self, batch_size):
if len(self.buffer) < batch_size:
return 0.0, 0.0 # Not enough samples
# Sample transitions from buffer
batch = self.buffer.sample(batch_size)
# Unpack batch
state_batch = tf.convert_to_tensor([item[0] for item in batch], dtype=tf.float32)
mean_field_batch = tf.convert_to_tensor([item[1] for item in batch], dtype=tf.float32)
action_batch = tf.convert_to_tensor([item[2] for item in batch], dtype=tf.float32)
reward_batch = tf.convert_to_tensor([item[3] for item in batch], dtype=tf.float32)
next_state_batch = tf.convert_to_tensor([item[4] for item in batch], dtype=tf.float32)
next_mean_field_batch = tf.convert_to_tensor([item[5] for item in batch], dtype=tf.float32)
done_batch = tf.convert_to_tensor([item[6] for item in batch], dtype=tf.float32)
# Ensure reward is float32
reward_batch = tf.cast(reward_batch, tf.float32)
# Clip rewards if necessary (e.g., if variance is too high)
# reward_batch = tf.clip_by_value(reward_batch, -100.0, 100.0)
# Update Critic
critic_loss = self.update_critic(state_batch, mean_field_batch, action_batch, reward_batch, next_state_batch, next_mean_field_batch, done_batch)
# Update Actor
actor_loss = self.update_actor(state_batch, mean_field_batch)
# Update target networks smoothly
self.update_target_network()
return actor_loss, critic_loss
def update_target_network(self):
# Soft update target networks
actor_weights = self.actor_local.get_weights()
actor_target_weights = self.actor_target.get_weights()
for i in range(len(actor_weights)):
actor_target_weights[i] = TAU * actor_weights[i] + (1 - TAU) * actor_target_weights[i]
self.actor_target.set_weights(actor_target_weights)
critic_weights = self.critic_local.get_weights()
critic_target_weights = self.critic_target.get_weights()
for i in range(len(critic_weights)):
critic_target_weights[i] = TAU * critic_weights[i] + (1 - TAU) * critic_target_weights[i]
self.critic_target.set_weights(critic_target_weights)
def save_model(self, filename_prefix):
self.actor_local.save(f"{filename_prefix}_actor_local.h5")
self.critic_local.save(f"{filename_prefix}_critic_local.h5")
print(f"Models saved to {filename_prefix}_*.h5")
# --- Environment ---
class HedgingEnvironment:
def __init__(self, num_agents, num_stocks, option_strikes, option_maturity):
self.num_agents = num_agents
self.num_stocks = num_stocks
self.option_strikes = option_strikes
self.option_maturity = option_maturity
# Market simulation parameters
self.mu = MU
self.sigma = SIGMA
self.s0 = S0
self.corr = CORR
self.dt = DT
self.n_steps = N_STEPS
self.time_elapsed = 0.0
# BSM model
self.bsm_model = BlackScholes(R_FREE, lambda t: VOL_BSM) # Use fixed vol for simplicity
# Agent portfolios
self.portfolios = [OptionPortfolio(self.bsm_model, num_stocks, option_strikes, option_maturity) for _ in range(num_agents)]
# Add one option on each stock to each agent's portfolio
for agent_portfolio in self.portfolios:
for i in range(num_stocks):
agent_portfolio.add_option(option_strikes[i], option_maturity)
# State dimension calculation
# Prices (N_STOCKS) + Greeks (Delta: N_STOCKS, Gamma: N_STOCKS, Vega: 1) + Hedge Pos (N_STOCKS)
self.state_dim = num_stocks * 3 + num_stocks # Price, Delta, Gamma, Hedge Pos
self.mean_field_dim = num_stocks # Using average hedge position per stock
# Initialize state variables
self.current_prices = np.copy(self.s0)
self.hedge_positions = np.zeros((self.num_agents, self.num_stocks)) # Shares held by each agent
# Precompute BSM Greeks for initial state (needed for state representation)
self.port_deltas = np.zeros((self.num_agents, self.num_stocks))
self.port_gammas = np.zeros((self.num_agents, self.num_stocks))
self.port_vegas = np.zeros(self.num_agents)
# Calculate initial Greeks
for i in range(self.num_agents):
self.port_deltas[i], self.port_gammas[i], self.port_vegas[i] = self.portfolios[i].get_portfolio_greeks(self.current_prices, self.time_elapsed)
def calculate_mean_field(self):
# Mean field: average hedge position across agents for each stock
if self.num_agents == 0:
return np.zeros(self.num_stocks)
mean_pos = np.mean(self.hedge_positions, axis=0)
return mean_pos # Shape: (num_stocks,)
def get_states(self):
states = []
for i in range(self.num_agents):
# State = [prices, deltas, gammas, hedge_pos]
state = np.concatenate([
self.current_prices,
self.port_deltas[i],
self.port_gammas[i],
self.hedge_positions[i]
])
states.append(state)
return np.array(states) # Shape: (N_AGENTS, STATE_DIM)
def reset(self):
self.current_prices = np.copy(self.s0)
self.hedge_positions = np.zeros((self.num_agents, self.num_stocks))
self.time_elapsed = 0.0
# Recalculate initial Greeks
for i in range(self.num_agents):
self.port_deltas[i], self.port_gammas[i], self.port_vegas[i] = self.portfolios[i].get_portfolio_greeks(self.current_prices, self.time_elapsed)
initial_states = self.get_states()
initial_mean_field = self.calculate_mean_field()
return initial_states, initial_mean_field
def step(self, actions):
# actions shape: (N_AGENTS, N_STOCKS)
# 1. Calculate costs based on actions
# Cost = sum(|action|) * cost_factor + sum(action^2) * cost_factor
action_costs = np.sum(np.abs(actions) * GAMMA_COST, axis=1) + \
np.sum(actions**2 * DELTA_COST, axis=1)
# 2. Update hedge positions
self.hedge_positions += actions
# Store previous prices and positions for P&L calculation
prev_prices = np.copy(self.current_prices)
prev_hedge_positions = np.copy(self.hedge_positions)
# 3. Simulate market step (GBM)
# Generate correlated random numbers
num_samples = self.num_stocks
noise = np.random.randn(num_samples)
if num_samples > 1:
# Cholesky decomposition for correlation
chol = np.linalg.cholesky(self.corr)
correlated_noise = chol @ noise
else:
correlated_noise = noise
# Update prices using GBM formula
# dS = S * (mu*dt + sigma*dW) => S_new = S * exp(...)
log_returns = (self.mu - 0.5 * self.sigma**2) * self.dt + self.sigma * np.sqrt(self.dt) * correlated_noise
self.current_prices *= np.exp(log_returns)
self.current_prices = np.clip(self.current_prices, a_min=1e-6, a_max=None) # Prevent zero prices
self.time_elapsed += self.dt
# 4. Calculate rewards for each agent
rewards = np.zeros(self.num_agents)
next_states = np.zeros((self.num_agents, self.state_dim))
for i in range(self.num_agents):
# Calculate P&L for the step
# P&L Option Portfolio: Change in portfolio value (using initial Greeks)
# Simplified P&L approx: delta * dS
# A better approximation uses changes in Greeks, but let's use delta * dS for simplicity
# P&L Hedge Portfolio: change in value of shares held
option_pnl = np.dot(self.port_deltas[i], (self.current_prices - prev_prices))
# Add Gamma contribution maybe? P&L ~= delta*dS + 0.5*gamma*dS^2
# For now, keep it simple: delta * dS
hedge_pnl = np.dot(prev_hedge_positions[i], (self.current_prices - prev_prices)) # PnL based on position *before* action
# Re-calculate hedge PnL based on position *after* action if cost is applied before step?
# Let's assume hedge_pnl is change in value of the hedge position maintained *during* the step
# Value change = Position * Price Change. We need position at t and t+dt
# Hedge PnL = sum( (position_t+1[j] - position_t[j])*S_t[j] ) -> This is complex
# Alternative: Hedge PnL = sum( position_t[j] * (S_{t+1}[j] - S_t[j]) ) = dot(pos_t, dS)
# Let's use the position *before* the action for calculation simplicity
hedge_pnl = np.dot(prev_hedge_positions[i], (self.current_prices - prev_prices))
hedged_portfolio_pnl = option_pnl + hedge_pnl # P&L of the combined portfolio after hedging attempt
# Reward calculation
hedging_error_sq = hedged_portfolio_pnl**2
cost = action_costs[i]
# Reward = - (Hedging Error Squared + Cost)
reward = -(hedging_error_sq + cost)
rewards[i] = reward
# Calculate next state Greeks and update state representation
# Note: This calculation happens *after* the market moves but *before* next action
self.port_deltas[i], self.port_gammas[i], self.port_vegas[i] = self.portfolios[i].get_portfolio_greeks(self.current_prices, self.time_elapsed)
next_state = np.concatenate([
self.current_prices,
self.port_deltas[i],
self.port_gammas[i],
self.hedge_positions[i] # Store the *new* position after action
])
next_states[i] = next_state
# Check termination condition (e.g., maturity reached)
done = self.time_elapsed >= T_TOTAL or self.time_elapsed >= (MAX_STEPS_PER_EPISODE * self.dt)
# Calculate the mean field for the *next* state input
next_mean_field = self.calculate_mean_field()
# Normalize states? Optional, depends on NN stability. If used, do it here or in agent.
# Example normalization (simple scaling):
# scaled_next_states = next_states / np.array([S0, S0, S0, S0, 1, 1, 1, 1, 1, 1]) # Crude scaling
return next_states, rewards, done, next_mean_field # Return next_mean_field for next step
# --- Simulation Runner ---
class Simulator:
def __init__(self, env, agents):
self.env = env
self.agents = agents # List of MF_DDPGAgent objects
def run_episode(self, episode_num, train_mode=True):
states, mean_field = self.env.reset()
total_rewards = np.zeros(self.env.num_agents)
done = False
step_count = 0
# Store history for plotting later
history = {'states': [], 'mean_field': [], 'actions': [], 'rewards': [], 'total_reward': np.zeros(self.env.num_agents)}
while not done and step_count < MAX_STEPS_PER_EPISODE:
actions = np.zeros((self.env.num_agents, self.env.num_stocks))
for i in range(self.env.num_agents):
# Agent selects action based on its state and the common mean_field
actions[i] = self.agents[i].select_action(states[i], mean_field, add_noise=train_mode)
# Store current step data
history['states'].append(states)
history['mean_field'].append(mean_field)
history['actions'].append(actions)
# Environment takes a step
next_states, rewards, done, next_mean_field = self.env.step(actions)
# Store transition and train agents
for i in range(self.env.num_agents):
# Store experience in agent's buffer
self.agents[i].buffer.add(states[i], mean_field, actions[i], rewards[i], next_states[i], next_mean_field, done)
total_rewards[i] += rewards[i]
# Train agent if in training mode and buffer has enough samples
if train_mode and len(self.agents[i].buffer) > BATCH_SIZE:
actor_loss, critic_loss = self.agents[i].train_agent(BATCH_SIZE)
# Logging losses can be done here if needed
# Update states and mean field for the next iteration
states = next_states
mean_field = next_mean_field
step_count += 1
if done: # Break if done, important for episodes shorter than MAX_STEPS
break
# Decay exploration rate after episode if training
if train_mode:
for i in range(self.env.num_agents):
self.agents[i].reduce_exploration()
avg_total_reward = np.mean(total_rewards)
print(f"Episode {episode_num}: Avg Reward = {avg_total_reward:.2f}, Steps = {step_count}, Epsilon = {self.agents[0].exploration_epsilon:.3f}")
# Return average reward and maybe losses for plotting
return avg_total_reward, total_rewards # Could return losses too
# --- Main Execution ---
if __name__ == "__main__":
# 1. Initialize Environment and Agents
env = HedgingEnvironment(N_AGENTS, N_STOCKS, OPTION_K, OPTION_MATURITY)
state_dim = env.state_dim
mean_field_dim = env.mean_field_dim
action_dim = env.num_stocks # Action is change in shares for N_STOCKS
agents = [MF_DDPGAgent(state_dim, mean_field_dim, action_dim, N_STOCKS) for _ in range(N_AGENTS)]
simulator = Simulator(env, agents)
# 2. Training Loop
print("Starting Training...")
episode_rewards = []
start_time = time.time()
for episode in range(N_EPISODES):
avg_reward, _ = simulator.run_episode(episode, train_mode=True)
episode_rewards.append(avg_reward)
if (episode + 1) % 50 == 0:
print(f"Episode {episode+1}/{N_EPISODES}, Average Reward (last 50): {np.mean(episode_rewards[-50:]):.2f}")
# Optional: Save models periodically
# for i, agent in enumerate(agents):
# agent.save_model(f"mf_ddpg_agent_{i}_ep{episode+1}")
end_time = time.time()
print(f"\nTraining finished in {end_time - start_time:.2f} seconds.")
# 3. Plotting Results
plt.figure(figsize=(12, 6))
plt.plot(episode_rewards)
plt.title('Average Agent Reward per Episode')
plt.xlabel('Episode')
plt.ylabel('Average Reward')
plt.grid(True)
plt.show()
# 4. Save final models (optional)
# You might want to save only one agent if they share weights, or average weights
# Let's save the first agent's weights as representative
agents[0].save_model("mf_ddpg_final")
# 5. (Optional) Evaluate the trained agent without noise
print("\nRunning evaluation (no exploration noise)...")
states, mean_field = env.reset()
total_rewards_eval = np.zeros(env.num_agents)
done = False
step_count_eval = 0
# Use the first agent's learned policy
trained_actor = agents[0].actor_local
while not done and step_count_eval < MAX_STEPS_PER_EPISODE:
actions = np.zeros((env.num_agents, env.num_stocks))
for i in range(env.num_agents):
# Use actor prediction WITHOUT noise
actions[i] = trained_actor.predict([np.reshape(states[i], [1,-1]), np.reshape(mean_field, [1,-1])], verbose=0)[0]
# Clip actions to bounds strictly
actions[i] = np.clip(actions[i], -S0*0.5, S0*0.5)
next_states, rewards, done, next_mean_field = env.step(actions)
total_rewards_eval += rewards
states = next_states
mean_field = next_mean_field
step_count_eval += 1
# Optional: Store trajectory for plotting PnL etc.
# Store S, hedge_pos, actions, reward etc.
print(f"Evaluation finished. Final Avg Reward = {np.mean(total_rewards_eval):.2f} over {step_count_eval} steps.")
# print("Final Hedge Positions:\n", env.hedge_positions)
# print("Final Portfolio Deltas:\n", env.port_deltas)