### Interactive Brokers Volatility Trading Dashboard (Python) Source: https://context7.com/romanmichaelpaolucci/quant-guild-library/llms.txt This code snippet illustrates a real-time volatility trading dashboard using the Interactive Brokers (IB) API. It connects to IB, fetches historical data for a given symbol (SPY in this example), and prepares data for analysis. Requires an IB account and API setup. ```python from ibapi.client import EClient from ibapi.wrapper import EWrapper from ibapi.contract import Contract import pandas as pd import numpy as np from datetime import datetime class IBApp(EWrapper, EClient): def __init__(self): EClient.__init__(self, self) self.connected = False self.historical_data = {} def nextValidId(self, orderId): self.connected = True print("Connected to IB") def historicalData(self, reqId, bar): if reqId not in self.historical_data: self.historical_data[reqId] = [] self.historical_data[reqId].append({ 'date': bar.date, 'close': bar.close }) # Initialize and connect ib_app = IBApp() ib_app.connect("127.0.0.1", 7497, 0) # Create equity contract contract = Contract() contract.symbol = "SPY" contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" ``` -------------------------------- ### Numpy & Scipy: Setup for Statistical Animation Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/59. Brownian Motion for Quant Finance/brownian_motion.ipynb Initializes parameters for a statistical simulation, including mean, standard deviation, total samples, and animation frame count. It generates random samples from a normal distribution and computes the theoretical probability density function (PDF) for comparison. This setup is foundational for generating the animation data. ```python import numpy as np import plotly.graph_objects as go from scipy.stats import norm # ---------------------------------------------------------------------- # ⚙️ Setup Parameters # ---------------------------------------------------------------------- mu, sigma = 0, 1 N_total = 2000 # total samples frames_count = 100 # smoother animation bins = 30 np.random.seed(42) samples = np.random.normal(mu, sigma, N_total) # Theoretical normal PDF x = np.linspace(-4, 4, 200) theoretical_pdf = norm.pdf(x, mu, sigma) ``` -------------------------------- ### Create Plotly Policy Visualization Traces in Python Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/60. Is Trading Gambling - Quant Proves It's Not With Math/is_trading_gambling.ipynb Generates Plotly Scatter traces for visualizing EV function curves and highlighting fixed policy values with star markers. Populates lists for animated or multi-frame visualizations. Dependencies: Plotly graph_objects, ev_func_types, cycle, policy_vals, fixed_policy_val. Inputs: iteration over n_steps. Outputs: appended traces to policy_curves and policy_star_traces lists. Limitations: Memory-intensive for large n_steps, requires Plotly installation. ```python policy_curves = [] policy_star_traces = [] ev_vals_over_time = [] policy_ev_over_time = [] for step in range(n_steps): evf = ev_func_types[cycle[step]] evs = evf['fn'](policy_vals) policy_ev = evf['fn'](fixed_policy_val) ev_vals_over_time.append(evs) policy_ev_over_time.append(policy_ev) curve = go.Scatter( x=policy_vals, y=evs, mode='lines', line=dict(color=evf['color'], width=3), name=None, xaxis='x', yaxis='y', showlegend=False ) star = go.Scatter( x=[fixed_policy_val], y=[policy_ev], mode='markers+text', marker=dict(symbol='star', size=24, color='gold', line=dict(color='black', width=2)), text=[f'Policy {fixed_policy_val:.2f}'], textposition='top center', showlegend=False, xaxis='x', yaxis='y' ) policy_curves.append(curve) policy_star_traces.append(star) ``` -------------------------------- ### Build initial Plotly subplots with traces for EV and non‑stationary process in Python Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/60. Is Trading Gambling - Quant Proves It's Not With Math/is_trading_gambling.ipynb Creates a two‑column subplot figure and adds initial line traces representing the starting wealth for each sample path and the expected value line. Uses Plotly's make_subplots, adds green traces for individual paths and an orange dashed trace for the positive EV. The figure serves as the static base for later animation. ```Python fig_nonstat = make_subplots(\n rows=1, cols=2,\n subplot_titles=(\n \"Random/Ergodic Process (Positive EV & Convergence)\",\n \"Non-stationary Process (EV Shifts Over Time)\"\n ),\n column_widths=[0.5, 0.5]\n)\n# LEFT: positive EV sample paths & EV line\nfor path in range(n_paths):\n fig_nonstat.add_trace(\n go.Scatter(\n x=[0],\n y=[initial_wealth],\n mode='lines',\n line=dict(color='green', width=2),\n opacity=1.0 - path * (0.7/n_paths),\n showlegend=False\n ),\n row=1, col=1\n )\nfig_nonstat.add_trace(\n go.Scatter(\n x=[0],\n y=[initial_wealth],\n mode='lines',\n line=dict(color='orange', dash='dash', width=3),\n name='EV (Positive)',\n showlegend=True\n ),\n row=1, col=1\n) ``` -------------------------------- ### Monte Carlo Simulation of P/L Edge Using qfin in Python Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/6. How to Trade with the Black-Scholes Model/Black-ScholesTrading.ipynb Runs 100,000 simulations of the underlying asset, computes the profit‑or‑loss for each trial, and returns the average edge. Demonstrates batch evaluation of trading strategy performance. ```python premium = 14.10 * 100 pls = [] for i in range(100000): path = qf.simulations.GeometricBrownianMotion(100, 0.05, .3, 1/252, 1) pls.append(max(path.simulated_path[-1] - 100, 0)*100 - premium) np.mean(pls) ``` -------------------------------- ### Trading Strategy Simulation Parameters Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/50. Why Poker Pros Make the Best Traders (It's NOT Luck)/poker_trading.ipynb Initializes simulation parameters for trading strategy analysis including trader count, number of trades, starting capital, and trade size configuration. Sets up numpy random seed for reproducibility and initializes wealth tracking arrays for discretionary traders with positive expected value. Foundation setup for comparative analysis between different trading approaches. ```python # Simulation parameters for trading strategies n_traders = 10 n_trades = 1000 starting_capital = 1000 trade_size = 10 # Generate P&L paths for two groups of traders np.random.seed(42) # Group 1: Discretionary traders with positive EV disc_wealths = np.zeros((n_traders, n_trades + 1)) disc_wealths[:, 0] = starting_capital ``` -------------------------------- ### Initialize Game State (JavaScript) Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/5. I Made an Open-Source Market-Making Game to Practice Trading/PracticeMarketMaking/PracticeMarketMaking-main/index.html Sets the initial state of the game. It assigns random values to the dice, displays them as hidden initially, and sets initial bid-offer prices by calling 'updateBidOffer()'. This prepares the game for the first round. ```javascript function initializeGame() { const dice1 = document.getElementById("dice-1-value"); const dice2 = document.getElementById("dice-2-value"); const dice3 = document.getElementById("dice-3-value"); const initialDiceValues = [ Math.ceil(Math.random() * 6), Math.ceil(Math.random() * 6), Math.ceil(Math.random() * 6), ]; [dice1.textContent, dice2.textContent, dice3.textContent] = ["H", "H", "H"]; storedDiceValues = initialDiceValues; updateBidOffer(); } ``` -------------------------------- ### Example: Pricing an Option with Black-Scholes in Python Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/30. Trading with the Black-Scholes Implied Volatility Surface/the_implied_volatility_surface.ipynb This example demonstrates how to use the black_scholes_call function to price a call option with given market parameters. It shows the calculation with sample inputs and prints the resulting option price. ```Python S = 100 # Spot is given by the market/contract K = 100 # Strike is given by the market/contract r = 0.05 # Risk-free rate is given by the market/contract T = 1 # Time to maturity is given by the market/contract # Thanks to supply and demand, the market price of the call option is given by the market/contract C = 9.36 # Call option price is given by the market/contract # Volatility is not observable! We can proxy for it using a variety of measures but it isn't directly available. sigma = 0.2 # Volatility is NOT given by the market/contract! print("The Black-Scholes call option price is: $", np.round(black_scholes_call(S, K, r, sigma, T), 2)) ``` -------------------------------- ### Training Loop and Naive Strategy Comparison Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/52. Quant Proves Trading Cant Be Taught (But You CAN Learn This)/proof.ipynb Implements training loop comparing Q-learning agent against naive strategy that hits until 20 points. Simulates 10,000 episodes tracking cumulative wealth for both approaches. Uses Blackjack environment for game simulation and reward calculation. ```python # Training env = BlackjackEnv() agent = QLearningAgent() naive_wealth = [0] agent_wealth = [0] n_episodes = 10000 # Naive policy - hit until 20 def naive_policy(player_sum, dealer_up): return player_sum < 20 # Training loop for episode in range(n_episodes): # Naive strategy naive_reward = env.play_hand(naive_policy) naive_wealth.append(naive_wealth[-1] + naive_reward) # Q-learning agent player_sum = [env.deal(), env.deal()] dealer_up = env.deal() while sum(player_sum) < 21: state = (sum(player_sum), dealer_up) action = agent.get_action(sum(player_sum), dealer_up) if action == 0: # Stay break player_sum.append(env.deal()) reward = env.play_hand(lambda x,y: False) # Just to get the outcome agent.update(state, action, reward) agent_wealth.append(agent_wealth[-1] + reward) ``` -------------------------------- ### Simulate Underlying Dynamics and Plot Option Payoff in Python Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/6. How to Trade with the Black-Scholes Model/Black-ScholesTrading.ipynb Uses qfin to generate a geometric Brownian motion price path, then visualises the path, strike price, and profit‑or‑loss at expiry with Matplotlib. Also prints the initial premium and realized P/L based on the simulated terminal price. ```python import matplotlib.pyplot as plt import qfin as qf # simulate dynamics of the underlying according to Geometric Brownian Motion path = qf.simulations.GeometricBrownianMotion(100, 0.05, .3, 1/252, 1) # create a chart of the price path and the strike price plt.title("Terminal Value of an Option Contract") plt.hlines(100, 0, 252, label='Strike', color='orange') plt.plot(path.simulated_path, label='Price Path', color='white') if max(path.simulated_path[-1] - 100, 0) == 0: plt.vlines(252, path.simulated_path[-1], 100, color='red', label="P/L") else: plt.vlines(252, 100, path.simulated_path[-1], color='green', label="P/L") plt.style.use('dark_background') plt.xlabel('Time') plt.ylabel('Stock Price') plt.legend() plt.show() # print the premium and the resulting P/L print("Premium at t=0:", black_scholes_call(100, 100, .3, .05, 1)) print("P/L:", max(path.simulated_path[-1] - 100, 0) - black_scholes_call(100, 100, .3, .05, 1)) ``` -------------------------------- ### Python Time Series Forecast Failure Example Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/44. Time Series Analysis for Quant Finance/time_series_analysis_for_quant_finance.ipynb Generates sample time series data with an earnings jump and visualizes the failure of a pre-earnings forecast due to this event. It simulates historical data, a jump at a specific day, and a forecast with confidence bands. This example uses `numpy` for data generation, `datetime` and `timedelta` for date manipulation, and `plotly.graph_objects` for plotting. ```python # Generate sample time series data with an earnings jump np.random.seed(42) n_points = 100 dates = [datetime(2024,1,1) + timedelta(days=int(x)) for x in range(n_points)] price = 100 prices = [] # Add an earnings event around day 60 earnings_day = 60 jump_magnitude = 0.15 # 15% jump for i in range(n_points): if i == earnings_day: # Random direction of the earnings jump (up or down) direction = np.random.choice([-1, 1]) price *= (1 + direction * jump_magnitude) else: price *= (1 + np.random.normal(0.0002, 0.01)) prices.append(price) # Create figure for earnings example fig = make_subplots(rows=1, cols=1, subplot_titles=('Forecast Failure at Earnings Event',)) # Original Data up to earnings fig.add_trace( go.Scatter( x=dates[:earnings_day], y=prices[:earnings_day], mode='lines', line=dict(color='rgba(0, 255, 255, 1)'), name='Historical Data' ) ) # Data after earnings fig.add_trace( go.Scatter( x=dates[earnings_day:], y=prices[earnings_day:], mode='lines', line=dict(color='rgba(0, 255, 255, 1)'), name='Post-Earnings Data' ) ) # Generate pre-earnings forecast window = 10 last_price = prices[earnings_day-1] forecast = [last_price] forecast_days = 20 current_std = np.std(prices[earnings_day-window:earnings_day]) for _ in range(forecast_days-1): forecast.append(forecast[-1] * (1 + np.random.normal(0.0002, 0.01))) current_std *= 1.1 forecast_dates = [dates[earnings_day-1] + timedelta(days=int(x)) for x in range(forecast_days)] # Calculate confidence bands forecast_upper = np.array(forecast) + 2*np.array([current_std] * forecast_days) forecast_lower = np.array(forecast) - 2*np.array([current_std] * forecast_days) # Add forecast fig.add_trace( go.Scatter( x=forecast_dates, y=forecast, mode='lines', line=dict(color='rgba(57, 255, 20, 1)'), name='Pre-Earnings Forecast' ) ) # Add confidence bands fig.add_trace( go.Scatter( x=forecast_dates, y=forecast_upper, mode='lines', line=dict(color='rgba(57, 255, 20, 0.2)'), name='Forecast Confidence Band', showlegend=False ) ) fig.add_trace( go.Scatter( x=forecast_dates, y=forecast_lower, mode='lines', line=dict(color='rgba(57, 255, 20, 0.2)'), fill='tonexty', showlegend=False ) ) # Add vertical line for earnings # Use add_shape instead of add_vline to avoid type error with datetime fig.add_shape( type="line", x0=dates[earnings_day], x1=dates[earnings_day], y0=0, y1=1, yref="paper", line=dict( color="red", width=2, dash="dash" ) ) # Add earnings annotation fig.add_annotation( x=dates[earnings_day], y=1, yref="paper", text="Earnings Event", showarrow=False, yshift=10 ) # Update layout fig.update_layout( width=1200, height=600, title='Time Series Forecast Failure: Earnings Event Example', showlegend=True, plot_bgcolor='rgba(0,0,0,0)', paper_bgcolor='rgba(0,0,0,0)', font=dict(color='white') ) # Update axes fig.update_xaxes( showgrid=True, gridwidth=1, gridcolor='rgba(128,128,128,0.2)', zeroline=True, zerolinewidth=1, zerolinecolor='rgba(128,128,128,0.5)' ) fig.update_yaxes( showgrid=True, gridwidth=1, gridcolor='rgba(128,128,128,0.2)', zeroline=True, zerolinewidth=1, zerolinecolor='rgba(128,128,128,0.5)' ) fig.show() ``` -------------------------------- ### Initialize Market Making Simulation Parameters Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/44. Time Series Analysis for Quant Finance/time_series_analysis_for_quant_finance.ipynb Sets up initial parameters for the market making simulation including spread, trading activity rate, and moving average window. Prepares arrays for tracking simulation data. ```python n_steps = 100 dates = pd.date_range(start='2023-01-01', periods=n_steps) # Market making parameters spread = 0.7 lambda_rate = 0.3 window_size = 10 # Initialize arrays pnl = np.zeros(n_steps) positions = np.zeros(n_steps) dice_outcomes = np.zeros(n_steps) cumulative_pnl = np.zeros(n_steps) moving_avg = np.zeros(n_steps) # Create figure for animation fig = make_subplots(rows=3, cols=1, subplot_titles=('Dice Outcomes & Market Making Levels', 'Trading Positions', 'Cumulative P&L'), vertical_spacing=0.1) ``` -------------------------------- ### Generate Correlated Brownian Motions with Random Correlation Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/14. Quant Investing for Beginners/Quant Investing Strategies for Beginners.ipynb Simulates time-varying correlation between two assets using uniform random correlation values at each timestep. Demonstrates the effects of increasing correlation variability on asset co-movement. Requires numpy and matplotlib for execution. ```Python # Generate correlation that changes over time rho_random = np.random.uniform(0.6, 0.8, T) dW1 = np.random.normal(0, np.sqrt(dt), T) dW2 = np.array([rho_random[t] * dW1[t] + np.sqrt(1 - rho_random[t]**2) * np.random.normal(0, np.sqrt(dt)) for t in range(T)]) S1_rand = np.cumsum(dW1) S2_rand = np.cumsum(dW2) # Plot plt.figure(figsize=(10, 5)) plt.plot(S1_rand, label="Asset 1") plt.plot(S2_rand, label="Asset 2") plt.title("Brownian Motions with Changing Correlation") plt.legend() plt.show() # Plot correlation over time plt.figure(figsize=(10, 3)) plt.plot(rho_random, label="Correlation Over Time", color='red') plt.axhline(y=.7, color='black', linestyle='--') plt.title("Time-Varying Correlation") plt.legend() plt.show() ``` -------------------------------- ### Option Pricing Function Visualization (Python) Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/38. Finite Differences Option Pricing for Quant Finance/finite_differences_option_pricing.ipynb This snippet demonstrates the option pricing function f(x) = sqrt(x) + C, providing a simple example of an option pricing model. Plotly is used for visualization. ```python import numpy as np import plotly.graph_objects as go from plotly.subplots import make_subplots # Generate x values (using positive values since we're taking square root) x = np.linspace(0.01, 4, 200) # Start from small positive number to avoid division by zero # Create subplots fig = make_subplots(rows=1, cols=2, subplot_titles=('Pricing Differential Equation: f'(x) = 1/(2√x)', 'Option Pricing Function: f(x) = √x + C')) ``` -------------------------------- ### Generate Modified Ornstein-Uhlenbeck Process (Python) Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/58. Why Quant Models Break/why_models_break.ipynb This Python function simulates a modified Ornstein–Uhlenbeck process with higher mean-reversion and variance to model persistent high variance. The process is used in generating synthetic data for the example. It uses NumPy for calculations and returns a time series of variance. ```python import numpy as np from scipy import stats import plotly.graph_objects as go from plotly.subplots import make_subplots # Seed for reproducibility np.random.seed(42) # Parameters n_samples = 150_000 n_frames = 60 x_range = np.linspace(-6, 6, 300) # --- Modified Ornstein–Uhlenbeck process for persistent high variance --- def ou_process(theta=1.0, mu=3.0, sigma=1.0, dt=0.1, n_steps=n_frames): """ OU process with high mean-reversion level (mu=3) and lower mean reversion speed (theta=1) to make variance spike early and remain elevated. """ x = np.zeros(n_steps) x[0] = 0.5 # start low, then rise for t in range(1, n_steps): dx = theta * (mu - x[t-1]) * dt + sigma * np.sqrt(dt) * np.random.normal() x[t] = x[t-1] + dx return np.maximum(x, 0.1) # keep variance positive # Generate variance and mean paths time_points = np.linspace(0, n_frames/10, n_frames) variance_path = ou_process() ``` -------------------------------- ### Create Comparative Signal Visualization in Python Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/42. Quant on Trading and Investing/quant_on_trading_investing_market.ipynb Generates a side-by-side comparison of backtest vs live trading signals using Plotly. Demonstrates the instability of statistical relationships in financial data through visualization. ```python np.random.seed(42) n_bins = 20 backtest_x = np.linspace(-3, 3, n_bins) backtest_y = 0.3 * backtest_x + np.random.normal(0, 0.1, n_bins) live_x = np.linspace(-3, 3, n_bins) live_y = np.random.normal(0, 0.5, n_bins) fig = make_subplots(rows=1, cols=2, subplot_titles=('Backtest Signal (We Assume is Stable)', 'Live Trading Signal (Is Not Stable)'), horizontal_spacing=0.1) fig.add_trace( go.Bar(x=backtest_x, y=backtest_y, marker_color='rgba(0, 191, 255, 0.6)', name='Backtest Signal'), row=1, col=1 ) fig.add_trace( go.Bar(x=live_x, y=live_y, marker_color='rgba(255, 99, 71, 0.6)', name='Live Signal'), row=1, col=2 ) fig.update_layout( width=1000, height=400, plot_bgcolor='rgba(0,0,0,0)', paper_bgcolor='rgba(0,0,0,0)', font=dict(color='white'), showlegend=True ) ``` -------------------------------- ### Initialize Plotly Subplots with NumPy Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/38. Finite Differences Option Pricing for Quant Finance/finite_differences_option_pricing.ipynb This Python code initializes a Plotly figure with subplots using the make_subplots function and generates x-axis values using numpy.linspace. This setup is typical for creating multi-plot figures where each subplot might display different aspects of financial data or model outputs. ```python import numpy as np import plotly.graph_objects as go from plotly.subplots import make_subplots # Generate x values x = np.linspace(-2, 5, 200) ``` -------------------------------- ### Generate Correlated Brownian Motions with Evolving Correlation Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/14. Quant Investing for Beginners/Quant Investing Strategies for Beginners.ipynb Models a dynamic correlation process using an autoregressive-like structure. Simulates more realistic financial scenarios where correlations shift gradually rather than abruptly. Dependencies include numpy and matplotlib for simulation and visualization. ```Python import numpy as np import matplotlib.pyplot as plt # Set random seed for reproducibility np.random.seed(42) # Simulation parameters T = 252 # Number of trading days dt = 1 # Time step # Generate a non-stationary correlation process using an AR(1)-like model rho = np.zeros(T) rho[0] = np.random.uniform(-0.8, 0.8) # Initial correlation alpha = 0.9 # Persistence factor (closer to 1 means smoother evolution) shock_std = 0.1 # Standard deviation of random shocks for t in range(1, T): rho[t] = alpha * rho[t-1] + (1 - alpha) * np.random.uniform(-0.8, 0.8) + np.random.normal(0, shock_std) rho[t] = np.clip(rho[t], -1, 1) # Ensure correlation stays within [-1, 1] # Generate Brownian motions with evolving correlation dW1 = np.random.normal(0, np.sqrt(dt), T) dW2 = np.zeros(T) for t in range(T): dW2[t] = rho[t] * dW1[t] + np.sqrt(1 - rho[t]**2) * np.random.normal(0, np.sqrt(dt)) # Compute asset price paths S1_evolving = np.cumsum(dW1) S2_evolving = np.cumsum(dW2) # Plot asset price movements plt.figure(figsize=(10, 5)) plt.plot(S1_evolving, label="Asset 1") plt.plot(S2_evolving, label="Asset 2") plt.title("Brownian Motions with Non-Stationary Correlation") plt.legend() plt.show() # Plot correlation evolution over time plt.figure(figsize=(10, 3)) plt.plot(rho, label="Evolving Correlation", color='red') plt.axhline(y=0, color='black', linestyle='--') plt.title("Time-Varying Correlation") plt.legend() plt.show() ``` -------------------------------- ### Calculate Fraction of Traders Who Lost Money (Python) Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/46. Is Trading Luck or Skill Quant Debunks Trading Gurus with Math/is_trading_luck_or_skill.ipynb Determines the percentage and count of traders who ended up losing money compared to their starting wealth. This calculation uses NumPy for efficient array manipulation. ```python # Calculate fraction of traders who lost money at the end losses = np.zeros(100) for i in range(100): final_wealth = trader_wealth[i,-1] starting_wealth = trader_wealth[i,0] if final_wealth < starting_wealth: losses[i] = 1 fraction_with_losses = np.mean(losses) print(f"Fraction of traders who lost money: {fraction_with_losses:.1%}") print(f"Number of traders who lost money: {int(fraction_with_losses * 100)} out of 100") ``` -------------------------------- ### Initialize and Visualize Brownian Motion Simulation Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/59. Brownian Motion for Quant Finance/brownian_motion.ipynb This code snippet initializes parameters for Brownian motion simulation, calculates histogram data and theoretical distribution, and sets up initial scatter plots for paths and histograms using Plotly. It prepares data for animating the simulation over time. ```python init_t = 0 time_show = time_grid[:init_t + 1] hist_values = W[:, init_t] hist_fig = np.histogram(hist_values, bins=30, density=True) hist_y = 0.5 * (hist_fig[1][1:] + hist_fig[1][:-1]) hist_x = hist_fig[0] theory_x = np.zeros_like(hist_y) scatter_paths_init = [ go.Scatter( x=time_show, y=W[i, :init_t + 1], mode='lines', line=dict(color='#00ffff', width=1), opacity=0.3, showlegend=False, hoverinfo='none' ) for i in range(n_paths_show) ] scatter_main_init = go.Scatter( x=time_show, y=W[0, :init_t + 1], mode='lines', line=dict(color='magenta', width=3), ) hist_init = go.Bar( y=hist_y, x=hist_x, width=(hist_y[1] - hist_y[0]) if len(hist_y) > 1 else 0.5, orientation='h', marker=dict(color='rgba(100,255,100,0.6)') ) theory_line_init = go.Scatter( x=theory_x, y=hist_y, mode='lines', line=dict(color='magenta', width=3) ) vline_init = go.Scatter( x=[init_t, init_t], y=[-20, 20], mode='lines', line=dict(color='yellow', dash='dash'), showlegend=False ) ``` -------------------------------- ### Visualize Mid Price Distribution - Python Plotly Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/35. What Does AI Actually Learn/what_does_ai_actually_learn.ipynb Generates a histogram to visualize the distribution of mid-prices, derived from bid and ask prices. This example demonstrates how AI can model the expected distribution of values. It uses Plotly for creating the histogram and includes layout customizations for a dark theme. ```python import numpy as np import plotly.graph_objects as go # Generate sample data np.random.seed(42) n_samples = 10000 E_X = 3.5 u = np.random.uniform(0, 1, n_samples) # Calculate bid, ask and mid prices bids = E_X - 0.5 + u asks = E_X + 0.5 + u mids = (bids + asks) / 2 # Create histogram fig = go.Figure() fig.add_trace(go.Histogram( x=mids, nbinsx=50, name='Mid Price Distribution', marker_color='#00b4ff' )) # Update layout fig.update_layout( template='plotly_dark', paper_bgcolor='rgba(0,0,0,0)', font=dict(color='white'), title_text='Distribution of Mid Prices', title_x=0.5, title_font_size=20, xaxis_title='Mid Price', yaxis_title='Frequency', showlegend=False, yaxis=dict( gridwidth=1, gridcolor='rgba(128,128,128,0.2)', zeroline=True, zerolinewidth=1, zerolinecolor='rgba(128,128,128,0.5)', showgrid=True ) ) fig.show() ``` -------------------------------- ### Calculate bid/offer prices and simulate market trading in JavaScript Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/5. I Made an Open-Source Market-Making Game to Practice Trading/PracticeMarketMaking/PracticeMarketMaking-main/index.html This function validates midpoint and spread inputs, calculates bounded bid/offer prices between 3-18, computes expected dice values with 'H' as 3.5, determines buyer and seller edges, simulates trading quantities for 100 buyers and sellers, and dynamically displays market results in the DOM. It depends on specific HTML elements and global variables for price displays. The simulation stores results in window.marketResult for subsequent profit/loss calculations. ```javascript const midpoint = parseFloat(document.getElementById("midpoint").value) || 0; const spread = parseFloat(document.getElementById("spread").value) || 0; if (midpoint <= 0 || spread <= 0) { alert("Please provide valid midpoint and spread values."); return; } // Calculate bid and offer prices const bid = Math.max(3, midpoint - spread / 2); const offer = Math.min(18, midpoint + spread / 2); // Update displayed bid and offer prices bidPrice.textContent = bid.toFixed(2); offerPrice.textContent = offer.toFixed(2); storedMidpoint = midpoint; storedSpread = spread; // Calculate the expected value of dice (H = 3.5) const expectedDiceValues = storedDiceValues.map(value => (value === "H" ? 3.5 : parseFloat(value))); const expectedOutcome = expectedDiceValues.reduce((acc, value) => acc + value, 0); // Calculate edge for buyers and sellers const edgeBuy = Math.max(0, Math.min(1, (offer - expectedOutcome) / spread)); // Edge for buyers const edgeSell = Math.max(0, Math.min(1, (expectedOutcome - bid) / spread)); // Edge for sellers // Simulate quantity of buyers and sellers const nBuy = 100; // Number of buyers const nSell = 100; // Number of sellers const buyers = Math.round(edgeSell * nBuy); const sellers = Math.round(edgeBuy * nSell); // Display the market result const resultDiv = document.getElementById("market-result"); const resultText = `Purchased ${buyers} @ Offer: ${offer.toFixed(2)}, Sold ${sellers} @ Bid: ${bid.toFixed(2)}`; if (!resultDiv) { const newResultDiv = document.createElement("div"); newResultDiv.id = "market-result"; newResultDiv.style.textAlign = "center"; newResultDiv.style.color = "#76c7c0"; newResultDiv.style.fontWeight = "bold"; newResultDiv.textContent = resultText; priceTable.parentNode.insertBefore(newResultDiv, priceTable.nextSibling); } else { resultDiv.textContent = resultText; } // Store results for P/L calculation after realization window.marketResult = { buyers, sellers, bid, offer, spread }; ``` -------------------------------- ### Example Usage: Heston FFT Pricing (Python) Source: https://github.com/romanmichaelpaolucci/quant-guild-library/blob/main/2025 Video Lectures/39. Heston Stochastic Volatility Model and Fast Fourier Transforms/heston_fft.ipynb Demonstrates how to use the Heston FFT pricing functions. It sets up Heston parameters and initial conditions, then calculates a grid of call prices and a single call price for a specific strike. ```python # parameters S0, r, q, T = 100.0, 0.01, 0.00, 1.0 hp = HestonParams(kappa=1.5, theta=0.04, sigma=0.3, rho=-0.7, v0=0.04) # full grid of calls K, C = heston_fft_calls(S0, T, r, q, hp, N=4096, eta=0.25, alpha=1.5) # single strikes call_100 = heston_fft_call_price(S0, 100, T, r, q, hp) call_100 ```