Skip to content
TheChatArchiveThe Chat Archive
o3-mini· OpenAIHugging Face LMArena Human Preference 140K

Write and simulate using a GBM in Python a profitable market making algorithm for crypto…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Qwenqwen3-235b-a22b-no-thinking’s answer.
  1. User

    Write and simulate using a GBM in Python a profitable market making algorithm for crypto perpetual swaps.

  2. Assistant

    Below is an example of a “toy‐model” simulation in Python that uses a Geometric Brownian Motion (GBM) to simulate the underlying price and implements a very simple market‐making strategy for a crypto perpetual swap. (Remember, this is a simplified illustration only and not investment advice.)

    In this example, the market maker continuously posts a bid and an ask around the mid (“fair”) price. The quotes are adjusted by a simple “inventory‐skew” rule so that if the market maker holds a positive (or negative) position their quotes shift to favor reducing that position. (More sophisticated strategies exist—for example, those based on the Avellaneda–Stoikov framework—but for illustration we use fixed quotes plus an inventory adjustment.) In each simulation time step the underlying price is evolved using GBM, and we “fill” our bid if the next price falls below our bid and “fill” our ask if the next price rises above our ask. (In real markets execution is more complicated.) Finally, we mark the inventory to market to compute a profit‐and‐loss (PnL) profile.

    Below is the complete Python code. You can run it (for example in a Jupyter notebook) to see one simulation; you might wish to run many simulations or experiment with the parameters to understand the dynamics.


    import numpy as np
    import matplotlib.pyplot as plt
    
    # 1. Set Simulation Parameters
    
    # GBM parameters
    T = 1.0             # total time in years
    N = 252 * 6.5 * 60  # number of time steps (simulate one minute steps in 6.5 trading hours per day over 252 days, for instance)
    dt = T / N          # time step (in years)
    mu = 0.05           # annual drift
    sigma = 0.2         # annual volatility
    S0 = 100.0          # starting price
    
    # Market making parameters
    base_half_spread = 0.10  # base half-spread (in price units)
    inventory_penalty = 0.05 # adjustment to the quotes per unit inventory held
    
    # Simulation starting cash and inventory
    cash = 0.0
    inventory = 0
    PnL_history = []   # to record portfolio value over time
    
    # 2. Simulate the Underlying Price using GBM
    
    np.random.seed(42)  # for reproducibility
    # Pre-calculate drift and diffusion factors
    drift = (mu - 0.5 * sigma**2) * dt
    diffusion = sigma * np.sqrt(dt)
    prices = np.zeros(N)
    prices[0] = S0
    
    # Generate the GBM price path
    for t in range(1, N):
        prices[t] = prices[t-1] * np.exp(drift + diffusion * np.random.normal())
    
    # 3. Simulate the Market Making Algorithm
    
    # For simplicity, we assume that at the beginning of each time step we post both bid and ask.
    # If the next price jump crosses our bid or ask levels, we get executed.
    # The bid/ask quotes are adjusted by our current inventory in order to bias order flow toward neutralizing the inventory.
    
    # To record the times and trades
    trade_times = []
    trade_details = []  # each record: (t, side, price)
    
    # Initialize arrays for tracking positions
    inventory_history = np.zeros(N)
    cash_history = np.zeros(N)
    
    for t in range(N - 1):
        # Define the "fair" or mid price at time t
        mid_price = prices[t]
        
        # Adjust quotes based on inventory: if inventory is positive (long), we want to sell: lower our bid (so less likely to buy) and increase our ask (so more likely to sell)
        # Conversely, if inventory is negative, we want to buy back.
        bid = mid_price - base_half_spread - inventory_penalty * inventory
        ask = mid_price + base_half_spread - inventory_penalty * inventory
        
        # The next market price
        next_price = prices[t+1]
        
        # Execution logic:
        # If the price falls below our bid, it means a sell market order hit our bid => we buy.
        # If the price rises above our ask, it means a buy market order hit our ask => we sell.
        # In a given time step it is possible (in this simplified world) that both conditions hold 
        # (if the price made a huge swing) and we assume both fills occur.
        
        executed = False
        # Check bid execution
        if next_price <= bid:
            # Buy executed at our bid price
            inventory += 1
            cash -= bid
            trade_times.append(t)
            trade_details.append((t, 'buy', bid))
            executed = True
    
        # Check ask execution
        if next_price >= ask:
            # Sell executed at our ask price
            inventory -= 1
            cash += ask
            trade_times.append(t)
            trade_details.append((t, 'sell', ask))
            executed = True
    
        # Optionally, one could allow both fills in one step if the jump is extraordinary.
        
        # Record inventory and cash
        inventory_history[t+1] = inventory
        cash_history[t+1] = cash
        
        # Evaluate and store mark-to-market portfolio value: cash + inventory * current price.
        PnL_history.append(cash + inventory * prices[t])
    
    # Mark final PnL (using the last simulated price to value inventory)
    final_value = cash + inventory * prices[-1]
    print(f"Final mark-to-market portfolio value: {final_value:.2f}")
    
    # 4. Plot the Simulation Results
    
    time_axis = np.linspace(0, T, N)
    
    plt.figure(figsize=(14, 10))
    
    # Plot the underlying price
    plt.subplot(3,1,1)
    plt.plot(time_axis, prices, label='Underlying Price', color='blue')
    plt.xlabel('Time (years)')
    plt.ylabel('Price')
    plt.title('Underlying GBM Price Path')
    plt.legend()
    
    # Plot inventory vs. time
    plt.subplot(3,1,2)
    plt.plot(time_axis, inventory_history, label='Inventory', color='purple')
    plt.xlabel('Time (years)')
    plt.ylabel('Inventory')
    plt.title('Inventory over Time')
    plt.legend()
    
    # Plot the mark-to-market portfolio PnL over time
    plt.subplot(3,1,3)
    # Some early values may be missing because we recorded PnL starting at t=0.
    plt.plot(time_axis[1:], PnL_history, label='Mark-to-Market PnL', color='green')
    plt.xlabel('Time (years)')
    plt.ylabel('PnL')
    plt.title('Portfolio Value over Time')
    plt.legend()
    
    plt.tight_layout()
    plt.show()
    
    # 5. Print out a few trade details for inspection
    print("Sample trades:")
    for record in trade_details[:10]:
        t_step, side, price_executed = record
        sim_time = t_step * dt
        print(f"Time {sim_time:.4f} years, Side: {side}, Execution Price: {price_executed:.2f}")
    

    Explanation

    1. GBM Price Simulation:
      The code sets up a GBM with drift mu and volatility sigma. Each discrete step simulates the new price as:
      [ S_{t+1} = S_t \times \exp\Bigl((\mu - 0.5 \sigma^2),dt + \sigma\sqrt{dt},Z\Bigr) ]
      with a normally distributed random shock ( Z ).

    2. Market Making Logic:
      At every time step, the algorithm posts a bid and ask. The base half-spread is set to base_half_spread, and the quotes are adjusted by an inventory_penalty multiplied by the current inventory. This “skew” is meant to help drive the inventory back to zero.

      • Bid Execution: If the next GBM price is below our bid, our bid is “hit” and we buy one unit (inventory increases by 1, and cash decreases by the bid price).
      • Ask Execution: If the next GBM price is above our ask, our ask is “hit” and we sell one unit (inventory decreases by 1, and cash increases by the ask price).
    3. Portfolio Mark-to-Market:
      At each step (and finally), the portfolio value is calculated as:
      [ \text{Portfolio Value} = \text{Cash} + \text{Inventory} \times \text{Current Price} ] This is then plotted over time.

    4. Simulation Plots and Trades:
      The simulation plots show (a) the underlying price path, (b) the evolution of inventory, and (c) the portfolio’s mark‐to‐market profit and loss (PnL).

    Important Caveats

    • Simplifications:
      Real market making incorporates order book dynamics, transaction costs, latency, funding rates (especially for perpetual swaps), and more complex risk management. This simulation streamlines many aspects for clarity.

    • Profitability:
      In simulation, whether the strategy is “profitable” will depend heavily on the chosen parameters (spread, inventory adjustment, volatility, drift, execution assumptions, etc.). This code is meant as an instructive starting point rather than a battle‐tested trading system.

    • Not Investment Advice:
      This example is provided for educational purposes only. Do not use it for live trading without extensive testing and additional risk management.

    Feel free to modify the parameters (for example, the spread or inventory penalty) or the fill logic to explore how the strategy behaves under different market conditions.

  3. User

    Where is the code?

  4. Assistant

    Below is the complete Python code for the simulation. You can copy and paste it into your Python environment (such as a Jupyter Notebook) and run it to see the simulation in action.


    import numpy as np
    import matplotlib.pyplot as plt
    
    # 1. Set Simulation Parameters
    
    # GBM parameters
    T = 1.0             # total time in years
    N = 252 * 6.5 * 60  # number of time steps (simulate one minute steps in 6.5 trading hours per day over 252 days)
    dt = T / N          # time step (in years)
    mu = 0.05           # annual drift
    sigma = 0.2         # annual volatility
    S0 = 100.0          # starting price
    
    # Market making parameters
    base_half_spread = 0.10  # base half-spread (in price units)
    inventory_penalty = 0.05 # additional adjustment per unit of inventory
    
    # Simulation starting cash and inventory
    cash = 0.0
    inventory = 0
    PnL_history = []         # to record portfolio value for each step
    
    # 2. Simulate the Underlying Price using GBM
    
    np.random.seed(42)  # for reproducibility
    
    # Pre-calculate drift and diffusion factors
    drift = (mu - 0.5 * sigma**2) * dt
    diffusion = sigma * np.sqrt(dt)
    prices = np.zeros(N)
    prices[0] = S0
    
    # Generate the GBM price path
    for t in range(1, N):
        prices[t] = prices[t-1] * np.exp(drift + diffusion * np.random.normal())
    
    # 3. Simulate the Market Making Algorithm
    
    # At each time step, the algorithm posts both a bid and an ask around the mid-price.
    # The quotes are adjusted by our current inventory to bias future fills that push the inventory toward 0.
    # Fill logic: if the next price drop goes below the bid, we "buy" (bid is hit);
    # if the next price rises above the ask, we "sell" (ask is hit).
    
    # For logging executed trades
    trade_times = []
    trade_details = []  # each record: (time step, side, execution price)
    
    # Initialize arrays to record inventory and cash history through time
    inventory_history = np.zeros(N)
    cash_history = np.zeros(N)
    
    for t in range(N - 1):
        mid_price = prices[t]
        # Adjust quotes based on current inventory
        # If inventory is positive, we shift our quotes to favor selling (i.e., lower our chance to buy)
        bid = mid_price - base_half_spread - inventory_penalty * inventory
        ask = mid_price + base_half_spread - inventory_penalty * inventory
        
        # Look at the price at the next time step
        next_price = prices[t+1]
        
        # Execution: Check whether our bid or ask get filled.
        # If next_price <= bid, then our bid is hit (we "buy")
        if next_price <= bid:
            # Buy at the bid price
            inventory += 1
            cash -= bid
            trade_times.append(t)
            trade_details.append((t, 'buy', bid))
        
        # If next_price >= ask, then our ask is hit (we "sell")
        if next_price >= ask:
            # Sell at the ask price
            inventory -= 1
            cash += ask
            trade_times.append(t)
            trade_details.append((t, 'sell', ask))
        
        # Record our inventory and cash for this time step
        inventory_history[t+1] = inventory
        cash_history[t+1] = cash
        
        # Compute the mark-to-market portfolio value: cash + inventory * current price.
        PnL_history.append(cash + inventory * prices[t])
    
    # Final mark-to-market portfolio value (using the last available price)
    final_value = cash + inventory * prices[-1]
    print(f"Final mark-to-market portfolio value: {final_value:.2f}")
    
    # 4. Plot the Simulation Results
    
    time_axis = np.linspace(0, T, N)
    
    plt.figure(figsize=(14, 10))
    
    # Plot the underlying price path
    plt.subplot(3, 1, 1)
    plt.plot(time_axis, prices, label='Underlying Price', color='blue')
    plt.xlabel('Time (years)')
    plt.ylabel('Price')
    plt.title('Underlying GBM Price Path')
    plt.legend()
    
    # Plot inventory over time
    plt.subplot(3, 1, 2)
    plt.plot(time_axis, inventory_history, label='Inventory', color='purple')
    plt.xlabel('Time (years)')
    plt.ylabel('Inventory')
    plt.title('Inventory over Time')
    plt.legend()
    
    # Plot the mark-to-market PnL over time
    plt.subplot(3, 1, 3)
    plt.plot(time_axis[1:], PnL_history, label='Mark-to-Market PnL', color='green')
    plt.xlabel('Time (years)')
    plt.ylabel('PnL')
    plt.title('Portfolio Value over Time')
    plt.legend()
    
    plt.tight_layout()
    plt.show()
    
    # 5. Print out a few trade details for inspection
    print("Sample trades:")
    for record in trade_details[:10]:
        t_step, side, price_executed = record
        sim_time = t_step * dt
        print(f"Time {sim_time:.4f} years, Side: {side}, Execution Price: {price_executed:.2f}")
    

    Code Explanation

    1. GBM Price Simulation:

      • The code initializes a price series following a Geometric Brownian Motion (GBM) with the formula:
        [ S_{t+1} = S_t \times \exp\left(\left(\mu - \frac{1}{2}\sigma^2\right)dt + \sigma \sqrt{dt},Z\right) ]
        where ( Z ) is a standard normal random variable.
    2. Market Making Strategy:

      • The market maker posts bid and ask prices around the mid-price.
      • The bid price is adjusted downward, and the ask upward relative to the mid-price.
      • The quotes include an additional offset based on the current inventory. For example, if the market maker is long (positive inventory), the bid is decreased further and the ask increased, making it more likely to sell and hence reduce the long exposure.
      • If the next price falls below the bid, the bid is "hit" (simulated as a fill), and similarly, if the price rises above the ask, the ask is "hit".
    3. Portfolio Update and Visualization:

      • After each time step, the code updates the inventory, cash, and marks the portfolio to market.
      • It then produces plots of the underlying price path, inventory over time, and mark-to-market PnL (portfolio value).
    4. Caveats & Notes:

      • This is a simplified version of a market-making algorithm for illustration only.
      • Real-world implementations would need to consider more detailed order book dynamics, transaction costs, latency, and other risk management factors.

    Feel free to modify the parameters and logic to experiment with different market scenarios!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.