{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ec44d369",
   "metadata": {},
   "source": [
    "<div style=\"background-color:#000;\"><img src=\"pqn.png\"></img></div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e794167",
   "metadata": {},
   "source": [
    "This code simulates a trading strategy to assess the risk of ruin. It defines functions to simulate individual trades, an entire trading strategy, and calculate the risk of ruin over multiple simulations. The parameters include initial capital, win probability, average win/loss amounts, and the number of trades. The output is a plot showing how the probability of a winning trade affects the risk of ruin. This can help traders understand the robustness of their trading strategy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "23e1fe3a",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8a7ec979",
   "metadata": {},
   "source": [
    "Simulate a single trade with given win probability and average win/loss amounts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "23261ffb",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "def simulate_trade(win_prob, avg_win, avg_loss):\n",
    "    \"\"\"\n",
    "    Simulate a single trade with given win probability and average win/loss amounts.\n",
    "    \n",
    "    Parameters\n",
    "    ----------\n",
    "    win_prob : float\n",
    "        Probability of a winning trade\n",
    "    avg_win : float\n",
    "        Average amount won per winning trade\n",
    "    avg_loss : float\n",
    "        Average amount lost per losing trade\n",
    "    \n",
    "    Returns\n",
    "    -------\n",
    "    float\n",
    "        The result of the trade, positive for win and negative for loss\n",
    "    \"\"\"\n",
    "\n",
    "    # Determine the trade outcome based on win probability and return the result\n",
    "    if np.random.rand() < win_prob:\n",
    "        return avg_win\n",
    "    else:\n",
    "        return -avg_loss"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f6a99690",
   "metadata": {},
   "source": [
    "Simulate the entire trading strategy over a given number of trades"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8bfa85ae",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "def simulate_trading_strategy(initial_capital, trades, win_prob, avg_win, avg_loss):\n",
    "    \"\"\"\n",
    "    Simulate the entire trading strategy over a given number of trades.\n",
    "    \n",
    "    Parameters\n",
    "    ----------\n",
    "    initial_capital : float\n",
    "        Starting capital for the trading strategy\n",
    "    trades : int\n",
    "        Number of trades to simulate\n",
    "    win_prob : float\n",
    "        Probability of a winning trade\n",
    "    avg_win : float\n",
    "        Average amount won per winning trade\n",
    "    avg_loss : float\n",
    "        Average amount lost per losing trade\n",
    "    \n",
    "    Returns\n",
    "    -------\n",
    "    list\n",
    "        Capital history as a list of capital values after each trade\n",
    "    \"\"\"\n",
    "\n",
    "    # Initialize capital and history list\n",
    "    capital = initial_capital\n",
    "    capital_history = [capital]\n",
    "\n",
    "    # Simulate each trade and update capital\n",
    "    for _ in range(trades):\n",
    "        capital += simulate_trade(win_prob, avg_win, avg_loss)\n",
    "        capital_history.append(capital)\n",
    "\n",
    "    return capital_history"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79c3ffec",
   "metadata": {},
   "source": [
    "Calculate the risk of ruin over a number of trading simulations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11a634e0",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "def calculate_risk_of_ruin(initial_capital, trades, win_prob, avg_win, avg_loss, simulations=100):\n",
    "    \"\"\"\n",
    "    Calculate the risk of ruin over a number of trading simulations.\n",
    "    \n",
    "    Parameters\n",
    "    ----------\n",
    "    initial_capital : float\n",
    "        Starting capital for the trading strategy\n",
    "    trades : int\n",
    "        Number of trades to simulate\n",
    "    win_prob : float\n",
    "        Probability of a winning trade\n",
    "    avg_win : float\n",
    "        Average amount won per winning trade\n",
    "    avg_loss : float\n",
    "        Average amount lost per losing trade\n",
    "    simulations : int, optional\n",
    "        Number of simulations to run (default is 100)\n",
    "    \n",
    "    Returns\n",
    "    -------\n",
    "    float\n",
    "        Proportion of simulations where the capital went to zero or below\n",
    "    \"\"\"\n",
    "\n",
    "    # Initialize ruin count\n",
    "    ruin_count = 0\n",
    "\n",
    "    # Run the specified number of simulations\n",
    "    for _ in range(simulations):\n",
    "        capital_history = simulate_trading_strategy(initial_capital, trades, win_prob, avg_win, avg_loss)\n",
    "        if min(capital_history) <= 0:\n",
    "            ruin_count += 1\n",
    "\n",
    "    return ruin_count / simulations"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "38b50779",
   "metadata": {},
   "source": [
    "Define initial parameters for the trading simulation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6b0a2e66",
   "metadata": {},
   "outputs": [],
   "source": [
    "initial_capital = 10000\n",
    "average_win = 110\n",
    "average_loss = 100\n",
    "trades = 1000"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "93284971",
   "metadata": {},
   "source": [
    "Calculate risk of ruin for varying win probabilities"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b492dda9",
   "metadata": {},
   "outputs": [],
   "source": [
    "risk_of_ruins = []\n",
    "steps = range(30, 60)\n",
    "for step in steps:\n",
    "    win_probability = step / 100\n",
    "    risk_of_ruin = calculate_risk_of_ruin(initial_capital, trades, win_probability, average_win, average_loss)\n",
    "    risk_of_ruins.append(risk_of_ruin)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d5657ff2",
   "metadata": {},
   "source": [
    "Plot the risk of ruin versus probability of a winning trade"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a649045d",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(10, 6))\n",
    "plt.plot(steps, risk_of_ruins, label='Risk of ruin')\n",
    "plt.xlabel('Probability of a winning trade')\n",
    "plt.ylabel('Risk of ruin')\n",
    "plt.title(\"Probability of ruin versus probability of a winning trade\")\n",
    "plt.grid(True)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b6ef45a0",
   "metadata": {},
   "source": [
    "<a href=\"https://pyquantnews.com/\">PyQuant News</a> is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to <a href=\"https://gettingstartedwithpythonforquantfinance.com/\">get started with Python for quant finance</a>. For educational purposes. Not investment advise. Use at your own risk."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_metadata_filter": "-all",
   "main_language": "python",
   "notebook_metadata_filter": "-all"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
