├── old_videos ├── 1.png ├── .gitignore ├── rag_diagram.png ├── trade_mamba_new.jpg ├── Add a heading (11).png ├── rag_example-Page-1.drawio (1).png ├── ML Trading Bot for Interactive Brokers in Python (1).zip ├── ML Trading Bot for Interactive Brokers in Python (2).png ├── wsgi_file ├── README.md ├── data_utils.py ├── MultiLegOptions.ipynb ├── conditional-orders.ipynb ├── BinomialTreeCRRVideo.ipynb ├── get_1min_data_fast.ipynb ├── BinomialTreeToBlackScholes-Video.ipynb ├── Multithreading tutorial.ipynb ├── Watch-List.ipynb └── hello_dash_actual.ipynb ├── LiveNVDA.ipynb ├── Alpaca ├── TradingStream2.ipynb └── TradingStream.ipynb └── Together_AI_Rag.ipynb /old_videos/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adidror005/youtube-videos/HEAD/old_videos/1.png -------------------------------------------------------------------------------- /old_videos/.gitignore: -------------------------------------------------------------------------------- 1 | /data/ADP_1_mins.csv 2 | /data/CNHI_1_mins.csv 3 | /data/CB_1_mins.csv 4 | -------------------------------------------------------------------------------- /old_videos/rag_diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adidror005/youtube-videos/HEAD/old_videos/rag_diagram.png -------------------------------------------------------------------------------- /old_videos/trade_mamba_new.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adidror005/youtube-videos/HEAD/old_videos/trade_mamba_new.jpg -------------------------------------------------------------------------------- /old_videos/Add a heading (11).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adidror005/youtube-videos/HEAD/old_videos/Add a heading (11).png -------------------------------------------------------------------------------- /old_videos/rag_example-Page-1.drawio (1).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adidror005/youtube-videos/HEAD/old_videos/rag_example-Page-1.drawio (1).png -------------------------------------------------------------------------------- /old_videos/ML Trading Bot for Interactive Brokers in Python (1).zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adidror005/youtube-videos/HEAD/old_videos/ML Trading Bot for Interactive Brokers in Python (1).zip -------------------------------------------------------------------------------- /old_videos/ML Trading Bot for Interactive Brokers in Python (2).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adidror005/youtube-videos/HEAD/old_videos/ML Trading Bot for Interactive Brokers in Python (2).png -------------------------------------------------------------------------------- /old_videos/wsgi_file: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | # add your project directory to the sys.path 4 | project_home = u'/home/trademamba/dash' 5 | if project_home not in sys.path: 6 | sys.path = [project_home] + sys.path 7 | 8 | 9 | from app import app 10 | application = app.server 11 | -------------------------------------------------------------------------------- /old_videos/README.md: -------------------------------------------------------------------------------- 1 | # Youtube Videos 2 | 3 | ## Interactive Brokers 4 | ### Tutorial part 1 5 | https://youtu.be/_AASJZyNcXQ 6 | 7 | IMAGE ALT TEXT HERE 8 | 9 | 10 | 11 | ### Bollinger Band Trading Example 12 | https://youtu.be/_AASJZyNcXQ 13 | [![IMAGE ALT TEXT HERE](https://img.youtube.com/vi/G2wD2scvT8w/0.jpg)](https://www.youtube.com/watch?v=G2wD2scvT8w) 14 | 15 | 16 | -------------------------------------------------------------------------------- /old_videos/data_utils.py: -------------------------------------------------------------------------------- 1 | def _make_df(bars): 2 | df = util.df(bars) 3 | df.set_index('date',inplace=True) 4 | df.index = df.index.tz_localize(None) 5 | return df 6 | import pandas as pd 7 | import datetime 8 | import pandas_market_calendars as mcal 9 | import os 10 | from ib_insync import * 11 | # Create a calendar 12 | nyse = mcal.get_calendar('NYSE') 13 | def get_historical_1m_data_fast(ib,symbol,start_date,end_date,what_to_show='TRADES',use_rth=False): 14 | messup_count=0 15 | df_list=[] 16 | start_date = datetime.datetime.strptime(start_date,'%Y%m%d').date() # .date() is important to get correct date! 17 | start_date.strftime('%Y-%m-%d') 18 | end_date = datetime.datetime.strptime(end_date,'%Y%m%d').date() 19 | end_date.strftime('%Y-%m-%d') 20 | dates = nyse.schedule(start_date=start_date, end_date=end_date) 21 | dates = [t.strftime('%Y%m%d') for t in mcal.date_range(dates, frequency='1D').tolist()] 22 | dates = [datetime.datetime.strptime(t,'%Y%m%d').date() for t in dates] 23 | contract = Stock(symbol=symbol,exchange='SMART',currency='USD') 24 | ib.qualifyContracts(contract) 25 | 26 | last_end_date = dates[-1]+datetime.timedelta(days=1) 27 | for end_date in dates[::-1]: 28 | if end_date>=last_end_date: continue 29 | if messup_count>=2: break 30 | try: 31 | print("Retrieving data for ",symbol," for ",end_date) 32 | bars=ib.reqHistoricalData(contract,endDateTime=end_date, 33 | barSizeSetting='1 min',whatToShow=what_to_show,useRTH=use_rth, 34 | durationStr='1 W') 35 | df=_make_df(bars) 36 | last_end_date=bars[0].date.date() 37 | df_list.append(df) 38 | except Exception as e: 39 | messup_count+=1 40 | print(e) 41 | print("No data for ",end_date) 42 | else: 43 | messup_count=0 44 | return pd.concat(df_list).sort_index() -------------------------------------------------------------------------------- /LiveNVDA.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "provenance": [], 7 | "authorship_tag": "ABX9TyNwdwiocn8Intj+Yht5O5qC", 8 | "include_colab_link": true 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "markdown", 21 | "metadata": { 22 | "id": "view-in-github", 23 | "colab_type": "text" 24 | }, 25 | "source": [ 26 | "\"Open" 27 | ] 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "source": [ 32 | "### Install Alpaca-PY" 33 | ], 34 | "metadata": { 35 | "id": "XfSk3xqFlfSs" 36 | } 37 | }, 38 | { 39 | "cell_type": "code", 40 | "execution_count": null, 41 | "metadata": { 42 | "colab": { 43 | "base_uri": "https://localhost:8080/" 44 | }, 45 | "id": "_jrK56j2lUS9", 46 | "outputId": "cd943fa2-eb48-4e8a-f292-5da7a5fe5fea" 47 | }, 48 | "outputs": [ 49 | { 50 | "output_type": "stream", 51 | "name": "stdout", 52 | "text": [ 53 | "Collecting alpaca-py\n", 54 | " Downloading alpaca_py-0.40.1-py3-none-any.whl.metadata (13 kB)\n", 55 | "Requirement already satisfied: msgpack<2.0.0,>=1.0.3 in /usr/local/lib/python3.11/dist-packages (from alpaca-py) (1.1.0)\n", 56 | "Requirement already satisfied: pandas>=1.5.3 in /usr/local/lib/python3.11/dist-packages (from alpaca-py) (2.2.2)\n", 57 | "Requirement already satisfied: pydantic<3.0.0,>=2.0.3 in /usr/local/lib/python3.11/dist-packages (from alpaca-py) (2.11.4)\n", 58 | "Requirement already satisfied: requests<3.0.0,>=2.30.0 in /usr/local/lib/python3.11/dist-packages (from alpaca-py) (2.32.3)\n", 59 | "Collecting sseclient-py<2.0.0,>=1.7.2 (from alpaca-py)\n", 60 | " Downloading sseclient_py-1.8.0-py2.py3-none-any.whl.metadata (2.0 kB)\n", 61 | "Requirement already satisfied: websockets>=10.4 in /usr/local/lib/python3.11/dist-packages (from alpaca-py) (15.0.1)\n", 62 | "Requirement already satisfied: numpy>=1.23.2 in /usr/local/lib/python3.11/dist-packages (from pandas>=1.5.3->alpaca-py) (2.0.2)\n", 63 | "Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.11/dist-packages (from pandas>=1.5.3->alpaca-py) (2.9.0.post0)\n", 64 | "Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.11/dist-packages (from pandas>=1.5.3->alpaca-py) (2025.2)\n", 65 | "Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.11/dist-packages (from pandas>=1.5.3->alpaca-py) (2025.2)\n", 66 | "Requirement already satisfied: annotated-types>=0.6.0 in /usr/local/lib/python3.11/dist-packages (from pydantic<3.0.0,>=2.0.3->alpaca-py) (0.7.0)\n", 67 | "Requirement already satisfied: pydantic-core==2.33.2 in /usr/local/lib/python3.11/dist-packages (from pydantic<3.0.0,>=2.0.3->alpaca-py) (2.33.2)\n", 68 | "Requirement already satisfied: typing-extensions>=4.12.2 in /usr/local/lib/python3.11/dist-packages (from pydantic<3.0.0,>=2.0.3->alpaca-py) (4.13.2)\n", 69 | "Requirement already satisfied: typing-inspection>=0.4.0 in /usr/local/lib/python3.11/dist-packages (from pydantic<3.0.0,>=2.0.3->alpaca-py) (0.4.1)\n", 70 | "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.11/dist-packages (from requests<3.0.0,>=2.30.0->alpaca-py) (3.4.2)\n", 71 | "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.11/dist-packages (from requests<3.0.0,>=2.30.0->alpaca-py) (3.10)\n", 72 | "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.11/dist-packages (from requests<3.0.0,>=2.30.0->alpaca-py) (2.4.0)\n", 73 | "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.11/dist-packages (from requests<3.0.0,>=2.30.0->alpaca-py) (2025.4.26)\n", 74 | "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.11/dist-packages (from python-dateutil>=2.8.2->pandas>=1.5.3->alpaca-py) (1.17.0)\n", 75 | "Downloading alpaca_py-0.40.1-py3-none-any.whl (121 kB)\n", 76 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m121.7/121.7 kB\u001b[0m \u001b[31m1.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", 77 | "\u001b[?25hDownloading sseclient_py-1.8.0-py2.py3-none-any.whl (8.8 kB)\n", 78 | "Installing collected packages: sseclient-py, alpaca-py\n", 79 | "Successfully installed alpaca-py-0.40.1 sseclient-py-1.8.0\n" 80 | ] 81 | } 82 | ], 83 | "source": [ 84 | "!pip install alpaca-py" 85 | ] 86 | }, 87 | { 88 | "cell_type": "markdown", 89 | "source": [ 90 | "### Grab API Key + Secret" 91 | ], 92 | "metadata": { 93 | "id": "VC1LKjD0lcqZ" 94 | } 95 | }, 96 | { 97 | "cell_type": "code", 98 | "source": [ 99 | "from re import A\n", 100 | "from google.colab import userdata\n", 101 | "ALPACA_API_KEY = userdata.get('ALPACA_API_KEY')\n", 102 | "ALPACA_SECRET_KEY = userdata.get('ALPACA_API_SECRET')" 103 | ], 104 | "metadata": { 105 | "id": "k3_3HG-sljnl" 106 | }, 107 | "execution_count": null, 108 | "outputs": [] 109 | }, 110 | { 111 | "cell_type": "markdown", 112 | "source": [ 113 | "### Define TradingSteam" 114 | ], 115 | "metadata": { 116 | "id": "bJ9bsconls3U" 117 | } 118 | }, 119 | { 120 | "cell_type": "code", 121 | "source": [ 122 | "from alpaca.data.live import StockDataStream\n", 123 | "from alpaca.data.enums import DataFeed\n", 124 | "stock_data_stream = StockDataStream(ALPACA_API_KEY,ALPACA_SECRET_KEY,feed=DataFeed.SIP)" 125 | ], 126 | "metadata": { 127 | "id": "oR8f4nk8l8H-" 128 | }, 129 | "execution_count": null, 130 | "outputs": [] 131 | }, 132 | { 133 | "cell_type": "markdown", 134 | "source": [ 135 | "### Define Couroutine" 136 | ], 137 | "metadata": { 138 | "id": "azTbPm-fmIrD" 139 | } 140 | }, 141 | { 142 | "cell_type": "code", 143 | "source": [ 144 | "async def on_trade(trade):\n", 145 | " print(trade)" 146 | ], 147 | "metadata": { 148 | "id": "q_mo7wcKmQY_" 149 | }, 150 | "execution_count": null, 151 | "outputs": [] 152 | }, 153 | { 154 | "cell_type": "markdown", 155 | "source": [ 156 | "### Subscribe to Symbols" 157 | ], 158 | "metadata": { 159 | "id": "olhqMbUhmTKL" 160 | } 161 | }, 162 | { 163 | "cell_type": "code", 164 | "source": [ 165 | "stock_data_stream.subscribe_trades(on_trade,'AMD')" 166 | ], 167 | "metadata": { 168 | "id": "RzxWtZ0SmVAg" 169 | }, 170 | "execution_count": null, 171 | "outputs": [] 172 | }, 173 | { 174 | "cell_type": "markdown", 175 | "source": [ 176 | "### Since Using Jupyter need nest_asnycio" 177 | ], 178 | "metadata": { 179 | "id": "vd5ZJ5BfmmBw" 180 | } 181 | }, 182 | { 183 | "cell_type": "code", 184 | "source": [ 185 | "import nest_asyncio\n", 186 | "nest_asyncio.apply()" 187 | ], 188 | "metadata": { 189 | "id": "HmBjjyTDml6A" 190 | }, 191 | "execution_count": 9, 192 | "outputs": [] 193 | }, 194 | { 195 | "cell_type": "markdown", 196 | "source": [ 197 | "### Run the stream" 198 | ], 199 | "metadata": { 200 | "id": "-8ARfcWgmZu4" 201 | } 202 | }, 203 | { 204 | "cell_type": "code", 205 | "source": [ 206 | "stock_data_stream.run()" 207 | ], 208 | "metadata": { 209 | "id": "QZaoNbYFmbJO" 210 | }, 211 | "execution_count": null, 212 | "outputs": [] 213 | } 214 | ] 215 | } -------------------------------------------------------------------------------- /old_videos/MultiLegOptions.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "provenance": [], 7 | "authorship_tag": "ABX9TyOGN1p0mRx9fNAPUKnckoN7", 8 | "include_colab_link": true 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "markdown", 21 | "metadata": { 22 | "id": "view-in-github", 23 | "colab_type": "text" 24 | }, 25 | "source": [ 26 | "\"Open" 27 | ] 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "source": [ 32 | "# Setup\n", 33 | "\n", 34 | "\n", 35 | "### Install Alpaca-Py SDK" 36 | ], 37 | "metadata": { 38 | "id": "1ttkGrIf7jFV" 39 | } 40 | }, 41 | { 42 | "cell_type": "code", 43 | "execution_count": 20, 44 | "metadata": { 45 | "id": "o5D5DZyJmI3g" 46 | }, 47 | "outputs": [], 48 | "source": [] 49 | }, 50 | { 51 | "cell_type": "markdown", 52 | "source": [ 53 | "### Grab API Key + API Secret" 54 | ], 55 | "metadata": { 56 | "id": "IRC-UoT-7qPk" 57 | } 58 | }, 59 | { 60 | "cell_type": "code", 61 | "source": [], 62 | "metadata": { 63 | "id": "07CKn52Q7qEv" 64 | }, 65 | "execution_count": null, 66 | "outputs": [] 67 | }, 68 | { 69 | "cell_type": "markdown", 70 | "source": [ 71 | "### Initialize Trading Client" 72 | ], 73 | "metadata": { 74 | "id": "j99IJqoB7tM2" 75 | } 76 | }, 77 | { 78 | "cell_type": "code", 79 | "source": [], 80 | "metadata": { 81 | "id": "irjR4eh27wi5" 82 | }, 83 | "execution_count": null, 84 | "outputs": [] 85 | }, 86 | { 87 | "cell_type": "markdown", 88 | "source": [ 89 | "### Look at Open Orders" 90 | ], 91 | "metadata": { 92 | "id": "lfu4mb92mV8G" 93 | } 94 | }, 95 | { 96 | "cell_type": "code", 97 | "source": [], 98 | "metadata": { 99 | "id": "DlftJqFKmX7U" 100 | }, 101 | "execution_count": 20, 102 | "outputs": [] 103 | }, 104 | { 105 | "cell_type": "markdown", 106 | "source": [ 107 | "# Utility Function to Get Option Symbols" 108 | ], 109 | "metadata": { 110 | "id": "KsOd91Ch4gl2" 111 | } 112 | }, 113 | { 114 | "cell_type": "code", 115 | "source": [ 116 | "from alpaca.trading.requests import GetOptionContractsRequest\n", 117 | "from alpaca.trading.enums import ContractType\n", 118 | "def get_option_symbol(symbol, expiry, strike, option_type):\n", 119 | " option_contracts = trading_client.get_option_contracts(\n", 120 | " GetOptionContractsRequest(\n", 121 | " underlying_symbols=[symbol],\n", 122 | " expiration_date=expiry,\n", 123 | " strike_price_gte=str(strike),\n", 124 | " strike_price_lte=str(strike),\n", 125 | " type=option_type\n", 126 | " )\n", 127 | " ).option_contracts\n", 128 | "\n", 129 | " if len(option_contracts) != 1:\n", 130 | " raise ValueError(\"Did not find exactly 1 unique contract.\")\n", 131 | " return option_contracts[0].symbol\n", 132 | "get_option_symbol('AMD','2025-05-30',100,ContractType.CALL),get_option_symbol('NVDA','2025-05-23',120,ContractType.CALL)" 133 | ], 134 | "metadata": { 135 | "colab": { 136 | "base_uri": "https://localhost:8080/" 137 | }, 138 | "id": "b37TUz5upGq3", 139 | "outputId": "a9166f45-2bb0-426e-cbc7-08e4f3b4ea44" 140 | }, 141 | "execution_count": 13, 142 | "outputs": [ 143 | { 144 | "output_type": "execute_result", 145 | "data": { 146 | "text/plain": [ 147 | "('AMD250530C00100000', 'NVDA250523C00120000')" 148 | ] 149 | }, 150 | "metadata": {}, 151 | "execution_count": 13 152 | } 153 | ] 154 | }, 155 | { 156 | "cell_type": "markdown", 157 | "source": [ 158 | "### Define The Legs of the Contract (i.e. for Diagonal Call Spread)\n", 159 | "* symbol\n", 160 | "* side\n", 161 | "* ratio_qty\n" 162 | ], 163 | "metadata": { 164 | "id": "66FnxP6zmpFp" 165 | } 166 | }, 167 | { 168 | "cell_type": "code", 169 | "source": [ 170 | "from alpaca.trading.requests import OptionLegRequest\n", 171 | "from alpaca.trading.enums import OrderSide\n" 172 | ], 173 | "metadata": { 174 | "id": "c8vAKd6dokxt" 175 | }, 176 | "execution_count": 21, 177 | "outputs": [] 178 | }, 179 | { 180 | "cell_type": "markdown", 181 | "source": [ 182 | "### Define Order Request and Submit Order\n", 183 | "* order_class = OrderClass.MLEG\n", 184 | "* legs = list[OptionLegRequest]\n", 185 | "* Note: what is cool is we can define our own id via the *client_id* so we can manage IDs ourselves.\n" 186 | ], 187 | "metadata": { 188 | "id": "7dspLo8k5zUx" 189 | } 190 | }, 191 | { 192 | "cell_type": "code", 193 | "source": [ 194 | "from alpaca.trading.requests import LimitOrderRequest, MarketOrderRequest\n", 195 | "from alpaca.trading.enums import OrderSide, OrderClass, TimeInForce\n" 196 | ], 197 | "metadata": { 198 | "id": "fcsdaffpmtXD" 199 | }, 200 | "execution_count": 22, 201 | "outputs": [] 202 | }, 203 | { 204 | "cell_type": "markdown", 205 | "source": [ 206 | "### Get Order By Client Id" 207 | ], 208 | "metadata": { 209 | "id": "h8tofRBt6U-U" 210 | } 211 | }, 212 | { 213 | "cell_type": "code", 214 | "source": [], 215 | "metadata": { 216 | "id": "Mo0JMSsb6U3C" 217 | }, 218 | "execution_count": null, 219 | "outputs": [] 220 | }, 221 | { 222 | "cell_type": "markdown", 223 | "source": [ 224 | "### Cancel Orders if Necessary" 225 | ], 226 | "metadata": { 227 | "id": "FmWxe-s86Iyo" 228 | } 229 | }, 230 | { 231 | "cell_type": "code", 232 | "source": [], 233 | "metadata": { 234 | "id": "wBrhQZ1QqHMJ" 235 | }, 236 | "execution_count": 22, 237 | "outputs": [] 238 | }, 239 | { 240 | "cell_type": "markdown", 241 | "source": [ 242 | "### Replace Order By ID\n", 243 | "* Can only replace limit_price, qty--- Not individual symbols or ratios." 244 | ], 245 | "metadata": { 246 | "id": "EGlQiG2yrXxe" 247 | } 248 | }, 249 | { 250 | "cell_type": "code", 251 | "source": [ 252 | "from alpaca.trading.requests import ReplaceOrderRequest\n", 253 | "" 254 | ], 255 | "metadata": { 256 | "id": "dfVUbWo1yxsV" 257 | }, 258 | "execution_count": 23, 259 | "outputs": [] 260 | }, 261 | { 262 | "cell_type": "markdown", 263 | "source": [ 264 | "### Good References" 265 | ], 266 | "metadata": { 267 | "id": "M_ytVk2QzQ6s" 268 | } 269 | }, 270 | { 271 | "cell_type": "markdown", 272 | "source": [ 273 | "* Alpaca-Py Github: https://github.com/alpacahq/alpaca-py.git\n", 274 | "* Multi-leg Options: https://github.com/alpacahq/alpaca-py/tree/master/examples/options\n", 275 | "* My YouTube Channel: https://www.youtube.com/channel/UCZHN0IOGmmvY6JtquMoEn9w\n", 276 | " - Checkout Alpaca Playlist\n", 277 | " - Ultimate Getting Started with Alpaca Tutorial" 278 | ], 279 | "metadata": { 280 | "id": "0nkFkaMi90sG" 281 | } 282 | }, 283 | { 284 | "cell_type": "code", 285 | "source": [], 286 | "metadata": { 287 | "id": "nPSkb0hn-Gf6" 288 | }, 289 | "execution_count": null, 290 | "outputs": [] 291 | } 292 | ] 293 | } -------------------------------------------------------------------------------- /old_videos/conditional-orders.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "id": "f8e8337c", 7 | "metadata": {}, 8 | "outputs": [ 9 | { 10 | "data": { 11 | "text/plain": [ 12 | "" 13 | ] 14 | }, 15 | "execution_count": 1, 16 | "metadata": {}, 17 | "output_type": "execute_result" 18 | } 19 | ], 20 | "source": [ 21 | "from ib_insync import *\n", 22 | "ib = IB()\n", 23 | "util.startLoop()\n", 24 | "ib.connect(port=4004,clientId=0)" 25 | ] 26 | }, 27 | { 28 | "cell_type": "markdown", 29 | "id": "489309b4", 30 | "metadata": {}, 31 | "source": [ 32 | "### Time based condition" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": 123, 38 | "id": "a99e1b74", 39 | "metadata": {}, 40 | "outputs": [ 41 | { 42 | "data": { 43 | "text/plain": [ 44 | "OrderStatus(orderId=3932, status='PreSubmitted', filled=0.0, remaining=1.0, avgFillPrice=0.0, permId=1077044632, parentId=0, lastFillPrice=0.0, clientId=0, whyHeld='', mktCapPrice=0.0)" 45 | ] 46 | }, 47 | "execution_count": 123, 48 | "metadata": {}, 49 | "output_type": "execute_result" 50 | } 51 | ], 52 | "source": [ 53 | "conditional_order = MarketOrder(action='BUY',totalQuantity=1)\n", 54 | "timeCondition = TimeCondition()\n", 55 | "timeCondition.time = \"20240109 15:10:00\" # Format: YYYYMMDD HH:MM:SS\n", 56 | "timeCondition.conjunction='a'\n", 57 | "timeCondition.isMore=True\n", 58 | "conditional_order.conditions.append(timeCondition)\n", 59 | "nvda = Stock('NVDA', 'SMART', 'USD')\n", 60 | "ib.qualifyContracts(nvda)\n", 61 | "priceCondition=PriceCondition(conId=nvda.conId, conjunction='a',exch=\"SMART\", isMore=True, price=537)\n", 62 | "conditional_order.conditions.append(priceCondition)\n", 63 | "pctChangeCondition = PercentChangeCondition(\n", 64 | " changePercent=4.0, # 2 percent change\n", 65 | " conId=nvda.conId, \n", 66 | " exch='SMART'\n", 67 | ")\n", 68 | "conditional_order.conditions.append(pctChangeCondition)\n", 69 | "\n", 70 | "contract=Stock(\"TSLA\",exchange='SMART',currency='USD')\n", 71 | "ib.qualifyContracts(contract)\n", 72 | "trade=ib.placeOrder(contract,conditional_order)\n", 73 | "ib.sleep(3)\n", 74 | "trade.orderStatus" 75 | ] 76 | }, 77 | { 78 | "cell_type": "code", 79 | "execution_count": 124, 80 | "id": "b4d197c8", 81 | "metadata": {}, 82 | "outputs": [ 83 | { 84 | "data": { 85 | "text/plain": [ 86 | "datetime.datetime(2024, 1, 9, 15, 12, 0, 110656)" 87 | ] 88 | }, 89 | "execution_count": 124, 90 | "metadata": {}, 91 | "output_type": "execute_result" 92 | } 93 | ], 94 | "source": [ 95 | "import datetime\n", 96 | "datetime.datetime.now()" 97 | ] 98 | }, 99 | { 100 | "cell_type": "code", 101 | "execution_count": 127, 102 | "id": "7b46a3c9", 103 | "metadata": {}, 104 | "outputs": [ 105 | { 106 | "data": { 107 | "text/plain": [ 108 | "OrderStatus(orderId=3932, status='PreSubmitted', filled=0.0, remaining=1.0, avgFillPrice=0.0, permId=1077044632, parentId=0, lastFillPrice=0.0, clientId=0, whyHeld='', mktCapPrice=0.0)" 109 | ] 110 | }, 111 | "execution_count": 127, 112 | "metadata": {}, 113 | "output_type": "execute_result" 114 | } 115 | ], 116 | "source": [ 117 | "trade.orderStatus" 118 | ] 119 | }, 120 | { 121 | "cell_type": "code", 122 | "execution_count": null, 123 | "id": "7e6e6b8b", 124 | "metadata": {}, 125 | "outputs": [], 126 | "source": [] 127 | }, 128 | { 129 | "cell_type": "code", 130 | "execution_count": 53, 131 | "id": "9f87b9cf", 132 | "metadata": {}, 133 | "outputs": [ 134 | { 135 | "data": { 136 | "text/plain": [ 137 | "OrderStatus(orderId=3900, status='PreSubmitted', filled=0.0, remaining=1.0, avgFillPrice=0.0, permId=1077044622, parentId=0, lastFillPrice=0.0, clientId=0, whyHeld='', mktCapPrice=0.0)" 138 | ] 139 | }, 140 | "execution_count": 53, 141 | "metadata": {}, 142 | "output_type": "execute_result" 143 | } 144 | ], 145 | "source": [ 146 | "trade=ib.placeOrder(contract,conditional_order)\n", 147 | "ib.sleep(3)\n", 148 | "trade.orderStatus" 149 | ] 150 | }, 151 | { 152 | "cell_type": "code", 153 | "execution_count": 54, 154 | "id": "51ecb4f2", 155 | "metadata": {}, 156 | "outputs": [ 157 | { 158 | "data": { 159 | "text/plain": [ 160 | "MarketOrder(orderId=3900, permId=1077044622, action='BUY', totalQuantity=1.0, lmtPrice=0.0, auxPrice=0.0, conditions=[TimeCondition(condType=3, conjunction='a', isMore=True, time='20240109 14:53:00'), PriceCondition(condType=1, conjunction='a', isMore=True, price=550, conId=4815747, exch='SMART', triggerMethod=0)])" 161 | ] 162 | }, 163 | "execution_count": 54, 164 | "metadata": {}, 165 | "output_type": "execute_result" 166 | } 167 | ], 168 | "source": [ 169 | "trade.order\n" 170 | ] 171 | }, 172 | { 173 | "cell_type": "code", 174 | "execution_count": 143, 175 | "id": "ab0a4b28", 176 | "metadata": {}, 177 | "outputs": [], 178 | "source": [ 179 | "]" 180 | ] 181 | }, 182 | { 183 | "cell_type": "code", 184 | "execution_count": 58, 185 | "id": "90b58925", 186 | "metadata": {}, 187 | "outputs": [ 188 | { 189 | "data": { 190 | "text/plain": [ 191 | "OrderStatus(orderId=3900, status='Filled', filled=1.0, remaining=0.0, avgFillPrice=234.08, permId=1077044622, parentId=0, lastFillPrice=234.08, clientId=0, whyHeld='', mktCapPrice=0.0)" 192 | ] 193 | }, 194 | "execution_count": 58, 195 | "metadata": {}, 196 | "output_type": "execute_result" 197 | } 198 | ], 199 | "source": [ 200 | "trade.orderStatus" 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "execution_count": 145, 206 | "id": "a19fbb5c", 207 | "metadata": {}, 208 | "outputs": [ 209 | { 210 | "data": { 211 | "text/plain": [ 212 | ">" 213 | ] 214 | }, 215 | "execution_count": 145, 216 | "metadata": {}, 217 | "output_type": "execute_result" 218 | } 219 | ], 220 | "source": [ 221 | "ib.placeOrder" 222 | ] 223 | }, 224 | { 225 | "cell_type": "code", 226 | "execution_count": 24, 227 | "id": "c4eaa7df", 228 | "metadata": {}, 229 | "outputs": [ 230 | { 231 | "data": { 232 | "text/plain": [ 233 | "MarketOrder(orderId=322, permId=951219239, action='BUY', totalQuantity=1.0, lmtPrice=0.0, auxPrice=0.0, conditions=[TimeCondition(condType=3, conjunction='a', isMore=True, time='20240109 13:12:00')])" 234 | ] 235 | }, 236 | "execution_count": 24, 237 | "metadata": {}, 238 | "output_type": "execute_result" 239 | } 240 | ], 241 | "source": [ 242 | "trade.order" 243 | ] 244 | }, 245 | { 246 | "cell_type": "code", 247 | "execution_count": 166, 248 | "id": "1fd91413", 249 | "metadata": {}, 250 | "outputs": [ 251 | { 252 | "name": "stdout", 253 | "output_type": "stream", 254 | "text": [ 255 | "Time zone: Eastern Standard Time\n" 256 | ] 257 | }, 258 | { 259 | "name": "stderr", 260 | "output_type": "stream", 261 | "text": [ 262 | "Peer closed connection.\n" 263 | ] 264 | } 265 | ], 266 | "source": [ 267 | "import datetime\n", 268 | "\n", 269 | "# Get the current time and date\n", 270 | "current_time = datetime.datetime.now()\n", 271 | "\n", 272 | "# Get the time zone information\n", 273 | "time_zone = current_time.astimezone().tzinfo\n", 274 | "\n", 275 | "# Print the time zone information\n", 276 | "print(\"Time zone:\", time_zone)\n" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "execution_count": 6, 282 | "id": "12369b71", 283 | "metadata": {}, 284 | "outputs": [], 285 | "source": [ 286 | "ticker = ib.reqMktData(contract,\"\",False,False)\n" 287 | ] 288 | }, 289 | { 290 | "cell_type": "code", 291 | "execution_count": 7, 292 | "id": "31b39455", 293 | "metadata": {}, 294 | "outputs": [], 295 | "source": [ 296 | "import numpy as np\n", 297 | "def onTickerUpdate(ticker):\n", 298 | " global trade\n", 299 | " trade.order.lmtPrice=np.round(ticker.midpoint(),2) \n", 300 | " trade=ib.placeOrder(contract,trade.order)" 301 | ] 302 | }, 303 | { 304 | "cell_type": "code", 305 | "execution_count": 8, 306 | "id": "15e0a924", 307 | "metadata": {}, 308 | "outputs": [], 309 | "source": [ 310 | "ticker.updateEvent+=onTickerUpdate" 311 | ] 312 | }, 313 | { 314 | "cell_type": "code", 315 | "execution_count": 18, 316 | "id": "b464488c", 317 | "metadata": {}, 318 | "outputs": [ 319 | { 320 | "data": { 321 | "text/plain": [ 322 | "Order(orderId=3855, permId=1899152479, action='BUY', totalQuantity=1.0, orderType='MKT', lmtPrice=234.66, auxPrice=0.0, outsideRth=True, conditions=[TimeCondition(condType=3, conjunction='a', isMore=True, time='20240109 12:59:00')])" 323 | ] 324 | }, 325 | "execution_count": 18, 326 | "metadata": {}, 327 | "output_type": "execute_result" 328 | } 329 | ], 330 | "source": [ 331 | "\n", 332 | "trade.orer" 333 | ] 334 | }, 335 | { 336 | "cell_type": "code", 337 | "execution_count": 17, 338 | "id": "c3cc7de0", 339 | "metadata": {}, 340 | "outputs": [ 341 | { 342 | "data": { 343 | "text/plain": [ 344 | "'PreSubmitted'" 345 | ] 346 | }, 347 | "execution_count": 17, 348 | "metadata": {}, 349 | "output_type": "execute_result" 350 | } 351 | ], 352 | "source": [ 353 | "trade.orderStatus.status" 354 | ] 355 | }, 356 | { 357 | "cell_type": "code", 358 | "execution_count": null, 359 | "id": "84ed84b2", 360 | "metadata": {}, 361 | "outputs": [], 362 | "source": [] 363 | }, 364 | { 365 | "cell_type": "code", 366 | "execution_count": null, 367 | "id": "3c89b64b", 368 | "metadata": {}, 369 | "outputs": [], 370 | "source": [] 371 | } 372 | ], 373 | "metadata": { 374 | "kernelspec": { 375 | "display_name": "py310", 376 | "language": "python", 377 | "name": "py310" 378 | }, 379 | "language_info": { 380 | "codemirror_mode": { 381 | "name": "ipython", 382 | "version": 3 383 | }, 384 | "file_extension": ".py", 385 | "mimetype": "text/x-python", 386 | "name": "python", 387 | "nbconvert_exporter": "python", 388 | "pygments_lexer": "ipython3", 389 | "version": "3.10.13" 390 | } 391 | }, 392 | "nbformat": 4, 393 | "nbformat_minor": 5 394 | } 395 | -------------------------------------------------------------------------------- /old_videos/BinomialTreeCRRVideo.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 49, 6 | "id": "c4ac1925", 7 | "metadata": {}, 8 | "outputs": [ 9 | { 10 | "data": { 11 | "text/html": [ 12 | "\n", 13 | "\n" 16 | ], 17 | "text/plain": [ 18 | "" 19 | ] 20 | }, 21 | "execution_count": 49, 22 | "metadata": {}, 23 | "output_type": "execute_result" 24 | } 25 | ], 26 | "source": [ 27 | "from IPython.core.display import HTML\n", 28 | "HTML(\"\"\"\n", 29 | "\n", 32 | "\"\"\")" 33 | ] 34 | }, 35 | { 36 | "cell_type": "markdown", 37 | "id": "c4f88437", 38 | "metadata": {}, 39 | "source": [ 40 | "#### Imports" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": 50, 46 | "id": "138da028", 47 | "metadata": {}, 48 | "outputs": [], 49 | "source": [ 50 | "import numpy as np" 51 | ] 52 | }, 53 | { 54 | "cell_type": "markdown", 55 | "id": "03e5928f", 56 | "metadata": {}, 57 | "source": [ 58 | "### Inputs" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": 51, 64 | "id": "194ed07a", 65 | "metadata": {}, 66 | "outputs": [], 67 | "source": [ 68 | "s = 100\n", 69 | "K = 105\n", 70 | "sigma = 0.2\n", 71 | "r = 0.05\n", 72 | "T = 1\n", 73 | "n = 100\n", 74 | "kind = 'call'\n", 75 | "style = 'European'" 76 | ] 77 | }, 78 | { 79 | "cell_type": "markdown", 80 | "id": "13d2d092", 81 | "metadata": {}, 82 | "source": [ 83 | "### Binomial Tree Model" 84 | ] 85 | }, 86 | { 87 | "cell_type": "code", 88 | "execution_count": 52, 89 | "id": "0e097765", 90 | "metadata": {}, 91 | "outputs": [], 92 | "source": [ 93 | "def intrinsic_value(S,K,kind):\n", 94 | " assert kind in ['call','put'],\"Must be call or put\"\n", 95 | " return max(S-K,0) if kind == 'call' else max(K-S,0)\n", 96 | " \n", 97 | "def binomial_tree_price(S,K,sigma,r,T,n,kind='call',style='European'):\n", 98 | " assert kind in ['call','put'],\"Must be call or put\"\n", 99 | " assert style in ['European','American'],\"Must be European or American\"\n", 100 | " \n", 101 | " h = T/n\n", 102 | " u = np.exp(sigma*np.sqrt(h))\n", 103 | " d = 1/u\n", 104 | " p_rn = (np.exp(r*h)-d)/(u-d)\n", 105 | " discount_factor = np.exp(-r*h)\n", 106 | " \n", 107 | " V = np.zeros(shape=(n+1,n+1))\n", 108 | " \n", 109 | " # At expiry (j=n) we know the option values\n", 110 | " for i in range(n+1):\n", 111 | " V[i,n]=intrinsic_value(S*u**i*d**(n-i),K,kind)\n", 112 | " # Go backwords in time\n", 113 | " for j in range(n-1,-1,-1):\n", 114 | " for i in range(j+1):\n", 115 | " continuation_value=discount_factor*(p_rn*V[i+1,j+1]+(1-p_rn)*V[i,j+1])\n", 116 | " if style == 'American':\n", 117 | " early_exercise_value = intrinsic_value(S*u**i*d**(j-i),K,kind=kind)\n", 118 | " V[i,j]=max(early_exercise_value,continuation_value)\n", 119 | " else:\n", 120 | " V[i,j]=continuation_value\n", 121 | " return V[0,0]\n", 122 | " \n", 123 | " \n", 124 | " \n", 125 | " \n", 126 | " \n", 127 | " " 128 | ] 129 | }, 130 | { 131 | "cell_type": "code", 132 | "execution_count": 53, 133 | "id": "5b8417de", 134 | "metadata": {}, 135 | "outputs": [ 136 | { 137 | "data": { 138 | "text/plain": [ 139 | "8.026229025058432" 140 | ] 141 | }, 142 | "execution_count": 53, 143 | "metadata": {}, 144 | "output_type": "execute_result" 145 | } 146 | ], 147 | "source": [ 148 | "binomial_tree_price(S,K,sigma,r,T,n,kind='call',style='European')" 149 | ] 150 | }, 151 | { 152 | "cell_type": "code", 153 | "execution_count": 54, 154 | "id": "3ac3c9f6", 155 | "metadata": {}, 156 | "outputs": [ 157 | { 158 | "data": { 159 | "text/plain": [ 160 | "8.026229025058432" 161 | ] 162 | }, 163 | "execution_count": 54, 164 | "metadata": {}, 165 | "output_type": "execute_result" 166 | } 167 | ], 168 | "source": [ 169 | "binomial_tree_price(S,K,sigma,r,T,n,kind='call',style='American')" 170 | ] 171 | }, 172 | { 173 | "cell_type": "code", 174 | "execution_count": 55, 175 | "id": "68288d4a", 176 | "metadata": {}, 177 | "outputs": [ 178 | { 179 | "data": { 180 | "text/plain": [ 181 | "8.747558705041387" 182 | ] 183 | }, 184 | "execution_count": 55, 185 | "metadata": {}, 186 | "output_type": "execute_result" 187 | } 188 | ], 189 | "source": [ 190 | "binomial_tree_price(S,K,sigma,r,T,n,kind='put',style='American')" 191 | ] 192 | }, 193 | { 194 | "cell_type": "code", 195 | "execution_count": 56, 196 | "id": "cddaaf6e", 197 | "metadata": {}, 198 | "outputs": [ 199 | { 200 | "data": { 201 | "text/plain": [ 202 | "7.90531859763425" 203 | ] 204 | }, 205 | "execution_count": 56, 206 | "metadata": {}, 207 | "output_type": "execute_result" 208 | } 209 | ], 210 | "source": [ 211 | "binomial_tree_price(S,K,sigma,r,T,n,kind='put',style='European')" 212 | ] 213 | }, 214 | { 215 | "cell_type": "markdown", 216 | "id": "6c871f40", 217 | "metadata": {}, 218 | "source": [ 219 | "## Black Scholes Formula\n", 220 | "\n", 221 | "**Black-Scholes Formula**\n", 222 | "\n", 223 | "The Black-Scholes formula is a cornerstone in options pricing, providing a theoretical value for European-style options. It relies on several key assumptions about market behavior and the underlying asset.\n", 224 | "\n", 225 | "**Mathematical Representation**\n", 226 | "\n", 227 | "$$\n", 228 | "C = S_0 N(d_1) - K e^{-rT} N(d_2)\n", 229 | "$$\n", 230 | "\n", 231 | "$$\n", 232 | "P = K e^{-rT} N(-d_2) - S_0 N(-d_1)\n", 233 | "$$\n", 234 | "\n", 235 | "where:\n", 236 | "\n", 237 | "* $C$: Call option price\n", 238 | "* $P$: Put option price\n", 239 | "* $S_0$: Current price of the underlying asset\n", 240 | "* $K$: Strike price of the option\n", 241 | "* $r$: Risk-free interest rate\n", 242 | "* $T$: Time to expiration (in years)\n", 243 | "* $N(x)$: Cumulative standard normal distribution function\n", 244 | "* $d_1 = \\frac{\\ln(\\frac{S_0}{K}) + (r + \\frac{\\sigma^2}{2})T}{\\sigma \\sqrt{T}}$\n", 245 | "* $d_2 = d_1 - \\sigma \\sqrt{T}$\n", 246 | "* $\\sigma$: Volatility of the underlying asset's returns\n", 247 | "\n", 248 | "**Interpretation**\n", 249 | "\n", 250 | "* The formula calculates the fair price of a call or put option based on the interplay of factors like the current stock price, strike price, time to expiration, risk-free rate, and volatility. \n", 251 | "* $N(d_1)$ and $N(d_2)$ represent the probabilities that the option will expire in-the-money under the risk-neutral measure.\n", 252 | "\n", 253 | "**Assumptions**\n", 254 | "\n", 255 | "* The underlying asset follows a geometric Brownian motion (constant volatility).\n", 256 | "* No dividends are paid on the underlying asset during the option's life.\n", 257 | "* No transaction costs or taxes.\n", 258 | "* Markets are frictionless (no arbitrage opportunities).\n", 259 | "* The risk-free interest rate is constant.\n", 260 | "\n", 261 | "**Caveats**\n", 262 | "\n", 263 | "While widely used, the Black-Scholes model has limitations. Real-world markets often exhibit features that violate its assumptions, such as jumps in prices or changing volatility. Therefore, it's crucial to understand its limitations and consider more sophisticated models when dealing with complex market dynamics.\n", 264 | "\n", 265 | "Let me know if you'd like to delve deeper into any specific aspect or explore extensions to the Black-Scholes model! \n", 266 | " " 267 | ] 268 | }, 269 | { 270 | "cell_type": "code", 271 | "execution_count": 72, 272 | "id": "69a5abfb", 273 | "metadata": {}, 274 | "outputs": [], 275 | "source": [ 276 | "from scipy.stats import norm \n", 277 | "N = norm.cdf\n", 278 | "\n", 279 | "def bs_price(S,K,sigma,r,T,n,kind='call'):\n", 280 | " assert kind in ['call','put'],\"Must be call or put\"\n", 281 | " d1 = (np.log(S/K)+(r+0.5*sigma**2)*T)/sigma/np.sqrt(T)\n", 282 | " d2 = d1-sigma*np.sqrt(T)\n", 283 | " return S*N(d1)-K*np.exp(-r*T)*N(d2) if kind=='call' else K*np.exp(-r*T)*N(-d2)-S*N(-d1)\n", 284 | "\n", 285 | "\n", 286 | "\n" 287 | ] 288 | }, 289 | { 290 | "cell_type": "code", 291 | "execution_count": 73, 292 | "id": "e9780aec", 293 | "metadata": {}, 294 | "outputs": [], 295 | "source": [ 296 | "bs_call_price=bs_price(S,K,sigma,r,T,n,kind='call')\n", 297 | "bs_put_price=bs_price(S,K,sigma,r,T,n,kind='put')" 298 | ] 299 | }, 300 | { 301 | "cell_type": "code", 302 | "execution_count": 74, 303 | "id": "7a9924ab", 304 | "metadata": {}, 305 | "outputs": [], 306 | "source": [ 307 | "binomial_call_prices={}\n", 308 | "for n in [100,200,500,1000,10000]:\n", 309 | " binomial_call_prices[n]=binomial_tree_price(S,K,sigma,r,T,n,kind='call',style='European')" 310 | ] 311 | }, 312 | { 313 | "cell_type": "code", 314 | "execution_count": 81, 315 | "id": "1bafa9af", 316 | "metadata": {}, 317 | "outputs": [ 318 | { 319 | "data": { 320 | "text/plain": [ 321 | "({100: 8.0262, 200: 8.026, 500: 8.0232, 1000: 8.0211, 10000: 8.0214}, 8.0214)" 322 | ] 323 | }, 324 | "execution_count": 81, 325 | "metadata": {}, 326 | "output_type": "execute_result" 327 | } 328 | ], 329 | "source": [ 330 | "{k:np.round(v,4) for k,v in binomial_call_prices.items()},np.round(bs_call_price,4)" 331 | ] 332 | }, 333 | { 334 | "cell_type": "code", 335 | "execution_count": 83, 336 | "id": "910a021a", 337 | "metadata": {}, 338 | "outputs": [], 339 | "source": [ 340 | "binomial_put_prices={}\n", 341 | "for n in [100,200,500,1000,10000]:\n", 342 | " binomial_put_prices[n]=binomial_tree_price(S,K,sigma,r,T,n,kind='put',style='European')" 343 | ] 344 | }, 345 | { 346 | "cell_type": "code", 347 | "execution_count": 84, 348 | "id": "f4fd405b", 349 | "metadata": {}, 350 | "outputs": [ 351 | { 352 | "data": { 353 | "text/plain": [ 354 | "({100: 7.9053, 200: 7.9051, 500: 7.9023, 1000: 7.9001, 10000: 7.9005}, 7.9004)" 355 | ] 356 | }, 357 | "execution_count": 84, 358 | "metadata": {}, 359 | "output_type": "execute_result" 360 | } 361 | ], 362 | "source": [ 363 | "{k:np.round(v,4) for k,v in binomial_put_prices.items()},np.round(bs_put_price,4)" 364 | ] 365 | }, 366 | { 367 | "cell_type": "code", 368 | "execution_count": null, 369 | "id": "97ca76f3", 370 | "metadata": {}, 371 | "outputs": [], 372 | "source": [] 373 | } 374 | ], 375 | "metadata": { 376 | "kernelspec": { 377 | "display_name": "py310", 378 | "language": "python", 379 | "name": "py310" 380 | }, 381 | "language_info": { 382 | "codemirror_mode": { 383 | "name": "ipython", 384 | "version": 3 385 | }, 386 | "file_extension": ".py", 387 | "mimetype": "text/x-python", 388 | "name": "python", 389 | "nbconvert_exporter": "python", 390 | "pygments_lexer": "ipython3", 391 | "version": "3.10.13" 392 | } 393 | }, 394 | "nbformat": 4, 395 | "nbformat_minor": 5 396 | } 397 | -------------------------------------------------------------------------------- /old_videos/get_1min_data_fast.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "id": "b2080e48", 7 | "metadata": {}, 8 | "outputs": [ 9 | { 10 | "data": { 11 | "text/plain": [ 12 | "" 13 | ] 14 | }, 15 | "execution_count": 1, 16 | "metadata": {}, 17 | "output_type": "execute_result" 18 | } 19 | ], 20 | "source": [ 21 | "from ib_insync import *\n", 22 | "ib = IB()\n", 23 | "util.startLoop()\n", 24 | "ib.connect(port=4001,clientId=0)" 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": 5, 30 | "id": "bee9e8e5", 31 | "metadata": {}, 32 | "outputs": [ 33 | { 34 | "name": "stderr", 35 | "output_type": "stream", 36 | "text": [ 37 | "reqHistoricalData: Timeout for Stock(conId=76792991, symbol='TSLA', exchange='SMART', primaryExchange='NASDAQ', currency='USD', localSymbol='TSLA', tradingClass='NMS')\n", 38 | "Error 162, reqId 5327: Historical Market Data Service error message:API historical data query cancelled: 5327, contract: Stock(conId=76792991, symbol='TSLA', exchange='SMART', primaryExchange='NASDAQ', currency='USD', localSymbol='TSLA', tradingClass='NMS')\n" 39 | ] 40 | } 41 | ], 42 | "source": [ 43 | "contract = Stock(symbol=\"TSLA\",exchange=\"SMART\",currency=\"USD\")\n", 44 | "ib.qualifyContracts(contract)\n", 45 | "bars = ib.reqHistoricalData(contract,\"\",barSizeSetting='1 min',durationStr='3 M',whatToShow='TRADES',useRTH=False)" 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "execution_count": 13, 51 | "id": "6b585933", 52 | "metadata": {}, 53 | "outputs": [], 54 | "source": [ 55 | "def _make_df(bars):\n", 56 | " df = util.df(bars)\n", 57 | " df.set_index('date',inplace=True)\n", 58 | " df.index = df.index.tz_localize(None)\n", 59 | " return df \n", 60 | "import pandas as pd\n", 61 | "import datetime\n", 62 | "import pandas_market_calendars as mcal\n", 63 | "import os\n", 64 | "# Create a calendar\n", 65 | "nyse = mcal.get_calendar('NYSE')\n", 66 | "def get_historical_1m_data_fast(ib,symbol,start_date,end_date,what_to_show='TRADES',use_rth=False): \n", 67 | " messup_count=0\n", 68 | " df_list=[]\n", 69 | " start_date = datetime.datetime.strptime(start_date,'%Y%m%d').date() # .date() is important to get correct date!\n", 70 | " start_date.strftime('%Y-%m-%d')\n", 71 | " end_date = datetime.datetime.strptime(end_date,'%Y%m%d').date()\n", 72 | " end_date.strftime('%Y-%m-%d')\n", 73 | " dates = nyse.schedule(start_date=start_date, end_date=end_date)\n", 74 | " dates = [t.strftime('%Y%m%d') for t in mcal.date_range(dates, frequency='1D').tolist()]\n", 75 | " dates = [datetime.datetime.strptime(t,'%Y%m%d').date() for t in dates]\n", 76 | " contract = Stock(symbol=symbol,exchange='SMART',currency='USD')\n", 77 | " ib.qualifyContracts(contract)\n", 78 | "\n", 79 | " last_end_date = dates[-1]+datetime.timedelta(days=1)\n", 80 | " for end_date in dates[::-1]:\n", 81 | " if end_date>=last_end_date: continue\n", 82 | " if messup_count>=2: break\n", 83 | " try:\n", 84 | " print(\"Retrieving data for \",symbol,\" for \",end_date)\n", 85 | " bars=ib.reqHistoricalData(contract,endDateTime=end_date,\n", 86 | " barSizeSetting='1 min',whatToShow=what_to_show,useRTH=use_rth,\n", 87 | " durationStr='1 W')\n", 88 | " df=_make_df(bars)\n", 89 | " last_end_date=bars[0].date.date()\n", 90 | " df_list.append(df)\n", 91 | " except Exception as e:\n", 92 | " messup_count+=1\n", 93 | " print(e)\n", 94 | " print(\"No data for \",end_date)\n", 95 | " else:\n", 96 | " messup_count=0\n", 97 | " return pd.concat(df_list).sort_index()" 98 | ] 99 | }, 100 | { 101 | "cell_type": "code", 102 | "execution_count": 14, 103 | "id": "89fe9ad7", 104 | "metadata": {}, 105 | "outputs": [ 106 | { 107 | "name": "stdout", 108 | "output_type": "stream", 109 | "text": [ 110 | "Retrieving data for TSLA for 2023-12-01\n", 111 | "Retrieving data for TSLA for 2023-11-24\n", 112 | "Retrieving data for TSLA for 2023-11-17\n", 113 | "Retrieving data for TSLA for 2023-11-10\n", 114 | "Retrieving data for TSLA for 2023-11-03\n" 115 | ] 116 | } 117 | ], 118 | "source": [ 119 | "df=get_historical_1m_data_fast(ib,'TSLA','20231101','20231201',what_to_show='TRADES',use_rth=False)" 120 | ] 121 | }, 122 | { 123 | "cell_type": "code", 124 | "execution_count": 15, 125 | "id": "bd40ad3b", 126 | "metadata": {}, 127 | "outputs": [ 128 | { 129 | "data": { 130 | "text/html": [ 131 | "
\n", 132 | "\n", 145 | "\n", 146 | " \n", 147 | " \n", 148 | " \n", 149 | " \n", 150 | " \n", 151 | " \n", 152 | " \n", 153 | " \n", 154 | " \n", 155 | " \n", 156 | " \n", 157 | " \n", 158 | " \n", 159 | " \n", 160 | " \n", 161 | " \n", 162 | " \n", 163 | " \n", 164 | " \n", 165 | " \n", 166 | " \n", 167 | " \n", 168 | " \n", 169 | " \n", 170 | " \n", 171 | " \n", 172 | " \n", 173 | " \n", 174 | " \n", 175 | " \n", 176 | " \n", 177 | " \n", 178 | " \n", 179 | " \n", 180 | " \n", 181 | " \n", 182 | " \n", 183 | " \n", 184 | " \n", 185 | " \n", 186 | " \n", 187 | " \n", 188 | " \n", 189 | " \n", 190 | " \n", 191 | " \n", 192 | " \n", 193 | " \n", 194 | " \n", 195 | " \n", 196 | " \n", 197 | " \n", 198 | " \n", 199 | " \n", 200 | " \n", 201 | " \n", 202 | " \n", 203 | " \n", 204 | " \n", 205 | " \n", 206 | " \n", 207 | " \n", 208 | " \n", 209 | " \n", 210 | " \n", 211 | " \n", 212 | " \n", 213 | " \n", 214 | " \n", 215 | " \n", 216 | " \n", 217 | " \n", 218 | " \n", 219 | " \n", 220 | " \n", 221 | " \n", 222 | " \n", 223 | " \n", 224 | " \n", 225 | " \n", 226 | " \n", 227 | " \n", 228 | " \n", 229 | " \n", 230 | " \n", 231 | " \n", 232 | " \n", 233 | " \n", 234 | " \n", 235 | " \n", 236 | " \n", 237 | " \n", 238 | " \n", 239 | " \n", 240 | " \n", 241 | " \n", 242 | " \n", 243 | " \n", 244 | " \n", 245 | " \n", 246 | " \n", 247 | " \n", 248 | " \n", 249 | " \n", 250 | " \n", 251 | " \n", 252 | " \n", 253 | " \n", 254 | " \n", 255 | " \n", 256 | " \n", 257 | " \n", 258 | " \n", 259 | " \n", 260 | " \n", 261 | " \n", 262 | " \n", 263 | " \n", 264 | " \n", 265 | " \n", 266 | " \n", 267 | " \n", 268 | " \n", 269 | " \n", 270 | " \n", 271 | " \n", 272 | " \n", 273 | " \n", 274 | " \n", 275 | " \n", 276 | " \n", 277 | " \n", 278 | " \n", 279 | " \n", 280 | "
openhighlowclosevolumeaveragebarCount
date
2023-10-30 04:00:00209.21210.60208.52210.065142.0209.63022
2023-10-30 04:01:00210.10210.10209.90209.902456.0210.01616
2023-10-30 04:02:00210.10210.21210.10210.19987.0210.1686
2023-10-30 04:03:00210.05210.05209.76209.861942.0209.86911
2023-10-30 04:04:00209.80209.80209.80209.80200.0209.8001
........................
2023-12-01 19:55:00239.30239.40239.30239.401682.0239.31010
2023-12-01 19:56:00239.40239.40239.30239.304223.0239.3555
2023-12-01 19:57:00239.25239.44239.25239.335120.0239.33917
2023-12-01 19:58:00239.45239.45239.35239.443034.0239.41612
2023-12-01 19:59:00239.42239.45239.24239.316054.0239.38724
\n", 281 | "

22860 rows × 7 columns

\n", 282 | "
" 283 | ], 284 | "text/plain": [ 285 | " open high low close volume average barCount\n", 286 | "date \n", 287 | "2023-10-30 04:00:00 209.21 210.60 208.52 210.06 5142.0 209.630 22\n", 288 | "2023-10-30 04:01:00 210.10 210.10 209.90 209.90 2456.0 210.016 16\n", 289 | "2023-10-30 04:02:00 210.10 210.21 210.10 210.19 987.0 210.168 6\n", 290 | "2023-10-30 04:03:00 210.05 210.05 209.76 209.86 1942.0 209.869 11\n", 291 | "2023-10-30 04:04:00 209.80 209.80 209.80 209.80 200.0 209.800 1\n", 292 | "... ... ... ... ... ... ... ...\n", 293 | "2023-12-01 19:55:00 239.30 239.40 239.30 239.40 1682.0 239.310 10\n", 294 | "2023-12-01 19:56:00 239.40 239.40 239.30 239.30 4223.0 239.355 5\n", 295 | "2023-12-01 19:57:00 239.25 239.44 239.25 239.33 5120.0 239.339 17\n", 296 | "2023-12-01 19:58:00 239.45 239.45 239.35 239.44 3034.0 239.416 12\n", 297 | "2023-12-01 19:59:00 239.42 239.45 239.24 239.31 6054.0 239.387 24\n", 298 | "\n", 299 | "[22860 rows x 7 columns]" 300 | ] 301 | }, 302 | "execution_count": 15, 303 | "metadata": {}, 304 | "output_type": "execute_result" 305 | } 306 | ], 307 | "source": [ 308 | "df" 309 | ] 310 | } 311 | ], 312 | "metadata": { 313 | "kernelspec": { 314 | "display_name": "py310", 315 | "language": "python", 316 | "name": "py310" 317 | }, 318 | "language_info": { 319 | "codemirror_mode": { 320 | "name": "ipython", 321 | "version": 3 322 | }, 323 | "file_extension": ".py", 324 | "mimetype": "text/x-python", 325 | "name": "python", 326 | "nbconvert_exporter": "python", 327 | "pygments_lexer": "ipython3", 328 | "version": "3.10.13" 329 | } 330 | }, 331 | "nbformat": 4, 332 | "nbformat_minor": 5 333 | } 334 | -------------------------------------------------------------------------------- /Alpaca/TradingStream2.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "provenance": [], 7 | "authorship_tag": "ABX9TyNfF5OWrydpI47exQsDaEYE", 8 | "include_colab_link": true 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "markdown", 21 | "metadata": { 22 | "id": "view-in-github", 23 | "colab_type": "text" 24 | }, 25 | "source": [ 26 | "\"Open" 27 | ] 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "source": [ 32 | "# Setup\n", 33 | "\n", 34 | "### Install Python SDK" 35 | ], 36 | "metadata": { 37 | "id": "WBFiHh7B4i6Q" 38 | } 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": null, 43 | "metadata": { 44 | "id": "hOR_HPraHxRC" 45 | }, 46 | "outputs": [], 47 | "source": [] 48 | }, 49 | { 50 | "cell_type": "markdown", 51 | "source": [ 52 | "### Grab API key and Secret" 53 | ], 54 | "metadata": { 55 | "id": "YksmyNWk45op" 56 | } 57 | }, 58 | { 59 | "cell_type": "code", 60 | "source": [], 61 | "metadata": { 62 | "id": "gNadZhiAH0Cz" 63 | }, 64 | "execution_count": null, 65 | "outputs": [] 66 | }, 67 | { 68 | "cell_type": "markdown", 69 | "source": [ 70 | "### Connect to Trading Client" 71 | ], 72 | "metadata": { 73 | "id": "sHtVhd4248FR" 74 | } 75 | }, 76 | { 77 | "cell_type": "code", 78 | "source": [], 79 | "metadata": { 80 | "id": "S-1nNEljH3Kw" 81 | }, 82 | "execution_count": null, 83 | "outputs": [] 84 | }, 85 | { 86 | "cell_type": "markdown", 87 | "source": [ 88 | "### Helper Function to View Respones as DataFrames" 89 | ], 90 | "metadata": { 91 | "id": "Kg8RLXy74shB" 92 | } 93 | }, 94 | { 95 | "cell_type": "code", 96 | "source": [ 97 | "import pandas as pd\n", 98 | "\n", 99 | "class Util:\n", 100 | " @staticmethod\n", 101 | " def to_dataframe(data):\n", 102 | " if isinstance(data, list):\n", 103 | " return pd.DataFrame([item.__dict__ for item in data])\n", 104 | " return pd.DataFrame(data, columns=['tag', 'value']).set_index('tag')" 105 | ], 106 | "metadata": { 107 | "id": "DV8DlO2l4sLZ" 108 | }, 109 | "execution_count": null, 110 | "outputs": [] 111 | }, 112 | { 113 | "cell_type": "markdown", 114 | "source": [ 115 | "### Cancel all Orders" 116 | ], 117 | "metadata": { 118 | "id": "bIiXvr-J5LoA" 119 | } 120 | }, 121 | { 122 | "cell_type": "code", 123 | "source": [ 124 | "" 125 | ], 126 | "metadata": { 127 | "id": "rQXPJafC5NgT" 128 | }, 129 | "execution_count": 1, 130 | "outputs": [] 131 | }, 132 | { 133 | "cell_type": "markdown", 134 | "source": [ 135 | "# Make a Buy Order for 1000$ of AMD" 136 | ], 137 | "metadata": { 138 | "id": "ft3grI-4fpin" 139 | } 140 | }, 141 | { 142 | "cell_type": "code", 143 | "source": [ 144 | "from alpaca.trading.requests import MarketOrderRequest,TakeProfitRequest,LimitOrderRequest\n", 145 | "from alpaca.trading.enums import OrderSide, TimeInForce, OrderClass\n", 146 | "\n", 147 | "\n" 148 | ], 149 | "metadata": { 150 | "id": "Qe-mebjvH_sv" 151 | }, 152 | "execution_count": 1, 153 | "outputs": [] 154 | }, 155 | { 156 | "cell_type": "markdown", 157 | "source": [ 158 | "## Let's look at open orders" 159 | ], 160 | "metadata": { 161 | "id": "xEM6fWiNGwfD" 162 | } 163 | }, 164 | { 165 | "cell_type": "code", 166 | "source": [ 167 | "from alpaca.trading.enums import QueryOrderStatus\n", 168 | "from alpaca.trading.requests import GetOrdersRequest\n", 169 | "Util.to_dataframe(trading_client.get_orders(GetOrdersRequest(status=QueryOrderStatus.OPEN)))" 170 | ], 171 | "metadata": { 172 | "colab": { 173 | "base_uri": "https://localhost:8080/", 174 | "height": 182 175 | }, 176 | "id": "kxrhs-HZIMc4", 177 | "outputId": "956f466d-9bd8-4c9b-ec88-780d2817463b" 178 | }, 179 | "execution_count": null, 180 | "outputs": [ 181 | { 182 | "output_type": "execute_result", 183 | "data": { 184 | "text/plain": [ 185 | " id client_order_id \\\n", 186 | "0 4954b422-9158-4974-8e8c-0b04dd54b29e 3bbe2ed9-fa9d-4629-acdb-db757d2950a2 \n", 187 | "\n", 188 | " created_at updated_at \\\n", 189 | "0 2025-05-12 09:35:06.355465+00:00 2025-05-12 09:35:06.365818+00:00 \n", 190 | "\n", 191 | " submitted_at filled_at expired_at \\\n", 192 | "0 2025-05-12 09:35:06.364437+00:00 None None \n", 193 | "\n", 194 | " expires_at canceled_at failed_at ... limit_price stop_price \\\n", 195 | "0 2025-05-13 00:00:00+00:00 None None ... 114.3 None \n", 196 | "\n", 197 | " status extended_hours legs trail_percent trail_price hwm \\\n", 198 | "0 OrderStatus.NEW True None None None None \n", 199 | "\n", 200 | " position_intent ratio_qty \n", 201 | "0 PositionIntent.BUY_TO_OPEN None \n", 202 | "\n", 203 | "[1 rows x 35 columns]" 204 | ], 205 | "text/html": [ 206 | "\n", 207 | "
\n", 208 | "
\n", 209 | "\n", 222 | "\n", 223 | " \n", 224 | " \n", 225 | " \n", 226 | " \n", 227 | " \n", 228 | " \n", 229 | " \n", 230 | " \n", 231 | " \n", 232 | " \n", 233 | " \n", 234 | " \n", 235 | " \n", 236 | " \n", 237 | " \n", 238 | " \n", 239 | " \n", 240 | " \n", 241 | " \n", 242 | " \n", 243 | " \n", 244 | " \n", 245 | " \n", 246 | " \n", 247 | " \n", 248 | " \n", 249 | " \n", 250 | " \n", 251 | " \n", 252 | " \n", 253 | " \n", 254 | " \n", 255 | " \n", 256 | " \n", 257 | " \n", 258 | " \n", 259 | " \n", 260 | " \n", 261 | " \n", 262 | " \n", 263 | " \n", 264 | " \n", 265 | " \n", 266 | " \n", 267 | " \n", 268 | " \n", 269 | " \n", 270 | " \n", 271 | " \n", 272 | " \n", 273 | " \n", 274 | " \n", 275 | "
idclient_order_idcreated_atupdated_atsubmitted_atfilled_atexpired_atexpires_atcanceled_atfailed_at...limit_pricestop_pricestatusextended_hourslegstrail_percenttrail_pricehwmposition_intentratio_qty
04954b422-9158-4974-8e8c-0b04dd54b29e3bbe2ed9-fa9d-4629-acdb-db757d2950a22025-05-12 09:35:06.355465+00:002025-05-12 09:35:06.365818+00:002025-05-12 09:35:06.364437+00:00NoneNone2025-05-13 00:00:00+00:00NoneNone...114.3NoneOrderStatus.NEWTrueNoneNoneNoneNonePositionIntent.BUY_TO_OPENNone
\n", 276 | "

1 rows × 35 columns

\n", 277 | "
\n", 278 | "
\n", 279 | "\n", 280 | "
\n", 281 | " \n", 289 | "\n", 290 | " \n", 330 | "\n", 331 | " \n", 355 | "
\n", 356 | "\n", 357 | "\n", 358 | "
\n", 359 | "
\n" 360 | ], 361 | "application/vnd.google.colaboratory.intrinsic+json": { 362 | "type": "dataframe" 363 | } 364 | }, 365 | "metadata": {}, 366 | "execution_count": 7 367 | } 368 | ] 369 | } 370 | ] 371 | } -------------------------------------------------------------------------------- /old_videos/BinomialTreeToBlackScholes-Video.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 27, 6 | "id": "c4ac1925", 7 | "metadata": {}, 8 | "outputs": [ 9 | { 10 | "data": { 11 | "text/html": [ 12 | "\n", 13 | "\n" 16 | ], 17 | "text/plain": [ 18 | "" 19 | ] 20 | }, 21 | "execution_count": 27, 22 | "metadata": {}, 23 | "output_type": "execute_result" 24 | } 25 | ], 26 | "source": [ 27 | "from IPython.core.display import HTML\n", 28 | "HTML(\"\"\"\n", 29 | "\n", 32 | "\"\"\")" 33 | ] 34 | }, 35 | { 36 | "cell_type": "markdown", 37 | "id": "5da8efb2", 38 | "metadata": {}, 39 | "source": [ 40 | "### Goal of this video\n", 41 | "* Convince you guys emperically that the CRR Binomial Tree Model for European options converges to the Black Scholes Formula as $n\\rightarrow\\infty$\n", 42 | "* Note we can actually show this mathematically (If I get enough comments I can show you)\n", 43 | " \n", 44 | " **Hints**\n", 45 | " - Central limit theorom -> Binomial Distribution becomes Normal as n gets large\n", 46 | " - Expand the risk neutral probability with Taylor Series\n", 47 | " " 48 | ] 49 | }, 50 | { 51 | "cell_type": "markdown", 52 | "id": "f43493af", 53 | "metadata": {}, 54 | "source": [ 55 | "Let's start off where we left off in the previous video with the binomial tree model and show the value for various $n$ steps" 56 | ] 57 | }, 58 | { 59 | "cell_type": "markdown", 60 | "id": "c4f88437", 61 | "metadata": {}, 62 | "source": [ 63 | "#### Imports" 64 | ] 65 | }, 66 | { 67 | "cell_type": "code", 68 | "execution_count": 28, 69 | "id": "138da028", 70 | "metadata": {}, 71 | "outputs": [], 72 | "source": [ 73 | "import numpy as np" 74 | ] 75 | }, 76 | { 77 | "cell_type": "markdown", 78 | "id": "03e5928f", 79 | "metadata": {}, 80 | "source": [ 81 | "### Inputs" 82 | ] 83 | }, 84 | { 85 | "cell_type": "code", 86 | "execution_count": 31, 87 | "id": "194ed07a", 88 | "metadata": {}, 89 | "outputs": [], 90 | "source": [ 91 | "S = 100\n", 92 | "K = 105\n", 93 | "sigma = 0.2\n", 94 | "r = 0.05\n", 95 | "T = 1\n", 96 | "n = 100\n", 97 | "kind = 'call'\n", 98 | "style = 'European'" 99 | ] 100 | }, 101 | { 102 | "cell_type": "markdown", 103 | "id": "13d2d092", 104 | "metadata": {}, 105 | "source": [ 106 | "### Binomial Tree Model" 107 | ] 108 | }, 109 | { 110 | "cell_type": "code", 111 | "execution_count": 30, 112 | "id": "0e097765", 113 | "metadata": {}, 114 | "outputs": [], 115 | "source": [ 116 | "def intrinsic_value(S,K,kind):\n", 117 | " assert kind in ['call','put'],\"Must be call or put\"\n", 118 | " return max(S-K,0) if kind == 'call' else max(K-S,0)\n", 119 | " \n", 120 | "def binomial_tree_price(S,K,sigma,r,T,n,kind='call',style='European'):\n", 121 | " assert kind in ['call','put'],\"Must be call or put\"\n", 122 | " assert style in ['European','American'],\"Must be European or American\"\n", 123 | " \n", 124 | " h = T/n\n", 125 | " u = np.exp(sigma*np.sqrt(h))\n", 126 | " d = 1/u\n", 127 | " p_rn = (np.exp(r*h)-d)/(u-d)\n", 128 | " discount_factor = np.exp(-r*h)\n", 129 | " \n", 130 | " V = np.zeros(shape=(n+1,n+1))\n", 131 | " \n", 132 | " # At expiry (j=n) we know the option values\n", 133 | " for i in range(n+1):\n", 134 | " V[i,n]=intrinsic_value(S*u**i*d**(n-i),K,kind)\n", 135 | " # Go backwords in time\n", 136 | " for j in range(n-1,-1,-1):\n", 137 | " for i in range(j+1):\n", 138 | " continuation_value=discount_factor*(p_rn*V[i+1,j+1]+(1-p_rn)*V[i,j+1])\n", 139 | " if style == 'American':\n", 140 | " early_exercise_value = intrinsic_value(S*u**i*d**(j-i),K,kind=kind)\n", 141 | " V[i,j]=max(early_exercise_value,continuation_value)\n", 142 | " else:\n", 143 | " V[i,j]=continuation_value\n", 144 | " return V[0,0]\n", 145 | " \n", 146 | " \n", 147 | " \n", 148 | " \n", 149 | " \n", 150 | " " 151 | ] 152 | }, 153 | { 154 | "cell_type": "code", 155 | "execution_count": 32, 156 | "id": "5b8417de", 157 | "metadata": {}, 158 | "outputs": [ 159 | { 160 | "data": { 161 | "text/plain": [ 162 | "8.026229025058432" 163 | ] 164 | }, 165 | "execution_count": 32, 166 | "metadata": {}, 167 | "output_type": "execute_result" 168 | } 169 | ], 170 | "source": [ 171 | "binomial_tree_price(S,K,sigma,r,T,n,kind='call',style='European')" 172 | ] 173 | }, 174 | { 175 | "cell_type": "code", 176 | "execution_count": 33, 177 | "id": "3ac3c9f6", 178 | "metadata": {}, 179 | "outputs": [ 180 | { 181 | "data": { 182 | "text/plain": [ 183 | "8.026229025058432" 184 | ] 185 | }, 186 | "execution_count": 33, 187 | "metadata": {}, 188 | "output_type": "execute_result" 189 | } 190 | ], 191 | "source": [ 192 | "binomial_tree_price(S,K,sigma,r,T,n,kind='call',style='American')" 193 | ] 194 | }, 195 | { 196 | "cell_type": "code", 197 | "execution_count": 34, 198 | "id": "68288d4a", 199 | "metadata": {}, 200 | "outputs": [ 201 | { 202 | "data": { 203 | "text/plain": [ 204 | "8.747558705041387" 205 | ] 206 | }, 207 | "execution_count": 34, 208 | "metadata": {}, 209 | "output_type": "execute_result" 210 | } 211 | ], 212 | "source": [ 213 | "binomial_tree_price(S,K,sigma,r,T,n,kind='put',style='American')" 214 | ] 215 | }, 216 | { 217 | "cell_type": "code", 218 | "execution_count": 35, 219 | "id": "cddaaf6e", 220 | "metadata": {}, 221 | "outputs": [ 222 | { 223 | "data": { 224 | "text/plain": [ 225 | "7.90531859763425" 226 | ] 227 | }, 228 | "execution_count": 35, 229 | "metadata": {}, 230 | "output_type": "execute_result" 231 | } 232 | ], 233 | "source": [ 234 | "binomial_tree_price(S,K,sigma,r,T,n,kind='put',style='European')" 235 | ] 236 | }, 237 | { 238 | "cell_type": "markdown", 239 | "id": "8046ece9", 240 | "metadata": {}, 241 | "source": [ 242 | "##### Binomial Tree European value for various n steps\n", 243 | "* For call and put options\n", 244 | "* n = 100,200,500,1000,10000\n", 245 | "* Let's also round to nearest 4 decimal places to better convince you guys" 246 | ] 247 | }, 248 | { 249 | "cell_type": "code", 250 | "execution_count": 37, 251 | "id": "b1e4124a", 252 | "metadata": {}, 253 | "outputs": [], 254 | "source": [ 255 | "binomial_call_prices = {}\n", 256 | "for n in [100,200,500,1000,10000]:\n", 257 | " binomial_call_prices[n] = binomial_tree_price(S,K,sigma,r,T,n,kind='call',style='European')" 258 | ] 259 | }, 260 | { 261 | "cell_type": "code", 262 | "execution_count": 39, 263 | "id": "90a03cba", 264 | "metadata": {}, 265 | "outputs": [ 266 | { 267 | "data": { 268 | "text/plain": [ 269 | "{100: 8.026229025058432,\n", 270 | " 200: 8.02600008453047,\n", 271 | " 500: 8.023175991863205,\n", 272 | " 1000: 8.02106028769686,\n", 273 | " 10000: 8.021380371469782}" 274 | ] 275 | }, 276 | "execution_count": 39, 277 | "metadata": {}, 278 | "output_type": "execute_result" 279 | } 280 | ], 281 | "source": [ 282 | "binomial_call_prices" 283 | ] 284 | }, 285 | { 286 | "cell_type": "code", 287 | "execution_count": 41, 288 | "id": "63d9c636", 289 | "metadata": {}, 290 | "outputs": [], 291 | "source": [ 292 | "binomial_put_prices = {}\n", 293 | "for n in [100,200,500,1000,10000,20000]:\n", 294 | " binomial_put_prices[n] = binomial_tree_price(S,K,sigma,r,T,n,kind='put',style='European')" 295 | ] 296 | }, 297 | { 298 | "cell_type": "code", 299 | "execution_count": 42, 300 | "id": "ebfcbfb6", 301 | "metadata": {}, 302 | "outputs": [ 303 | { 304 | "data": { 305 | "text/plain": [ 306 | "{100: 7.90531859763425,\n", 307 | " 200: 7.905089657104705,\n", 308 | " 500: 7.9022655644360125,\n", 309 | " 1000: 7.900149860269342,\n", 310 | " 10000: 7.900469944031665,\n", 311 | " 20000: 7.900478840722425}" 312 | ] 313 | }, 314 | "execution_count": 42, 315 | "metadata": {}, 316 | "output_type": "execute_result" 317 | } 318 | ], 319 | "source": [ 320 | "binomial_put_prices" 321 | ] 322 | }, 323 | { 324 | "cell_type": "markdown", 325 | "id": "6c871f40", 326 | "metadata": {}, 327 | "source": [ 328 | "## Black Scholes Formula\n", 329 | "\n", 330 | "**Black-Scholes Formula**\n", 331 | "\n", 332 | "The Black-Scholes formula is a cornerstone in options pricing, providing a theoretical value for European-style options. It relies on several key assumptions about market behavior and the underlying asset.\n", 333 | "\n", 334 | "**Mathematical Representation**\n", 335 | "\n", 336 | "$$\n", 337 | "C = S_0 N(d_1) - K e^{-rT} N(d_2)\n", 338 | "$$\n", 339 | "\n", 340 | "$$\n", 341 | "P = K e^{-rT} N(-d_2) - S_0 N(-d_1)\n", 342 | "$$\n", 343 | "\n", 344 | "where:\n", 345 | "\n", 346 | "* $C$: Call option price\n", 347 | "* $P$: Put option price\n", 348 | "* $S_0$: Current price of the underlying asset\n", 349 | "* $K$: Strike price of the option\n", 350 | "* $r$: Risk-free interest rate\n", 351 | "* $T$: Time to expiration (in years)\n", 352 | "* $N(x)$: Cumulative standard normal distribution function\n", 353 | "* $d_1 = \\frac{\\ln(\\frac{S_0}{K}) + (r + \\frac{\\sigma^2}{2})T}{\\sigma \\sqrt{T}}$\n", 354 | "* $d_2 = d_1 - \\sigma \\sqrt{T}$\n", 355 | "* $\\sigma$: Volatility of the underlying asset's returns\n", 356 | "\n", 357 | "**Interpretation**\n", 358 | "\n", 359 | "* The formula calculates the fair price of a call or put option based on the interplay of factors like the current stock price, strike price, time to expiration, risk-free rate, and volatility. \n", 360 | "* $N(d_1)$ and $N(d_2)$ represent the probabilities that the option will expire in-the-money under the risk-neutral measure.\n", 361 | "\n", 362 | "**Assumptions**\n", 363 | "\n", 364 | "* The underlying asset follows a geometric Brownian motion (constant volatility).\n", 365 | "* No dividends are paid on the underlying asset during the option's life.\n", 366 | "* No transaction costs or taxes.\n", 367 | "* Markets are frictionless (no arbitrage opportunities).\n", 368 | "* The risk-free interest rate is constant.\n" 369 | ] 370 | }, 371 | { 372 | "cell_type": "code", 373 | "execution_count": 43, 374 | "id": "69a5abfb", 375 | "metadata": {}, 376 | "outputs": [], 377 | "source": [ 378 | "from scipy.stats import norm\n", 379 | "N = norm.cdf\n", 380 | "def bs_price(S,K,sigma,r,T,n,kind='call'):\n", 381 | " assert kind in ['call','put']\n", 382 | " d1 = (np.log(S/K)+(r+sigma**2/2)*T)/sigma/np.sqrt(T)\n", 383 | " d2 = d1 - sigma*np.sqrt(T)\n", 384 | " return S*N(d1)-K*np.exp(-r*T)*N(d2) if kind == 'call' else K*np.exp(-r*T)*N(-d2)-S*N(-d1)" 385 | ] 386 | }, 387 | { 388 | "cell_type": "code", 389 | "execution_count": 45, 390 | "id": "e9780aec", 391 | "metadata": {}, 392 | "outputs": [], 393 | "source": [ 394 | "bs_call_price = bs_price(S,K,sigma,r,T,n,kind='call')" 395 | ] 396 | }, 397 | { 398 | "cell_type": "code", 399 | "execution_count": 44, 400 | "id": "91e257c5", 401 | "metadata": {}, 402 | "outputs": [], 403 | "source": [ 404 | "bs_put_price = bs_price(S,K,sigma,r,T,n,kind='put')" 405 | ] 406 | }, 407 | { 408 | "cell_type": "markdown", 409 | "id": "6724b134", 410 | "metadata": {}, 411 | "source": [ 412 | "##### Compare Binomial to BS Call Prices" 413 | ] 414 | }, 415 | { 416 | "cell_type": "code", 417 | "execution_count": 49, 418 | "id": "d0b9cc1b", 419 | "metadata": {}, 420 | "outputs": [ 421 | { 422 | "name": "stdout", 423 | "output_type": "stream", 424 | "text": [ 425 | "Num steps 100,Price 8.0262\n", 426 | "Num steps 200,Price 8.026\n", 427 | "Num steps 500,Price 8.0232\n", 428 | "Num steps 1000,Price 8.0211\n", 429 | "Num steps 10000,Price 8.0214\n", 430 | "BS Price 8.0214\n" 431 | ] 432 | } 433 | ], 434 | "source": [ 435 | "for n_steps,option_price in binomial_call_prices.items():\n", 436 | " print(f\"Num steps {n_steps},Price {np.round(option_price,4)}\")\n", 437 | "print(\"BS Price\",np.round(bs_call_price,4))" 438 | ] 439 | }, 440 | { 441 | "cell_type": "markdown", 442 | "id": "a1e69866", 443 | "metadata": {}, 444 | "source": [ 445 | "##### Compare Binomial to BS Put Prices" 446 | ] 447 | }, 448 | { 449 | "cell_type": "code", 450 | "execution_count": 51, 451 | "id": "24fc37ea", 452 | "metadata": {}, 453 | "outputs": [ 454 | { 455 | "name": "stdout", 456 | "output_type": "stream", 457 | "text": [ 458 | "Num steps 100,Price 7.9053\n", 459 | "Num steps 200,Price 7.9051\n", 460 | "Num steps 500,Price 7.9023\n", 461 | "Num steps 1000,Price 7.9001\n", 462 | "Num steps 10000,Price 7.9005\n", 463 | "Num steps 20000,Price 7.9005\n", 464 | "BS Price 7.9004\n" 465 | ] 466 | } 467 | ], 468 | "source": [ 469 | "for n_steps,option_price in binomial_put_prices.items():\n", 470 | " print(f\"Num steps {n_steps},Price {np.round(option_price,4)}\")\n", 471 | "print(\"BS Price\",np.round(bs_put_price,4))" 472 | ] 473 | }, 474 | { 475 | "cell_type": "code", 476 | "execution_count": null, 477 | "id": "ba4e7acd", 478 | "metadata": {}, 479 | "outputs": [], 480 | "source": [] 481 | }, 482 | { 483 | "cell_type": "code", 484 | "execution_count": null, 485 | "id": "4b225497", 486 | "metadata": {}, 487 | "outputs": [], 488 | "source": [] 489 | } 490 | ], 491 | "metadata": { 492 | "kernelspec": { 493 | "display_name": "py310", 494 | "language": "python", 495 | "name": "py310" 496 | }, 497 | "language_info": { 498 | "codemirror_mode": { 499 | "name": "ipython", 500 | "version": 3 501 | }, 502 | "file_extension": ".py", 503 | "mimetype": "text/x-python", 504 | "name": "python", 505 | "nbconvert_exporter": "python", 506 | "pygments_lexer": "ipython3", 507 | "version": "3.10.13" 508 | } 509 | }, 510 | "nbformat": 4, 511 | "nbformat_minor": 5 512 | } 513 | -------------------------------------------------------------------------------- /Together_AI_Rag.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "provenance": [], 7 | "authorship_tag": "ABX9TyMvNfquPFi3bU0z4qOmlxyU", 8 | "include_colab_link": true 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "markdown", 21 | "metadata": { 22 | "id": "view-in-github", 23 | "colab_type": "text" 24 | }, 25 | "source": [ 26 | "\"Open" 27 | ] 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "source": [ 32 | "Together AI is a platform that simplifies working with open‑source generative AI models. It offers serverless model access, quick fine‑tuning, private GPU endpoints, and scalable cloud infrastructure—making it easy for developers to train, deploy, and run models for tasks like chat, vision, embeddings, and more using just a few lines of code ." 33 | ], 34 | "metadata": { 35 | "id": "TlzpeQtTIaLs" 36 | } 37 | }, 38 | { 39 | "cell_type": "code", 40 | "source": [ 41 | "!pip install together" 42 | ], 43 | "metadata": { 44 | "colab": { 45 | "base_uri": "https://localhost:8080/" 46 | }, 47 | "id": "yGWOK5cIoiuA", 48 | "outputId": "c333c81b-62ad-4bd7-d0ab-75f0dcd0150c" 49 | }, 50 | "execution_count": 3, 51 | "outputs": [ 52 | { 53 | "output_type": "stream", 54 | "name": "stdout", 55 | "text": [ 56 | "Collecting together\n", 57 | " Downloading together-1.5.13-py3-none-any.whl.metadata (15 kB)\n", 58 | "Requirement already satisfied: aiohttp<4.0.0,>=3.9.3 in /usr/local/lib/python3.11/dist-packages (from together) (3.11.15)\n", 59 | "Requirement already satisfied: click<9.0.0,>=8.1.7 in /usr/local/lib/python3.11/dist-packages (from together) (8.2.1)\n", 60 | "Collecting eval-type-backport<0.3.0,>=0.1.3 (from together)\n", 61 | " Downloading eval_type_backport-0.2.2-py3-none-any.whl.metadata (2.2 kB)\n", 62 | "Requirement already satisfied: filelock<4.0.0,>=3.13.1 in /usr/local/lib/python3.11/dist-packages (from together) (3.18.0)\n", 63 | "Requirement already satisfied: numpy>=1.23.5 in /usr/local/lib/python3.11/dist-packages (from together) (2.0.2)\n", 64 | "Requirement already satisfied: pillow<12.0.0,>=11.1.0 in /usr/local/lib/python3.11/dist-packages (from together) (11.2.1)\n", 65 | "Requirement already satisfied: pydantic<3.0.0,>=2.6.3 in /usr/local/lib/python3.11/dist-packages (from together) (2.11.5)\n", 66 | "Requirement already satisfied: requests<3.0.0,>=2.31.0 in /usr/local/lib/python3.11/dist-packages (from together) (2.32.3)\n", 67 | "Requirement already satisfied: rich<15.0.0,>=13.8.1 in /usr/local/lib/python3.11/dist-packages (from together) (13.9.4)\n", 68 | "Requirement already satisfied: tabulate<0.10.0,>=0.9.0 in /usr/local/lib/python3.11/dist-packages (from together) (0.9.0)\n", 69 | "Requirement already satisfied: tqdm<5.0.0,>=4.66.2 in /usr/local/lib/python3.11/dist-packages (from together) (4.67.1)\n", 70 | "Collecting typer<0.16,>=0.9 (from together)\n", 71 | " Downloading typer-0.15.4-py3-none-any.whl.metadata (15 kB)\n", 72 | "Requirement already satisfied: aiohappyeyeballs>=2.3.0 in /usr/local/lib/python3.11/dist-packages (from aiohttp<4.0.0,>=3.9.3->together) (2.6.1)\n", 73 | "Requirement already satisfied: aiosignal>=1.1.2 in /usr/local/lib/python3.11/dist-packages (from aiohttp<4.0.0,>=3.9.3->together) (1.3.2)\n", 74 | "Requirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.11/dist-packages (from aiohttp<4.0.0,>=3.9.3->together) (25.3.0)\n", 75 | "Requirement already satisfied: frozenlist>=1.1.1 in /usr/local/lib/python3.11/dist-packages (from aiohttp<4.0.0,>=3.9.3->together) (1.6.0)\n", 76 | "Requirement already satisfied: multidict<7.0,>=4.5 in /usr/local/lib/python3.11/dist-packages (from aiohttp<4.0.0,>=3.9.3->together) (6.4.4)\n", 77 | "Requirement already satisfied: propcache>=0.2.0 in /usr/local/lib/python3.11/dist-packages (from aiohttp<4.0.0,>=3.9.3->together) (0.3.1)\n", 78 | "Requirement already satisfied: yarl<2.0,>=1.17.0 in /usr/local/lib/python3.11/dist-packages (from aiohttp<4.0.0,>=3.9.3->together) (1.20.0)\n", 79 | "Requirement already satisfied: annotated-types>=0.6.0 in /usr/local/lib/python3.11/dist-packages (from pydantic<3.0.0,>=2.6.3->together) (0.7.0)\n", 80 | "Requirement already satisfied: pydantic-core==2.33.2 in /usr/local/lib/python3.11/dist-packages (from pydantic<3.0.0,>=2.6.3->together) (2.33.2)\n", 81 | "Requirement already satisfied: typing-extensions>=4.12.2 in /usr/local/lib/python3.11/dist-packages (from pydantic<3.0.0,>=2.6.3->together) (4.14.0)\n", 82 | "Requirement already satisfied: typing-inspection>=0.4.0 in /usr/local/lib/python3.11/dist-packages (from pydantic<3.0.0,>=2.6.3->together) (0.4.1)\n", 83 | "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.11/dist-packages (from requests<3.0.0,>=2.31.0->together) (3.4.2)\n", 84 | "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.11/dist-packages (from requests<3.0.0,>=2.31.0->together) (3.10)\n", 85 | "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.11/dist-packages (from requests<3.0.0,>=2.31.0->together) (2.4.0)\n", 86 | "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.11/dist-packages (from requests<3.0.0,>=2.31.0->together) (2025.4.26)\n", 87 | "Requirement already satisfied: markdown-it-py>=2.2.0 in /usr/local/lib/python3.11/dist-packages (from rich<15.0.0,>=13.8.1->together) (3.0.0)\n", 88 | "Requirement already satisfied: pygments<3.0.0,>=2.13.0 in /usr/local/lib/python3.11/dist-packages (from rich<15.0.0,>=13.8.1->together) (2.19.1)\n", 89 | "Collecting click<9.0.0,>=8.1.7 (from together)\n", 90 | " Downloading click-8.1.8-py3-none-any.whl.metadata (2.3 kB)\n", 91 | "Requirement already satisfied: shellingham>=1.3.0 in /usr/local/lib/python3.11/dist-packages (from typer<0.16,>=0.9->together) (1.5.4)\n", 92 | "Requirement already satisfied: mdurl~=0.1 in /usr/local/lib/python3.11/dist-packages (from markdown-it-py>=2.2.0->rich<15.0.0,>=13.8.1->together) (0.1.2)\n", 93 | "Downloading together-1.5.13-py3-none-any.whl (90 kB)\n", 94 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m90.7/90.7 kB\u001b[0m \u001b[31m6.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", 95 | "\u001b[?25hDownloading eval_type_backport-0.2.2-py3-none-any.whl (5.8 kB)\n", 96 | "Downloading typer-0.15.4-py3-none-any.whl (45 kB)\n", 97 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m45.3/45.3 kB\u001b[0m \u001b[31m3.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", 98 | "\u001b[?25hDownloading click-8.1.8-py3-none-any.whl (98 kB)\n", 99 | "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m98.2/98.2 kB\u001b[0m \u001b[31m7.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", 100 | "\u001b[?25hInstalling collected packages: eval-type-backport, click, typer, together\n", 101 | " Attempting uninstall: click\n", 102 | " Found existing installation: click 8.2.1\n", 103 | " Uninstalling click-8.2.1:\n", 104 | " Successfully uninstalled click-8.2.1\n", 105 | " Attempting uninstall: typer\n", 106 | " Found existing installation: typer 0.16.0\n", 107 | " Uninstalling typer-0.16.0:\n", 108 | " Successfully uninstalled typer-0.16.0\n", 109 | "Successfully installed click-8.1.8 eval-type-backport-0.2.2 together-1.5.13 typer-0.15.4\n" 110 | ] 111 | } 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": 6, 117 | "metadata": { 118 | "colab": { 119 | "base_uri": "https://localhost:8080/" 120 | }, 121 | "id": "PaDQxcn5nHU-", 122 | "outputId": "575ecce5-9703-44f0-da4d-bfc5ad8f2389" 123 | }, 124 | "outputs": [ 125 | { 126 | "output_type": "stream", 127 | "name": "stdout", 128 | "text": [ 129 | "\n", 130 | "Okay, the user is asking for fun things to do in New York. Let me start by recalling the major attractions. There's Central Park, obviously. People love that for picnics, walking, or biking. Then there's the Statue of Liberty and Ellis Island. Those are must-sees for tourists, but maybe locals enjoy them too. The Metropolitan Museum of Art comes to mind. Museums are a big part of NYC. Times Square is another iconic spot, especially at night with the lights.\n", 131 | "\n", 132 | "Wait, but the user might already know the obvious stuff. Maybe I should include some lesser-known spots too. Like the High Line, the elevated park. That's pretty unique. Also, maybe the 9/11 Memorial and Museum. It's a significant site and can be both educational and moving.\n", 133 | "\n", 134 | "Food is a big part of New York. Maybe suggest some famous foods like pizza, bagels, or the food markets like Chelsea Market. Theater in Broadway is a classic, but maybe mention off-Broadway shows for different experiences. The Brooklyn Bridge walk is another activity that offers great views.\n", 135 | "\n", 136 | "What about seasonal activities? Like ice skating in the winter, maybe at Rockefeller Center. Summer concerts or Shakespeare in the Park. Also, neighborhoods like SoHo for shopping, Greenwich Village for its historic vibe. The Empire State Building and Top of the Rock for observation decks. Maybe the American Museum of Natural History for families.\n", 137 | "\n", 138 | "Wait, but I should check if I'm missing any recent additions. Like the Vessel at Hudson Yards, or the Little Island park. Also, cultural areas like Chinatown or Harlem. Maybe include a jazz club or a famous diner like Katz's Delicatessen. Oh, and the New York Public Library is a beautiful spot.\n", 139 | "\n", 140 | "I should also consider different interests—art, history, food, outdoor activities. Maybe separate into categories. Also, transportation tips? Like subway or Citi Bikes. But the user asked for fun things, not logistics. Need to balance between iconic and hidden gems. Let me list out the main ones and then add some unique ones. Also, maybe mention events like the Macy's Parade or New Year's Eve in Times Square. But that's seasonal. Maybe include a mix.\n", 141 | "\n", 142 | "Wait, the user might be a tourist or a local looking for new ideas. So covering both could be good. Let me make sure to include a variety. Also, check for any inaccuracies. For example, is the High Line still popular? Yes, it's a big attraction. And the Vessel, though controversial, is still a spot. Also, maybe the Bronx Zoo or Coney Island for more offbeat stuff. But that might be stretching. Need to keep it manageable. Alright, I think I have a good list. Now structure it into sections with brief descriptions and tips.\n", 143 | "\n", 144 | "\n", 145 | "New York City is a treasure trove of iconic landmarks, cultural gems, and unique experiences. Here's a curated list of fun activities, blending classics with hidden gems:\n", 146 | "\n", 147 | "### **Iconic Must-Do Experiences**\n", 148 | "1. **Statue of Liberty & Ellis Island** \n", 149 | " - Take a ferry to explore the statue's pedestal or museum, then learn about immigration history at Ellis Island.\n", 150 | " - *Tip:* Book tickets early for rooftop access at the Statue.\n", 151 | "\n", 152 | "2. **Central Park** \n", 153 | " - Rent a bike, picnic on the Great Lawn, or explore hidden spots like the **Bethesda Terrace** or **Strawberry Fields**.\n", 154 | " - *Seasonal Tip:* Winter ice-skating at Wollman Rink.\n", 155 | "\n", 156 | "3. **Top of the Rock or Empire State Building** \n", 157 | " - Compare sunset views from these iconic observation decks. The Rock’s open-air decks offer a unique perspective.\n", 158 | "\n", 159 | "4. **Broadway Show** \n", 160 | " - Catch a musical or play. For budget-friendly options, try the **TodayTix app** for last-minute tickets or opt for off-Broadway gems like the **Blue Man Group**.\n", 161 | "\n", 162 | "### **Cultural & Historical Gems**\n", 163 | "5. **The Met Cloisters & Temple of Dendur** \n", 164 | " - A medieval art haven in Fort Tryon Park, with a serene rooftop garden and a stunning Egyptian temple.\n", 165 | "\n", 166 | "6. **9/11 Memorial & Museum** \n", 167 | " - Reflect at the twin reflecting pools and explore artifacts in the underground museum.\n", 168 | "\n", 169 | "7. **Harlem Renaissance Tours** \n", 170 | " - Experience soul food, gospel brunches, or a guided walk through historic sites like the **Apollo Theater**.\n", 171 | "\n", 172 | "### **Outdoor Adventures**\n", 173 | "8. **High Line & Little Island** \n", 174 | " - Stroll this elevated park built on old train tracks, ending at the quirky **Vessel** sculpture. Nearby, **Little Island** offers performance spaces and green terraces.\n", 175 | "\n", 176 | "9. **Brooklyn Bridge Walk** \n", 177 | " - Walk or bike across the bridge at dusk for skyline views. Pair it with a visit to **Dumbo** and **Jane’s Carousel**.\n", 178 | "\n", 179 | "10. **Coney Island** \n", 180 | " - Ride the Cyclone roller coaster, eat Nathan’s hot dogs, and enjoy the boardwalk’s retro vibe.\n", 181 | "\n", 182 | "### **Food & Markets**\n", 183 | "11. **Chelsea Market** \n", 184 | " - Sample global eats like Los Tacos No. 1 or the famous **Big Mozzarella Stand**.\n", 185 | "\n", 186 | "12. **Katz’s Delicatessen** \n", 187 | " - Dive into a pastrami sandwich (made famous by *When Harry Met Sally*) and watch the slicers in action.\n", 188 | "\n", 189 | "13. **Arthur Avenue (The Bronx)** \n", 190 | " - Explore NYC’s original Little Italy with authentic Italian markets and restaurants.\n", 191 | "\n", 192 | "### **Hidden Gems & Local Favorites**\n", 193 | "14. **The New York Public Library** \n", 194 | " - Admire the Beaux-Arts architecture and the iconic lion statues (Patience and Fortitude).\n", 195 | "\n", 196 | "15. **Green-Wood Cemetery** \n", 197 | " - A serene, historic burial ground with artful tombs and trolley tours.\n", 198 | "\n", 199 | "16. **The Tenement Museum** \n", 200 | " - Step into 19th-century immigrant life through immersive tours of a restored apartment building.\n", 201 | "\n", 202 | "### **Seasonal Fun**\n", 203 | "- **Winter:** Rockefeller Center ice-skating and holiday markets. \n", 204 | "- **Spring:** Sakura Matsuri cherry blossom festival in Brooklyn Botanic Garden. \n", 205 | "- **Summer:** Outdoor movies in parks or **Shakespeare in the Park**. \n", 206 | "- **Fall:** Apple-picking in the Hudson Valley or leaf-peeping in Central Park.\n", 207 | "\n", 208 | "### **Unique Experiences**\n", 209 | "- **Whitney Museum’s 7th Floor Terrace:** Rooftop views with art installations. \n", 210 | "- **Lowline Lab:** A futuristic underground park prototype. \n", 211 | "- **Coney Island Sideshows:** Check out quirky performances at the **Coney Island Circus Sideshow**.\n", 212 | "\n", 213 | "### **Practical Tips**\n", 214 | "- **Transportation:** Use the subway or **Citi Bike** for easy exploration. \n", 215 | "- **Free Attractions:** Many museums (The Met, MoMA) have pay-what-you-wish policies. \n", 216 | "- **Events:** Check listings for **NYC Official Guide** for festivals, parades, or pop-ups.\n", 217 | "\n", 218 | "Whether you're a first-timer or a local, NYC’s mix of energy and history ensures there’s always something new to discover! 🗽🍴🗽\n" 219 | ] 220 | } 221 | ], 222 | "source": [ 223 | "from together import Together\n", 224 | "from google.colab import userdata\n", 225 | "import os\n", 226 | "os.environ[\"TOGETHER_API_KEY\"] = userdata.get('TOGETHER_API_KEY')\n", 227 | "client = Together() # auth defaults to os.environ.get(\"TOGETHER_API_KEY\")\n", 228 | "\n", 229 | "response = client.chat.completions.create(\n", 230 | " model=\"Qwen/Qwen3-235B-A22B-fp8-tput\",\n", 231 | " messages=[\n", 232 | " {\n", 233 | " \"role\": \"user\",\n", 234 | " \"content\": \"What are some fun things to do in New York?\"\n", 235 | " }\n", 236 | " ]\n", 237 | ")\n", 238 | "print(response.choices[0].message.content)" 239 | ] 240 | } 241 | ] 242 | } -------------------------------------------------------------------------------- /old_videos/Multithreading tutorial.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "861e637b", 6 | "metadata": {}, 7 | "source": [ 8 | "### Goal of this video\n", 9 | "* If you have multiple accounts with multiple users how to leverage python threading to get historical data much faster\n", 10 | "\n", 11 | "### Running a function in main thread blocks the code\n", 12 | "* Can run in seperate \"threads\" to be non blocking\n", 13 | "* Good for network/IO bound things\n", 14 | "* Not real C like threading, more like \"pseudo-threading\" moving between tasks due to GIL (global interpreter lock) " 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": 2, 20 | "id": "8ca5dd3f", 21 | "metadata": {}, 22 | "outputs": [], 23 | "source": [ 24 | "import threading\n", 25 | "import time\n", 26 | "def print_data(name,limit):\n", 27 | " global stop\n", 28 | " stop=False\n", 29 | " for i in range(limit):\n", 30 | " if stop:\n", 31 | " break\n", 32 | " time.sleep(1)\n", 33 | " print(f\"{name} {i}\")" 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": 2, 39 | "id": "3697dce7", 40 | "metadata": {}, 41 | "outputs": [ 42 | { 43 | "name": "stdout", 44 | "output_type": "stream", 45 | "text": [ 46 | "ADI 0\n", 47 | "ADI 1\n", 48 | "ADI 2\n", 49 | "ADI 3\n", 50 | "ADI 4\n", 51 | "ADI 5\n", 52 | "ADI 6\n", 53 | "ADI 7\n", 54 | "ADI 8\n", 55 | "ADI 9\n" 56 | ] 57 | } 58 | ], 59 | "source": [ 60 | "print_data(\"ADI\",10)" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": 3, 66 | "id": "249b3268", 67 | "metadata": {}, 68 | "outputs": [], 69 | "source": [ 70 | "t100 = threading.Thread(target=print_data,args=('adi',100))\n", 71 | "t10 = threading.Thread(target=print_data,args=('bob',10))" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": 4, 77 | "id": "6b39b525", 78 | "metadata": {}, 79 | "outputs": [], 80 | "source": [ 81 | "t100.start()\n", 82 | "t10.start()" 83 | ] 84 | }, 85 | { 86 | "cell_type": "code", 87 | "execution_count": null, 88 | "id": "1bc32ef3", 89 | "metadata": {}, 90 | "outputs": [ 91 | { 92 | "name": "stdout", 93 | "output_type": "stream", 94 | "text": [ 95 | "bob 0adi 0\n", 96 | "\n", 97 | "adi 1\n", 98 | "bob 1\n", 99 | "bob 2\n", 100 | "adi 2\n", 101 | "bob 3\n", 102 | "adi 3\n", 103 | "bob 4adi 4\n", 104 | "\n", 105 | "bob 5adi 5\n", 106 | "\n", 107 | "bob 6adi 6\n", 108 | "\n", 109 | "adi 7bob 7\n", 110 | "\n", 111 | "adi 8\n", 112 | "bob 8\n", 113 | "adi 9\n", 114 | "bob 9\n", 115 | "adi 10\n", 116 | "adi 11\n", 117 | "adi 12\n", 118 | "adi 13\n", 119 | "adi 14\n", 120 | "adi 15\n", 121 | "adi 16\n", 122 | "adi 17\n", 123 | "adi 18\n", 124 | "adi 19\n", 125 | "adi 20\n", 126 | "adi 21\n", 127 | "adi 22\n", 128 | "adi 23\n", 129 | "adi 24\n", 130 | "adi 25\n", 131 | "adi 26\n", 132 | "adi 27\n", 133 | "adi 28\n", 134 | "adi 29\n", 135 | "adi 30\n", 136 | "adi 31\n", 137 | "adi 32\n", 138 | "adi 33\n", 139 | "adi 34\n", 140 | "adi 35\n", 141 | "adi 36\n", 142 | "adi 37\n", 143 | "adi 38\n", 144 | "adi 39\n", 145 | "adi 40\n", 146 | "adi 41\n", 147 | "adi 42\n", 148 | "adi 43\n", 149 | "adi 44\n", 150 | "adi 45\n" 151 | ] 152 | } 153 | ], 154 | "source": [ 155 | "t100.join()\n", 156 | "t10.join()" 157 | ] 158 | }, 159 | { 160 | "cell_type": "markdown", 161 | "id": "cd83346a", 162 | "metadata": {}, 163 | "source": [ 164 | "* Use .start() to start thread\n", 165 | "* Can use .join to block future execucution. \n", 166 | "* Deamon threads are threads that run in the background and don't stop the program from exiting." 167 | ] 168 | }, 169 | { 170 | "cell_type": "code", 171 | "execution_count": 3, 172 | "id": "53d42649", 173 | "metadata": {}, 174 | "outputs": [], 175 | "source": [ 176 | "import pandas as pd\n", 177 | "import datetime\n", 178 | "\n", 179 | "### Nasdaq 100 Symbols\n", 180 | "\n", 181 | "import pandas as pd\n", 182 | "nasdaq_100=pd.read_html(\"https://en.wikipedia.org/wiki/Nasdaq-100\")[4]\n", 183 | "nasdaq_100_symbols=nasdaq_100.Ticker.tolist()\n", 184 | "\n", 185 | "### S&P 500 Symbols\n", 186 | "\n", 187 | "sp500=pd.read_html(\"https://en.wikipedia.org/wiki/List_of_S%26P_500_companies\")[0]\n", 188 | "sp500_symbols = sp500.Symbol.tolist()\n", 189 | "\n", 190 | "### Russell 1000\n", 191 | "\n", 192 | "russell=pd.read_html(\"https://en.wikipedia.org/wiki/Russell_1000_Index\")[2]\n", 193 | "russell_symbols=russell.Ticker.tolist()\n", 194 | "\n", 195 | "### Combined all ticker symbols\n", 196 | "\n", 197 | "symbol_list = list(set(nasdaq_100_symbols+sp500_symbols+russell_symbols))" 198 | ] 199 | }, 200 | { 201 | "cell_type": "markdown", 202 | "id": "b8ed7f68", 203 | "metadata": {}, 204 | "source": [ 205 | "##### Need to split this symbol_list into multiple parts accross ports (accounts)\n", 206 | "* will also split across clients, but i don't think this improves performance due to IB limitations.\n" 207 | ] 208 | }, 209 | { 210 | "cell_type": "code", 211 | "execution_count": 4, 212 | "id": "9ab1e4e2", 213 | "metadata": {}, 214 | "outputs": [], 215 | "source": [ 216 | "port_ids = [4001,4002,4003,4004]\n", 217 | "client_ids = [0,1]\n", 218 | "NUM_PORTS = len(port_ids)\n", 219 | "NUM_CLIENTS = len(client_ids)\n", 220 | "interval_size = len(symbol_list)//NUM_CLIENTS//NUM_PORTS\n", 221 | "symbol_list_split={(port_ids[i],client_ids[j]):\n", 222 | " symbol_list[(i*NUM_CLIENTS+j)*interval_size:(i*NUM_CLIENTS+j+1)*interval_size]\n", 223 | " for i in range(NUM_PORTS) for j in range(NUM_CLIENTS)\n", 224 | " \n", 225 | " }" 226 | ] 227 | }, 228 | { 229 | "cell_type": "markdown", 230 | "id": "89e4fcc5", 231 | "metadata": {}, 232 | "source": [ 233 | "### Create function for Port/Client Combo to do work" 234 | ] 235 | }, 236 | { 237 | "cell_type": "code", 238 | "execution_count": 5, 239 | "id": "0c83d36b", 240 | "metadata": {}, 241 | "outputs": [], 242 | "source": [ 243 | "from data_utils import get_historical_1m_data_fast" 244 | ] 245 | }, 246 | { 247 | "cell_type": "code", 248 | "execution_count": 6, 249 | "id": "17db8b86", 250 | "metadata": {}, 251 | "outputs": [ 252 | { 253 | "ename": "FileExistsError", 254 | "evalue": "[WinError 183] Cannot create a file when that file already exists: 'data'", 255 | "output_type": "error", 256 | "traceback": [ 257 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 258 | "\u001b[1;31mFileExistsError\u001b[0m Traceback (most recent call last)", 259 | "Cell \u001b[1;32mIn[6], line 2\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mos\u001b[39;00m\n\u001b[1;32m----> 2\u001b[0m \u001b[43mos\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mmkdir\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43mdata\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m)\u001b[49m\n", 260 | "\u001b[1;31mFileExistsError\u001b[0m: [WinError 183] Cannot create a file when that file already exists: 'data'" 261 | ] 262 | } 263 | ], 264 | "source": [ 265 | "import os\n", 266 | "os.mkdir('data')" 267 | ] 268 | }, 269 | { 270 | "cell_type": "code", 271 | "execution_count": 7, 272 | "id": "7b1b33c9", 273 | "metadata": {}, 274 | "outputs": [], 275 | "source": [ 276 | "import asyncio\n", 277 | "from ib_insync import *\n", 278 | "def get_data(port_id,client_id):\n", 279 | " loop = asyncio.new_event_loop()\n", 280 | " asyncio.set_event_loop(loop)\n", 281 | " ib = IB()\n", 282 | " ib.connect(port=port_id,clientId=client_id)\n", 283 | " try:\n", 284 | " for symbol in symbol_list_split[(port_id,client_id)]:\n", 285 | " print(f\"Getting data using port {port_id} and clientId {client_id}\")\n", 286 | " df=get_historical_1m_data_fast(ib,symbol,'20231101','20231201')\n", 287 | " df.to_csv(f'data/{symbol}_1_mins.csv')\n", 288 | " except Exception as e:\n", 289 | " print(e)\n", 290 | " ib.disconnect()\n" 291 | ] 292 | }, 293 | { 294 | "cell_type": "code", 295 | "execution_count": 8, 296 | "id": "ff6cd481", 297 | "metadata": {}, 298 | "outputs": [ 299 | { 300 | "name": "stdout", 301 | "output_type": "stream", 302 | "text": [ 303 | "Getting data using port 4001 and clientId 0\n", 304 | "Getting data using port 4001 and clientId 1\n", 305 | "Getting data using port 4002 and clientId 0\n", 306 | "Getting data using port 4004 and clientId 0\n", 307 | "Getting data using port 4003 and clientId 0\n", 308 | "Getting data using port 4002 and clientId 1\n" 309 | ] 310 | } 311 | ], 312 | "source": [ 313 | "threads = []\n", 314 | "\n", 315 | "for port_id in port_ids:\n", 316 | " for client_id in client_ids:\n", 317 | " thread = threading.Thread(target=get_data,args=(port_id,client_id))\n", 318 | " threads.append(thread)\n", 319 | " thread.start()\n", 320 | " " 321 | ] 322 | }, 323 | { 324 | "cell_type": "code", 325 | "execution_count": null, 326 | "id": "2e2f6445", 327 | "metadata": {}, 328 | "outputs": [ 329 | { 330 | "name": "stdout", 331 | "output_type": "stream", 332 | "text": [ 333 | "Getting data using port 4003 and clientId 1\n", 334 | "Getting data using port 4004 and clientId 1\n", 335 | "Retrieving data for BPOP for 2023-12-01\n", 336 | "Retrieving data for SPR for 2023-12-01\n", 337 | "Retrieving data for HPE for 2023-12-01\n", 338 | "Retrieving data for MPW for 2023-12-01\n", 339 | "Retrieving data for PODD for 2023-12-01\n", 340 | "Retrieving data for DLB for 2023-12-01\n", 341 | "Retrieving data for CAG for 2023-12-01\n", 342 | "Retrieving data for CARR for 2023-12-01\n", 343 | "Retrieving data for SPR for 2023-11-24\n", 344 | "Retrieving data for HPE for 2023-11-24\n", 345 | "Retrieving data for BPOP for 2023-11-24\n", 346 | "Retrieving data for PODD for 2023-11-24\n", 347 | "Retrieving data for CAG for 2023-11-24\n", 348 | "Retrieving data for MPW for 2023-11-24\n", 349 | "Retrieving data for CARR for 2023-11-24\n", 350 | "Retrieving data for PODD for 2023-11-17\n", 351 | "Retrieving data for MPW for 2023-11-17\n", 352 | "Retrieving data for CAG for 2023-11-17\n", 353 | "Retrieving data for SPR for 2023-11-17\n", 354 | "Retrieving data for HPE for 2023-11-17\n", 355 | "Retrieving data for CARR for 2023-11-17\n", 356 | "Retrieving data for PODD for 2023-11-10\n", 357 | "Retrieving data for BPOP for 2023-11-17\n", 358 | "Retrieving data for DLB for 2023-11-24\n", 359 | "Retrieving data for MPW for 2023-11-10\n", 360 | "Retrieving data for SPR for 2023-11-10\n", 361 | "Retrieving data for CARR for 2023-11-10\n", 362 | "Retrieving data for BPOP for 2023-11-10\n", 363 | "Retrieving data for DLB for 2023-11-17\n", 364 | "Retrieving data for CAG for 2023-11-10\n", 365 | "Retrieving data for PODD for 2023-11-03\n", 366 | "Retrieving data for MPW for 2023-11-03\n", 367 | "Retrieving data for CARR for 2023-11-03\n", 368 | "Retrieving data for HPE for 2023-11-10\n", 369 | "Retrieving data for SPR for 2023-11-03\n", 370 | "Retrieving data for HPE for 2023-11-03\n", 371 | "Retrieving data for BPOP for 2023-11-03\n", 372 | "Retrieving data for CAG for 2023-11-03\n", 373 | "Getting data using port 4002 and clientId 1\n", 374 | "Getting data using port 4002 and clientId 0\n", 375 | "Retrieving data for ADP for 2023-12-01\n", 376 | "Retrieving data for AN for 2023-12-01\n", 377 | "Getting data using port 4004 and clientId 1\n", 378 | "Retrieving data for PCTY for 2023-12-01\n", 379 | "Retrieving data for DLB for 2023-11-10\n", 380 | "Getting data using port 4003 and clientId 0\n", 381 | "Retrieving data for FCNCA for 2023-12-01\n", 382 | "Retrieving data for DLB for 2023-11-03\n", 383 | "Retrieving data for AN for 2023-11-24\n", 384 | "Retrieving data for FCNCA for 2023-11-24\n", 385 | "Getting data using port 4004 and clientId 0\n", 386 | "Retrieving data for QDEL for 2023-12-01\n", 387 | "Retrieving data for ADP for 2023-11-24\n", 388 | "Retrieving data for PCTY for 2023-11-24\n", 389 | "Getting data using port 4001 and clientId 0\n", 390 | "Retrieving data for GRMN for 2023-12-01\n", 391 | "Getting data using port 4003 and clientId 1\n", 392 | "Retrieving data for CNHI for 2023-12-01\n", 393 | "Retrieving data for FCNCA for 2023-11-17\n", 394 | "Retrieving data for AN for 2023-11-17\n", 395 | "Retrieving data for QDEL for 2023-11-24\n", 396 | "Getting data using port 4001 and clientId 1\n", 397 | "Retrieving data for BBWI for 2023-12-01\n", 398 | "Retrieving data for ADP for 2023-11-17\n", 399 | "Retrieving data for GRMN for 2023-11-24\n", 400 | "Retrieving data for CNHI for 2023-11-24\n", 401 | "Retrieving data for PCTY for 2023-11-17\n", 402 | "Retrieving data for QDEL for 2023-11-17\n", 403 | "Retrieving data for GRMN for 2023-11-17\n", 404 | "Retrieving data for CNHI for 2023-11-17\n", 405 | "Retrieving data for FCNCA for 2023-11-10\n", 406 | "Retrieving data for ADP for 2023-11-10\n", 407 | "Retrieving data for AN for 2023-11-10\n", 408 | "Retrieving data for PCTY for 2023-11-10\n", 409 | "Retrieving data for BBWI for 2023-11-24\n", 410 | "Retrieving data for ADP for 2023-11-03\n", 411 | "Retrieving data for PCTY for 2023-11-03\n", 412 | "Retrieving data for BBWI for 2023-11-17\n", 413 | "Retrieving data for CNHI for 2023-11-10\n", 414 | "Retrieving data for AN for 2023-11-03\n", 415 | "Retrieving data for GRMN for 2023-11-10\n", 416 | "Retrieving data for BBWI for 2023-11-10\n", 417 | "Retrieving data for FCNCA for 2023-11-03\n" 418 | ] 419 | }, 420 | { 421 | "name": "stderr", 422 | "output_type": "stream", 423 | "text": [ 424 | "reqHistoricalData: Timeout for Stock(conId=564701585, symbol='QDEL', exchange='SMART', primaryExchange='NASDAQ', currency='USD', localSymbol='QDEL', tradingClass='NMS')\n", 425 | "Error 162, reqId 2959: Historical Market Data Service error message:API historical data query cancelled: 2959, contract: Stock(conId=564701585, symbol='QDEL', exchange='SMART', primaryExchange='NASDAQ', currency='USD', localSymbol='QDEL', tradingClass='NMS')\n" 426 | ] 427 | }, 428 | { 429 | "name": "stdout", 430 | "output_type": "stream", 431 | "text": [ 432 | "'NoneType' object has no attribute 'set_index'\n", 433 | "No data for 2023-11-17\n", 434 | "Retrieving data for QDEL for 2023-11-16\n" 435 | ] 436 | }, 437 | { 438 | "name": "stderr", 439 | "output_type": "stream", 440 | "text": [ 441 | "Error 162, reqId 332: Historical Market Data Service error message:Trading TWS session is connected from a different IP address, contract: Stock(conId=269174, symbol='FCNCA', exchange='SMART', primaryExchange='NASDAQ', currency='USD', localSymbol='FCNCA', tradingClass='NMS')\n", 442 | "Error 162, reqId 103: Historical Market Data Service error message:Trading TWS session is connected from a different IP address, contract: Stock(conId=135330258, symbol='CNHI', exchange='SMART', primaryExchange='NYSE', currency='USD', localSymbol='CNHI', tradingClass='CNHI')\n" 443 | ] 444 | }, 445 | { 446 | "name": "stdout", 447 | "output_type": "stream", 448 | "text": [ 449 | "Getting data using port 4004 and clientId 1\n", 450 | "'NoneType' object has no attribute 'set_index'\n", 451 | "No data for 2023-11-03\n", 452 | "Retrieving data for FCNCA for 2023-11-02\n", 453 | "'NoneType' object has no attribute 'set_index'\n", 454 | "No data for 2023-11-10\n", 455 | "Retrieving data for CNHI for 2023-11-09\n" 456 | ] 457 | }, 458 | { 459 | "name": "stderr", 460 | "output_type": "stream", 461 | "text": [ 462 | "Error 162, reqId 333: Historical Market Data Service error message:Trading TWS session is connected from a different IP address, contract: Stock(conId=269174, symbol='FCNCA', exchange='SMART', primaryExchange='NASDAQ', currency='USD', localSymbol='FCNCA', tradingClass='NMS')\n", 463 | "Error 162, reqId 104: Historical Market Data Service error message:Trading TWS session is connected from a different IP address, contract: Stock(conId=135330258, symbol='CNHI', exchange='SMART', primaryExchange='NYSE', currency='USD', localSymbol='CNHI', tradingClass='CNHI')\n" 464 | ] 465 | }, 466 | { 467 | "name": "stdout", 468 | "output_type": "stream", 469 | "text": [ 470 | "'NoneType' object has no attribute 'set_index'\n", 471 | "No data for 2023-11-02\n", 472 | "Getting data using port 4003 and clientId 0\n", 473 | "'NoneType' object has no attribute 'set_index'\n", 474 | "No data for 2023-11-09\n", 475 | "Retrieving data for CB for 2023-12-01\n", 476 | "Getting data using port 4003 and clientId 1\n", 477 | "Retrieving data for FBIN for 2023-12-01\n", 478 | "Retrieving data for AIRC for 2023-12-01\n" 479 | ] 480 | }, 481 | { 482 | "name": "stderr", 483 | "output_type": "stream", 484 | "text": [ 485 | "Error 162, reqId 335: Historical Market Data Service error message:Trading TWS session is connected from a different IP address, contract: Stock(conId=94078796, symbol='FBIN', exchange='SMART', primaryExchange='NYSE', currency='USD', localSymbol='FBIN', tradingClass='FBIN')\n", 486 | "Error 162, reqId 106: Historical Market Data Service error message:Trading TWS session is connected from a different IP address, contract: Stock(conId=458022306, symbol='AIRC', exchange='SMART', primaryExchange='NYSE', currency='USD', localSymbol='AIRC', tradingClass='AIRC')\n" 487 | ] 488 | }, 489 | { 490 | "name": "stdout", 491 | "output_type": "stream", 492 | "text": [ 493 | "'NoneType' object has no attribute 'set_index'\n", 494 | "No data for 2023-12-01\n", 495 | "Retrieving data for FBIN for 2023-11-30\n", 496 | "'NoneType' object has no attribute 'set_index'\n", 497 | "No data for 2023-12-01\n", 498 | "Retrieving data for AIRC for 2023-11-30\n" 499 | ] 500 | }, 501 | { 502 | "name": "stderr", 503 | "output_type": "stream", 504 | "text": [ 505 | "Error 162, reqId 336: Historical Market Data Service error message:Trading TWS session is connected from a different IP address, contract: Stock(conId=94078796, symbol='FBIN', exchange='SMART', primaryExchange='NYSE', currency='USD', localSymbol='FBIN', tradingClass='FBIN')\n", 506 | "Error 162, reqId 107: Historical Market Data Service error message:Trading TWS session is connected from a different IP address, contract: Stock(conId=458022306, symbol='AIRC', exchange='SMART', primaryExchange='NYSE', currency='USD', localSymbol='AIRC', tradingClass='AIRC')\n" 507 | ] 508 | }, 509 | { 510 | "name": "stdout", 511 | "output_type": "stream", 512 | "text": [ 513 | "'NoneType' object has no attribute 'set_index'\n", 514 | "No data for 2023-11-30\n", 515 | "No objects to concatenate\n", 516 | "'NoneType' object has no attribute 'set_index'\n", 517 | "No data for 2023-11-30\n", 518 | "No objects to concatenate\n", 519 | "Getting data using port 4002 and clientId 0\n", 520 | "Getting data using port 4002 and clientId 1\n", 521 | "Retrieving data for FTNT for 2023-12-01\n", 522 | "Retrieving data for YUM for 2023-12-01\n", 523 | "Retrieving data for QDEL for 2023-11-09\n", 524 | "Retrieving data for GRMN for 2023-11-03\n", 525 | "Retrieving data for CB for 2023-11-24\n", 526 | "Retrieving data for BBWI for 2023-11-03\n", 527 | "Getting data using port 4001 and clientId 1\n", 528 | "Retrieving data for TECH for 2023-12-01\n", 529 | "Retrieving data for YUM for 2023-11-24\n", 530 | "Retrieving data for FTNT for 2023-11-24\n", 531 | "Retrieving data for CB for 2023-11-17\n", 532 | "Retrieving data for QDEL for 2023-11-02\n", 533 | "Retrieving data for YUM for 2023-11-17\n", 534 | "Getting data using port 4001 and clientId 0\n", 535 | "Retrieving data for WAL for 2023-12-01\n", 536 | "Retrieving data for FTNT for 2023-11-17\n", 537 | "Retrieving data for TECH for 2023-11-24\n", 538 | "Getting data using port 4004 and clientId 0\n", 539 | "Retrieving data for GGG for 2023-12-01\n", 540 | "Retrieving data for CB for 2023-11-10\n", 541 | "Retrieving data for YUM for 2023-11-10\n", 542 | "Retrieving data for WAL for 2023-11-24\n", 543 | "Retrieving data for CB for 2023-11-03\n", 544 | "Retrieving data for TECH for 2023-11-17\n", 545 | "Retrieving data for WAL for 2023-11-17\n", 546 | "Retrieving data for YUM for 2023-11-03\n", 547 | "Retrieving data for FTNT for 2023-11-10\n", 548 | "Retrieving data for GGG for 2023-11-24\n", 549 | "Getting data using port 4004 and clientId 1\n", 550 | "Retrieving data for AVGO for 2023-12-01\n", 551 | "Retrieving data for WAL for 2023-11-10\n", 552 | "Retrieving data for FTNT for 2023-11-03\n", 553 | "Retrieving data for GGG for 2023-11-17\n", 554 | "Retrieving data for TECH for 2023-11-10\n", 555 | "Retrieving data for WAL for 2023-11-03\n", 556 | "Getting data using port 4002 and clientId 1\n", 557 | "Getting data using port 4002 and clientId 0\n", 558 | "Retrieving data for VFC for 2023-12-01\n", 559 | "Retrieving data for BIIB for 2023-12-01\n", 560 | "Retrieving data for GGG for 2023-11-10\n", 561 | "Retrieving data for AVGO for 2023-11-24\n", 562 | "Retrieving data for VFC for 2023-11-24\n", 563 | "Retrieving data for TECH for 2023-11-03\n", 564 | "Getting data using port 4001 and clientId 0\n", 565 | "Retrieving data for ZG for 2023-12-01\n", 566 | "Retrieving data for GGG for 2023-11-03\n", 567 | "Retrieving data for ZG for 2023-11-24\n", 568 | "Retrieving data for VFC for 2023-11-17\n", 569 | "Retrieving data for BIIB for 2023-11-24\n", 570 | "Retrieving data for AVGO for 2023-11-17\n", 571 | "Getting data using port 4004 and clientId 0\n", 572 | "Retrieving data for T for 2023-12-01\n" 573 | ] 574 | } 575 | ], 576 | "source": [ 577 | "for thread in threads:\n", 578 | " thread.join()" 579 | ] 580 | }, 581 | { 582 | "cell_type": "code", 583 | "execution_count": null, 584 | "id": "8076d2c0", 585 | "metadata": {}, 586 | "outputs": [], 587 | "source": [] 588 | } 589 | ], 590 | "metadata": { 591 | "kernelspec": { 592 | "display_name": "py310", 593 | "language": "python", 594 | "name": "py310" 595 | }, 596 | "language_info": { 597 | "codemirror_mode": { 598 | "name": "ipython", 599 | "version": 3 600 | }, 601 | "file_extension": ".py", 602 | "mimetype": "text/x-python", 603 | "name": "python", 604 | "nbconvert_exporter": "python", 605 | "pygments_lexer": "ipython3", 606 | "version": "3.10.13" 607 | } 608 | }, 609 | "nbformat": 4, 610 | "nbformat_minor": 5 611 | } 612 | -------------------------------------------------------------------------------- /Alpaca/TradingStream.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "id": "view-in-github", 7 | "colab_type": "text" 8 | }, 9 | "source": [ 10 | "\"Open" 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "metadata": { 16 | "id": "WBFiHh7B4i6Q" 17 | }, 18 | "source": [ 19 | "# Setup\n", 20 | "\n", 21 | "### Install Python SDK\n" 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": 20, 27 | "metadata": { 28 | "colab": { 29 | "base_uri": "https://localhost:8080/" 30 | }, 31 | "id": "hOR_HPraHxRC", 32 | "outputId": "24b16eb3-e205-4aa2-c333-795dd6a7973a" 33 | }, 34 | "outputs": [ 35 | { 36 | "output_type": "stream", 37 | "name": "stdout", 38 | "text": [ 39 | "Requirement already satisfied: alpaca-py in /usr/local/lib/python3.11/dist-packages (0.40.0)\n", 40 | "Requirement already satisfied: msgpack<2.0.0,>=1.0.3 in /usr/local/lib/python3.11/dist-packages (from alpaca-py) (1.1.0)\n", 41 | "Requirement already satisfied: pandas>=1.5.3 in /usr/local/lib/python3.11/dist-packages (from alpaca-py) (2.2.2)\n", 42 | "Requirement already satisfied: pydantic<3.0.0,>=2.0.3 in /usr/local/lib/python3.11/dist-packages (from alpaca-py) (2.11.4)\n", 43 | "Requirement already satisfied: requests<3.0.0,>=2.30.0 in /usr/local/lib/python3.11/dist-packages (from alpaca-py) (2.32.3)\n", 44 | "Requirement already satisfied: sseclient-py<2.0.0,>=1.7.2 in /usr/local/lib/python3.11/dist-packages (from alpaca-py) (1.8.0)\n", 45 | "Requirement already satisfied: websockets>=10.4 in /usr/local/lib/python3.11/dist-packages (from alpaca-py) (15.0.1)\n", 46 | "Requirement already satisfied: numpy>=1.23.2 in /usr/local/lib/python3.11/dist-packages (from pandas>=1.5.3->alpaca-py) (2.0.2)\n", 47 | "Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.11/dist-packages (from pandas>=1.5.3->alpaca-py) (2.9.0.post0)\n", 48 | "Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.11/dist-packages (from pandas>=1.5.3->alpaca-py) (2025.2)\n", 49 | "Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.11/dist-packages (from pandas>=1.5.3->alpaca-py) (2025.2)\n", 50 | "Requirement already satisfied: annotated-types>=0.6.0 in /usr/local/lib/python3.11/dist-packages (from pydantic<3.0.0,>=2.0.3->alpaca-py) (0.7.0)\n", 51 | "Requirement already satisfied: pydantic-core==2.33.2 in /usr/local/lib/python3.11/dist-packages (from pydantic<3.0.0,>=2.0.3->alpaca-py) (2.33.2)\n", 52 | "Requirement already satisfied: typing-extensions>=4.12.2 in /usr/local/lib/python3.11/dist-packages (from pydantic<3.0.0,>=2.0.3->alpaca-py) (4.13.2)\n", 53 | "Requirement already satisfied: typing-inspection>=0.4.0 in /usr/local/lib/python3.11/dist-packages (from pydantic<3.0.0,>=2.0.3->alpaca-py) (0.4.0)\n", 54 | "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.11/dist-packages (from requests<3.0.0,>=2.30.0->alpaca-py) (3.4.2)\n", 55 | "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.11/dist-packages (from requests<3.0.0,>=2.30.0->alpaca-py) (3.10)\n", 56 | "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.11/dist-packages (from requests<3.0.0,>=2.30.0->alpaca-py) (2.4.0)\n", 57 | "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.11/dist-packages (from requests<3.0.0,>=2.30.0->alpaca-py) (2025.4.26)\n", 58 | "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.11/dist-packages (from python-dateutil>=2.8.2->pandas>=1.5.3->alpaca-py) (1.17.0)\n" 59 | ] 60 | } 61 | ], 62 | "source": [ 63 | "!pip install alpaca-py" 64 | ] 65 | }, 66 | { 67 | "cell_type": "markdown", 68 | "metadata": { 69 | "id": "YksmyNWk45op" 70 | }, 71 | "source": [ 72 | "### Grab API key and Secret" 73 | ] 74 | }, 75 | { 76 | "cell_type": "code", 77 | "execution_count": 21, 78 | "metadata": { 79 | "id": "gNadZhiAH0Cz" 80 | }, 81 | "outputs": [], 82 | "source": [ 83 | "from google.colab import userdata\n", 84 | "ALPACA_API_KEY = userdata.get('ALPACA_API_KEY')\n", 85 | "ALPACA_API_SECRET = userdata.get('ALPACA_API_SECRET')" 86 | ] 87 | }, 88 | { 89 | "cell_type": "markdown", 90 | "metadata": { 91 | "id": "sHtVhd4248FR" 92 | }, 93 | "source": [ 94 | "### Connect to Trading Client" 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "execution_count": 22, 100 | "metadata": { 101 | "id": "S-1nNEljH3Kw" 102 | }, 103 | "outputs": [], 104 | "source": [ 105 | "from alpaca.trading.client import TradingClient\n", 106 | "trading_client = TradingClient(ALPACA_API_KEY, ALPACA_API_SECRET, paper=True)" 107 | ] 108 | }, 109 | { 110 | "cell_type": "markdown", 111 | "metadata": { 112 | "id": "zTKCQC8_GP9P" 113 | }, 114 | "source": [ 115 | "### Nest_Asnycio\n", 116 | "* Needed for running asyncio in Jupyter Credit Ewald De Wit!" 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "execution_count": 24, 122 | "metadata": { 123 | "id": "6IppPUq9D2kD" 124 | }, 125 | "outputs": [], 126 | "source": [ 127 | "import nest_asyncio\n", 128 | "nest_asyncio.apply()" 129 | ] 130 | }, 131 | { 132 | "cell_type": "markdown", 133 | "metadata": { 134 | "id": "P88J6XKN64m4" 135 | }, 136 | "source": [ 137 | "# Trading Stream\n", 138 | "\n", 139 | "### Where we can handle events related to orders we placed.\n", 140 | "For example,\n", 141 | "* New Order\n", 142 | "* Replaced Order\n", 143 | "* Filled Order\n", 144 | "\n", 145 | "### Initialize Trading Stream" 146 | ] 147 | }, 148 | { 149 | "cell_type": "code", 150 | "execution_count": 25, 151 | "metadata": { 152 | "id": "0W6B5FfP66yw" 153 | }, 154 | "outputs": [], 155 | "source": [ 156 | "from alpaca.trading.stream import TradingStream\n", 157 | "trading_stream = TradingStream(ALPACA_API_KEY, ALPACA_API_SECRET)" 158 | ] 159 | }, 160 | { 161 | "cell_type": "markdown", 162 | "metadata": { 163 | "id": "7c2Ia5CBXiqv" 164 | }, 165 | "source": [ 166 | "### Example 1: Very Basic Example of TradingStream Couroutine" 167 | ] 168 | }, 169 | { 170 | "cell_type": "code", 171 | "source": [ 172 | "??TradeUpdate\n", 173 | "??TradeEvent" 174 | ], 175 | "metadata": { 176 | "id": "6DxmlO9vz59a" 177 | }, 178 | "execution_count": 28, 179 | "outputs": [] 180 | }, 181 | { 182 | "cell_type": "code", 183 | "source": [ 184 | "from alpaca.trading.models import TradeUpdate\n", 185 | "from alpaca.trading.enums import OrderStatus, OrderSide,TradeEvent\n", 186 | "from alpaca.trading.requests import LimitOrderRequest\n", 187 | "from alpaca.trading.enums import TimeInForce\n", 188 | "import numpy as np\n", 189 | "\n", 190 | "trading_stream = TradingStream(ALPACA_API_KEY, ALPACA_API_SECRET)\n", 191 | "\n", 192 | "async def on_order_update(trade_update:TradeUpdate):\n", 193 | " order_id = trade_update.order.id\n", 194 | " side = trade_update.order.side\n", 195 | " event = trade_update.event\n", 196 | " price = trade_update.price\n", 197 | " qty = trade_update.qty\n", 198 | " timestamp = trade_update.timestamp\n", 199 | " print(f\"OrderId: {order_id}\")\n", 200 | " print(f\"Timestamp: {timestamp}\")\n", 201 | " print(f\"Side: {side}\")\n", 202 | " print(f\"Event: {event}\")\n", 203 | " print(f\"Price: {price}\")\n", 204 | " print(f\"Qty: {qty}\")\n", 205 | "\n" 206 | ], 207 | "metadata": { 208 | "id": "EE4-Z0glzb1S" 209 | }, 210 | "execution_count": 29, 211 | "outputs": [] 212 | }, 213 | { 214 | "cell_type": "markdown", 215 | "metadata": { 216 | "id": "kmVE3zILdWxh" 217 | }, 218 | "source": [ 219 | "### Subscribe to \"Trade\" Updates\n", 220 | "**Note** I wish they could rename it because this can be confusing from market data trade updates..." 221 | ] 222 | }, 223 | { 224 | "cell_type": "code", 225 | "execution_count": 30, 226 | "metadata": { 227 | "id": "Or_NSauUGMsM" 228 | }, 229 | "outputs": [], 230 | "source": [ 231 | "trading_stream.subscribe_trade_updates(on_order_update)" 232 | ] 233 | }, 234 | { 235 | "cell_type": "markdown", 236 | "metadata": { 237 | "id": "xGFI0T168t4_" 238 | }, 239 | "source": [ 240 | "### Run the Websocket Stream\n", 241 | "* This is blocking later we can try the \"non-blocking\" version." 242 | ] 243 | }, 244 | { 245 | "cell_type": "code", 246 | "execution_count": 31, 247 | "metadata": { 248 | "id": "02c7vxdHGNDI", 249 | "outputId": "6c9adab8-bcef-46ae-9074-e6bc28231f48", 250 | "colab": { 251 | "base_uri": "https://localhost:8080/" 252 | } 253 | }, 254 | "outputs": [ 255 | { 256 | "output_type": "stream", 257 | "name": "stdout", 258 | "text": [ 259 | "OrderId: 2732ad45-433b-49fc-b6fd-ffee1f932044\n", 260 | "Timestamp: 2025-05-16 11:21:58.683150+00:00\n", 261 | "Side: OrderSide.BUY\n", 262 | "Event: canceled\n", 263 | "Price: None\n", 264 | "Qty: None\n", 265 | "OrderId: a480f13d-f447-4bb8-abd9-d604ae2b83e7\n", 266 | "Timestamp: 2025-05-16 11:21:58.686700+00:00\n", 267 | "Side: OrderSide.BUY\n", 268 | "Event: canceled\n", 269 | "Price: None\n", 270 | "Qty: None\n", 271 | "OrderId: 2e36e34f-735c-4d75-943e-c5f0da41d809\n", 272 | "Timestamp: 2025-05-16 11:23:05.298404+00:00\n", 273 | "Side: OrderSide.BUY\n", 274 | "Event: pending_new\n", 275 | "Price: None\n", 276 | "Qty: None\n", 277 | "OrderId: 2e36e34f-735c-4d75-943e-c5f0da41d809\n", 278 | "Timestamp: 2025-05-16 11:23:05.301936+00:00\n", 279 | "Side: OrderSide.BUY\n", 280 | "Event: new\n", 281 | "Price: None\n", 282 | "Qty: None\n", 283 | "OrderId: 56f978ce-baac-4927-9d03-e41c34fae102\n", 284 | "Timestamp: 2025-05-16 11:23:37.685036+00:00\n", 285 | "Side: OrderSide.BUY\n", 286 | "Event: pending_new\n", 287 | "Price: None\n", 288 | "Qty: None\n", 289 | "OrderId: 56f978ce-baac-4927-9d03-e41c34fae102\n", 290 | "Timestamp: 2025-05-16 11:23:37.690378+00:00\n", 291 | "Side: OrderSide.BUY\n", 292 | "Event: new\n", 293 | "Price: None\n", 294 | "Qty: None\n", 295 | "OrderId: 2a43f40f-d6fe-4d8b-8c06-d22f8b39185a\n", 296 | "Timestamp: 2025-05-16 11:24:10.155066+00:00\n", 297 | "Side: OrderSide.BUY\n", 298 | "Event: pending_new\n", 299 | "Price: None\n", 300 | "Qty: None\n", 301 | "OrderId: 2a43f40f-d6fe-4d8b-8c06-d22f8b39185a\n", 302 | "Timestamp: 2025-05-16 11:24:10.159821+00:00\n", 303 | "Side: OrderSide.BUY\n", 304 | "Event: new\n", 305 | "Price: None\n", 306 | "Qty: None\n", 307 | "OrderId: 2a43f40f-d6fe-4d8b-8c06-d22f8b39185a\n", 308 | "Timestamp: 2025-05-16 11:24:10.379012+00:00\n", 309 | "Side: OrderSide.BUY\n", 310 | "Event: partial_fill\n", 311 | "Price: 118.41\n", 312 | "Qty: 6.0\n", 313 | "OrderId: 2a43f40f-d6fe-4d8b-8c06-d22f8b39185a\n", 314 | "Timestamp: 2025-05-16 11:24:10.524544+00:00\n", 315 | "Side: OrderSide.BUY\n", 316 | "Event: partial_fill\n", 317 | "Price: 118.41\n", 318 | "Qty: 1.445232666\n", 319 | "OrderId: 2a43f40f-d6fe-4d8b-8c06-d22f8b39185a\n", 320 | "Timestamp: 2025-05-16 11:24:10.522413+00:00\n", 321 | "Side: OrderSide.BUY\n", 322 | "Event: fill\n", 323 | "Price: 118.41\n", 324 | "Qty: 1.0\n", 325 | "OrderId: 9d9bea5a-8114-4570-8c39-7718b46f37bd\n", 326 | "Timestamp: 2025-05-16 11:26:02.111320+00:00\n", 327 | "Side: OrderSide.BUY\n", 328 | "Event: pending_new\n", 329 | "Price: None\n", 330 | "Qty: None\n", 331 | "OrderId: 9d9bea5a-8114-4570-8c39-7718b46f37bd\n", 332 | "Timestamp: 2025-05-16 11:26:02.115710+00:00\n", 333 | "Side: OrderSide.BUY\n", 334 | "Event: new\n", 335 | "Price: None\n", 336 | "Qty: None\n", 337 | "OrderId: 9d9bea5a-8114-4570-8c39-7718b46f37bd\n", 338 | "Timestamp: 2025-05-16 11:26:02.208366+00:00\n", 339 | "Side: OrderSide.BUY\n", 340 | "Event: partial_fill\n", 341 | "Price: 118.45\n", 342 | "Qty: 4.0\n", 343 | "OrderId: 9d9bea5a-8114-4570-8c39-7718b46f37bd\n", 344 | "Timestamp: 2025-05-16 11:26:02.366264+00:00\n", 345 | "Side: OrderSide.BUY\n", 346 | "Event: partial_fill\n", 347 | "Price: 118.45\n", 348 | "Qty: 2.0\n", 349 | "OrderId: 9d9bea5a-8114-4570-8c39-7718b46f37bd\n", 350 | "Timestamp: 2025-05-16 11:26:02.544618+00:00\n", 351 | "Side: OrderSide.BUY\n", 352 | "Event: partial_fill\n", 353 | "Price: 118.45\n", 354 | "Qty: 1.442380751\n", 355 | "OrderId: 9d9bea5a-8114-4570-8c39-7718b46f37bd\n", 356 | "Timestamp: 2025-05-16 11:26:02.542283+00:00\n", 357 | "Side: OrderSide.BUY\n", 358 | "Event: fill\n", 359 | "Price: 118.45\n", 360 | "Qty: 1.0\n", 361 | "OrderId: 76915acc-e402-4850-8784-f011bb63029c\n", 362 | "Timestamp: 2025-05-16 11:26:23.897595+00:00\n", 363 | "Side: OrderSide.BUY\n", 364 | "Event: pending_new\n", 365 | "Price: None\n", 366 | "Qty: None\n", 367 | "OrderId: 76915acc-e402-4850-8784-f011bb63029c\n", 368 | "Timestamp: 2025-05-16 11:26:23.901573+00:00\n", 369 | "Side: OrderSide.BUY\n", 370 | "Event: new\n", 371 | "Price: None\n", 372 | "Qty: None\n", 373 | "OrderId: 76915acc-e402-4850-8784-f011bb63029c\n", 374 | "Timestamp: 2025-05-16 11:26:24.006081+00:00\n", 375 | "Side: OrderSide.BUY\n", 376 | "Event: partial_fill\n", 377 | "Price: 118.45\n", 378 | "Qty: 3.0\n", 379 | "OrderId: 76915acc-e402-4850-8784-f011bb63029c\n", 380 | "Timestamp: 2025-05-16 11:26:24.184702+00:00\n", 381 | "Side: OrderSide.BUY\n", 382 | "Event: partial_fill\n", 383 | "Price: 118.45\n", 384 | "Qty: 1.442380751\n", 385 | "OrderId: 76915acc-e402-4850-8784-f011bb63029c\n", 386 | "Timestamp: 2025-05-16 11:26:24.182486+00:00\n", 387 | "Side: OrderSide.BUY\n", 388 | "Event: fill\n", 389 | "Price: 118.45\n", 390 | "Qty: 4.0\n", 391 | "keyboard interrupt, bye\n" 392 | ] 393 | } 394 | ], 395 | "source": [ 396 | "trading_stream.run()" 397 | ] 398 | }, 399 | { 400 | "cell_type": "markdown", 401 | "metadata": { 402 | "id": "aoJNXUs8GEOn" 403 | }, 404 | "source": [ 405 | "### Let's trigger a take profit 1% Higher after a buy fill" 406 | ] 407 | }, 408 | { 409 | "cell_type": "code", 410 | "execution_count": 33, 411 | "metadata": { 412 | "id": "gIcOTp1oJsM6" 413 | }, 414 | "outputs": [], 415 | "source": [ 416 | "from alpaca.trading.models import TradeUpdate\n", 417 | "from alpaca.trading.enums import OrderStatus, OrderSide,TradeEvent\n", 418 | "from alpaca.trading.requests import LimitOrderRequest\n", 419 | "from alpaca.trading.enums import TimeInForce\n", 420 | "import numpy as np\n", 421 | "\n", 422 | "trading_stream = TradingStream(ALPACA_API_KEY, ALPACA_API_SECRET)\n", 423 | "\n", 424 | "async def on_order_update(trade_update:TradeUpdate):\n", 425 | " order_id = trade_update.order.id\n", 426 | " symbol = trade_update.order.symbol\n", 427 | " side = trade_update.order.side\n", 428 | " event = trade_update.event\n", 429 | " price = trade_update.price\n", 430 | " qty = trade_update.qty\n", 431 | " timestamp = trade_update.timestamp\n", 432 | " print(f\"OrderId: {order_id}\")\n", 433 | " print(f\"Symbol: {symbol}\")\n", 434 | " print(f\"Timestamp: {timestamp}\")\n", 435 | " print(f\"Side: {side}\")\n", 436 | " print(f\"Event: {event}\")\n", 437 | " print(f\"Price: {price}\")\n", 438 | " print(f\"Qty: {qty}\")\n", 439 | " if event in [TradeEvent.PARTIAL_FILL,TradeEvent.FILL]:\n", 440 | " take_profit_price = np.round(price * 1.01,2)\n", 441 | " take_profit_qty = qty\n", 442 | " take_profit_side = OrderSide.SELL\n", 443 | " limit_order_request = LimitOrderRequest(\n", 444 | " symbol=symbol,\n", 445 | " qty=take_profit_qty,\n", 446 | " side=take_profit_side,\n", 447 | " limit_price = take_profit_price,\n", 448 | " extended_hours=True,\n", 449 | " time_in_force=TimeInForce.DAY\n", 450 | " )\n", 451 | " take_profit_order = trading_client.submit_order(\n", 452 | " order_data=limit_order_request\n", 453 | " )\n", 454 | " print(f\"Trying to Submit Take Profit Order for {take_profit_qty} shares at {take_profit_price}\")\n", 455 | "\n" 456 | ] 457 | }, 458 | { 459 | "cell_type": "markdown", 460 | "source": [ 461 | "### Subsribe to Trade Updates and Run" 462 | ], 463 | "metadata": { 464 | "id": "Pnl2CNP3F9Mn" 465 | } 466 | }, 467 | { 468 | "cell_type": "code", 469 | "source": [ 470 | "trading_stream.subscribe_trade_updates(on_order_update)\n", 471 | "trading_stream.run()" 472 | ], 473 | "metadata": { 474 | "id": "NehHYaM2nzrH", 475 | "outputId": "ce8325bd-3ac1-4f13-ceba-6c45468553ab", 476 | "colab": { 477 | "base_uri": "https://localhost:8080/" 478 | } 479 | }, 480 | "execution_count": null, 481 | "outputs": [ 482 | { 483 | "output_type": "stream", 484 | "name": "stdout", 485 | "text": [ 486 | "OrderId: 2e36e34f-735c-4d75-943e-c5f0da41d809\n", 487 | "Symbol: AMD\n", 488 | "Timestamp: 2025-05-16 11:34:22.687141+00:00\n", 489 | "Side: OrderSide.BUY\n", 490 | "Event: canceled\n", 491 | "Price: None\n", 492 | "Qty: None\n", 493 | "OrderId: 56f978ce-baac-4927-9d03-e41c34fae102\n", 494 | "Symbol: AMD\n", 495 | "Timestamp: 2025-05-16 11:34:22.702451+00:00\n", 496 | "Side: OrderSide.BUY\n", 497 | "Event: canceled\n", 498 | "Price: None\n", 499 | "Qty: None\n", 500 | "OrderId: 2f9d0e3b-e41f-4970-a5b8-f07928d764c6\n", 501 | "Symbol: AMD\n", 502 | "Timestamp: 2025-05-16 11:35:04.572745+00:00\n", 503 | "Side: OrderSide.BUY\n", 504 | "Event: pending_new\n", 505 | "Price: None\n", 506 | "Qty: None\n", 507 | "OrderId: 2f9d0e3b-e41f-4970-a5b8-f07928d764c6\n", 508 | "Symbol: AMD\n", 509 | "Timestamp: 2025-05-16 11:35:04.576062+00:00\n", 510 | "Side: OrderSide.BUY\n", 511 | "Event: new\n", 512 | "Price: None\n", 513 | "Qty: None\n", 514 | "OrderId: 2f9d0e3b-e41f-4970-a5b8-f07928d764c6\n", 515 | "Symbol: AMD\n", 516 | "Timestamp: 2025-05-16 11:35:04.712641+00:00\n", 517 | "Side: OrderSide.BUY\n", 518 | "Event: partial_fill\n", 519 | "Price: 118.09\n", 520 | "Qty: 1.0\n", 521 | "Trying to Submit Take Profit Order for 1.0 shares at 119.27\n", 522 | "OrderId: 2f9d0e3b-e41f-4970-a5b8-f07928d764c6\n", 523 | "Symbol: AMD\n", 524 | "Timestamp: 2025-05-16 11:35:04.871949+00:00\n", 525 | "Side: OrderSide.BUY\n", 526 | "Event: partial_fill\n", 527 | "Price: 118.09\n", 528 | "Qty: 2.0\n", 529 | "Trying to Submit Take Profit Order for 2.0 shares at 119.27\n", 530 | "OrderId: 2f9d0e3b-e41f-4970-a5b8-f07928d764c6\n", 531 | "Symbol: AMD\n", 532 | "Timestamp: 2025-05-16 11:35:05.058655+00:00\n", 533 | "Side: OrderSide.BUY\n", 534 | "Event: partial_fill\n", 535 | "Price: 118.09\n", 536 | "Qty: 1.468117537\n", 537 | "Trying to Submit Take Profit Order for 1.468117537 shares at 119.27\n", 538 | "OrderId: 2f9d0e3b-e41f-4970-a5b8-f07928d764c6\n", 539 | "Symbol: AMD\n", 540 | "Timestamp: 2025-05-16 11:35:05.056115+00:00\n", 541 | "Side: OrderSide.BUY\n", 542 | "Event: fill\n", 543 | "Price: 118.09\n", 544 | "Qty: 4.0\n", 545 | "Trying to Submit Take Profit Order for 4.0 shares at 119.27\n", 546 | "OrderId: 2e1afd40-e7e8-4482-b542-126642660127\n", 547 | "Symbol: AMD\n", 548 | "Timestamp: 2025-05-16 11:35:05.075999+00:00\n", 549 | "Side: OrderSide.SELL\n", 550 | "Event: pending_new\n", 551 | "Price: None\n", 552 | "Qty: None\n", 553 | "OrderId: 2e1afd40-e7e8-4482-b542-126642660127\n", 554 | "Symbol: AMD\n", 555 | "Timestamp: 2025-05-16 11:35:05.079502+00:00\n", 556 | "Side: OrderSide.SELL\n", 557 | "Event: new\n", 558 | "Price: None\n", 559 | "Qty: None\n", 560 | "OrderId: f1693dc9-8312-4f02-9197-4d2296819efc\n", 561 | "Symbol: AMD\n", 562 | "Timestamp: 2025-05-16 11:35:05.142611+00:00\n", 563 | "Side: OrderSide.SELL\n", 564 | "Event: pending_new\n", 565 | "Price: None\n", 566 | "Qty: None\n", 567 | "OrderId: f1693dc9-8312-4f02-9197-4d2296819efc\n", 568 | "Symbol: AMD\n", 569 | "Timestamp: 2025-05-16 11:35:05.145563+00:00\n", 570 | "Side: OrderSide.SELL\n", 571 | "Event: new\n", 572 | "Price: None\n", 573 | "Qty: None\n", 574 | "OrderId: e22deea3-4085-4006-b5d1-eaa3adffe1a3\n", 575 | "Symbol: AMD\n", 576 | "Timestamp: 2025-05-16 11:35:05.211169+00:00\n", 577 | "Side: OrderSide.SELL\n", 578 | "Event: pending_new\n", 579 | "Price: None\n", 580 | "Qty: None\n", 581 | "OrderId: e22deea3-4085-4006-b5d1-eaa3adffe1a3\n", 582 | "Symbol: AMD\n", 583 | "Timestamp: 2025-05-16 11:35:05.214569+00:00\n", 584 | "Side: OrderSide.SELL\n", 585 | "Event: new\n", 586 | "Price: None\n", 587 | "Qty: None\n", 588 | "OrderId: ff63c883-461b-4a92-972a-cf6273d0b827\n", 589 | "Symbol: AMD\n", 590 | "Timestamp: 2025-05-16 11:35:05.277162+00:00\n", 591 | "Side: OrderSide.SELL\n", 592 | "Event: pending_new\n", 593 | "Price: None\n", 594 | "Qty: None\n", 595 | "OrderId: ff63c883-461b-4a92-972a-cf6273d0b827\n", 596 | "Symbol: AMD\n", 597 | "Timestamp: 2025-05-16 11:35:05.280833+00:00\n", 598 | "Side: OrderSide.SELL\n", 599 | "Event: new\n", 600 | "Price: None\n", 601 | "Qty: None\n" 602 | ] 603 | } 604 | ] 605 | }, 606 | { 607 | "cell_type": "code", 608 | "source": [], 609 | "metadata": { 610 | "id": "X-7evzvr3ygF" 611 | }, 612 | "execution_count": null, 613 | "outputs": [] 614 | } 615 | ], 616 | "metadata": { 617 | "colab": { 618 | "provenance": [], 619 | "authorship_tag": "ABX9TyO+KhStfH/z4gMiZ0Clc9qj", 620 | "include_colab_link": true 621 | }, 622 | "kernelspec": { 623 | "display_name": "Python 3", 624 | "name": "python3" 625 | }, 626 | "language_info": { 627 | "name": "python" 628 | } 629 | }, 630 | "nbformat": 4, 631 | "nbformat_minor": 0 632 | } -------------------------------------------------------------------------------- /old_videos/Watch-List.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "id": "9c39c7cd", 7 | "metadata": {}, 8 | "outputs": [ 9 | { 10 | "name": "stderr", 11 | "output_type": "stream", 12 | "text": [ 13 | "C:\\Users\\adidr\\AppData\\Local\\Temp\\ipykernel_35296\\233690474.py:1: DeprecationWarning: Importing display from IPython.core.display is deprecated since IPython 7.14, please import from IPython display\n", 14 | " from IPython.core.display import display, HTML\n" 15 | ] 16 | }, 17 | { 18 | "data": { 19 | "text/html": [ 20 | "" 21 | ], 22 | "text/plain": [ 23 | "" 24 | ] 25 | }, 26 | "metadata": {}, 27 | "output_type": "display_data" 28 | } 29 | ], 30 | "source": [ 31 | "from IPython.core.display import display, HTML\n", 32 | "display(HTML(\n", 33 | " ''\n", 38 | "))" 39 | ] 40 | }, 41 | { 42 | "cell_type": "markdown", 43 | "id": "d9d5d6e3", 44 | "metadata": {}, 45 | "source": [ 46 | "# Goals\n", 47 | "1. Subscribing to real time market data\n", 48 | "2. Using pendingTickersEvent to handle updates\n", 49 | "3. Display the watchlist!" 50 | ] 51 | }, 52 | { 53 | "cell_type": "markdown", 54 | "id": "769b2997", 55 | "metadata": {}, 56 | "source": [ 57 | "### Connect to IB" 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": 3, 63 | "id": "2852e4d9", 64 | "metadata": {}, 65 | "outputs": [ 66 | { 67 | "data": { 68 | "text/plain": [ 69 | "" 70 | ] 71 | }, 72 | "execution_count": 3, 73 | "metadata": {}, 74 | "output_type": "execute_result" 75 | } 76 | ], 77 | "source": [ 78 | "from ib_insync import *\n", 79 | "util.startLoop()\n", 80 | "ib = IB()\n", 81 | "ib.connect(port=4001,clientId=10)" 82 | ] 83 | }, 84 | { 85 | "cell_type": "code", 86 | "execution_count": 4, 87 | "id": "80023670", 88 | "metadata": {}, 89 | "outputs": [ 90 | { 91 | "data": { 92 | "text/plain": [ 93 | "[3, 2, 1]" 94 | ] 95 | }, 96 | "execution_count": 4, 97 | "metadata": {}, 98 | "output_type": "execute_result" 99 | } 100 | ], 101 | "source": [ 102 | "a=[1,2,3]\n", 103 | "a[::-1]" 104 | ] 105 | }, 106 | { 107 | "cell_type": "markdown", 108 | "id": "a9400979", 109 | "metadata": {}, 110 | "source": [ 111 | "### Subscribe to Market Data" 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": 5, 117 | "id": "b528c370", 118 | "metadata": {}, 119 | "outputs": [], 120 | "source": [ 121 | "contract = Stock(symbol='TSLA',exchange='SMART',currency='USD')\n", 122 | "ib.qualifyContracts(contract)\n", 123 | "ticker = ib.reqMktData(contract,\"\",False,False)" 124 | ] 125 | }, 126 | { 127 | "cell_type": "code", 128 | "execution_count": 6, 129 | "id": "d17ee868", 130 | "metadata": {}, 131 | "outputs": [ 132 | { 133 | "data": { 134 | "text/plain": [ 135 | "nan" 136 | ] 137 | }, 138 | "execution_count": 6, 139 | "metadata": {}, 140 | "output_type": "execute_result" 141 | } 142 | ], 143 | "source": [ 144 | " ticker.high" 145 | ] 146 | }, 147 | { 148 | "cell_type": "markdown", 149 | "id": "1e12989d", 150 | "metadata": {}, 151 | "source": [ 152 | "### Use PendingTickersEvent to handle ticker updates" 153 | ] 154 | }, 155 | { 156 | "cell_type": "code", 157 | "execution_count": 7, 158 | "id": "95e5a973", 159 | "metadata": {}, 160 | "outputs": [], 161 | "source": [ 162 | "def onPendingTickers(tickers):\n", 163 | " for ticker in tickers:\n", 164 | " print(ticker.contract.symbol,ticker.bid,ticker.bidSize,ticker.ask,ticker.askSize,ticker.last,ticker.lastSize)" 165 | ] 166 | }, 167 | { 168 | "cell_type": "markdown", 169 | "id": "22869363", 170 | "metadata": {}, 171 | "source": [ 172 | "### Cancel market data " 173 | ] 174 | }, 175 | { 176 | "cell_type": "code", 177 | "execution_count": 8, 178 | "id": "ee87c420", 179 | "metadata": {}, 180 | "outputs": [], 181 | "source": [ 182 | "ib.cancelMktData(contract)" 183 | ] 184 | }, 185 | { 186 | "cell_type": "markdown", 187 | "id": "f7467a92", 188 | "metadata": {}, 189 | "source": [ 190 | "### Symbols" 191 | ] 192 | }, 193 | { 194 | "cell_type": "code", 195 | "execution_count": 9, 196 | "id": "4cc03d32", 197 | "metadata": {}, 198 | "outputs": [], 199 | "source": [ 200 | "symbol_list = ['TSLA','RIVN','QQQ','BABA','NVDA','META','AAPL']" 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "execution_count": 10, 206 | "id": "762efc84", 207 | "metadata": {}, 208 | "outputs": [], 209 | "source": [ 210 | "for symbol in symbol_list:\n", 211 | " contract = Stock(symbol,exchange='SMART',currency='USD')\n", 212 | " ib.qualifyContracts(contract)\n", 213 | " ticker = ib.reqMktData(contract,\"\",False,False)" 214 | ] 215 | }, 216 | { 217 | "cell_type": "code", 218 | "execution_count": null, 219 | "id": "7822a309", 220 | "metadata": {}, 221 | "outputs": [], 222 | "source": [] 223 | }, 224 | { 225 | "cell_type": "code", 226 | "execution_count": 11, 227 | "id": "db9633c3", 228 | "metadata": {}, 229 | "outputs": [], 230 | "source": [ 231 | "ib.pendingTickersEvent.clear()" 232 | ] 233 | }, 234 | { 235 | "cell_type": "code", 236 | "execution_count": 12, 237 | "id": "71906f06", 238 | "metadata": {}, 239 | "outputs": [], 240 | "source": [ 241 | "previous_trade_prices={symbol:-1 for symbol in symbol_list}\n", 242 | "previous_colors={symbol:'' for symbol in symbol_list}\n", 243 | "def color_row(row):\n", 244 | " color = previous_colors[row.name]\n", 245 | " if row.name in previous_trade_prices:\n", 246 | " if row['lastTradePrice']>previous_trade_prices[row.name]:\n", 247 | " color = 'green'\n", 248 | " elif row['lastTradePrice']\n", 314 | "#T_d69ab th {\n", 315 | " background-color: #ffff99;\n", 316 | " font-size: 16px;\n", 317 | "}\n", 318 | "#T_d69ab td {\n", 319 | " font-size: 16px;\n", 320 | "}\n", 321 | "#T_d69ab td:hover {\n", 322 | " background-color: cyan;\n", 323 | "}\n", 324 | "#T_d69ab_row0_col0, #T_d69ab_row0_col1, #T_d69ab_row0_col2, #T_d69ab_row0_col3, #T_d69ab_row0_col4, #T_d69ab_row0_col5, #T_d69ab_row0_col6, #T_d69ab_row0_col7, #T_d69ab_row0_col8, #T_d69ab_row3_col0, #T_d69ab_row3_col1, #T_d69ab_row3_col2, #T_d69ab_row3_col3, #T_d69ab_row3_col4, #T_d69ab_row3_col5, #T_d69ab_row3_col6, #T_d69ab_row3_col7, #T_d69ab_row3_col8, #T_d69ab_row5_col0, #T_d69ab_row5_col1, #T_d69ab_row5_col2, #T_d69ab_row5_col3, #T_d69ab_row5_col4, #T_d69ab_row5_col5, #T_d69ab_row5_col6, #T_d69ab_row5_col7, #T_d69ab_row5_col8, #T_d69ab_row6_col0, #T_d69ab_row6_col1, #T_d69ab_row6_col2, #T_d69ab_row6_col3, #T_d69ab_row6_col4, #T_d69ab_row6_col5, #T_d69ab_row6_col6, #T_d69ab_row6_col7, #T_d69ab_row6_col8 {\n", 325 | " background-color: ;\n", 326 | "}\n", 327 | "#T_d69ab_row1_col0, #T_d69ab_row1_col1, #T_d69ab_row1_col2, #T_d69ab_row1_col3, #T_d69ab_row1_col4, #T_d69ab_row1_col5, #T_d69ab_row1_col6, #T_d69ab_row1_col7, #T_d69ab_row1_col8, #T_d69ab_row2_col0, #T_d69ab_row2_col1, #T_d69ab_row2_col2, #T_d69ab_row2_col3, #T_d69ab_row2_col4, #T_d69ab_row2_col5, #T_d69ab_row2_col6, #T_d69ab_row2_col7, #T_d69ab_row2_col8, #T_d69ab_row4_col0, #T_d69ab_row4_col1, #T_d69ab_row4_col2, #T_d69ab_row4_col3, #T_d69ab_row4_col4, #T_d69ab_row4_col5, #T_d69ab_row4_col6, #T_d69ab_row4_col7, #T_d69ab_row4_col8 {\n", 328 | " background-color: green;\n", 329 | "}\n", 330 | "\n", 331 | "\n", 332 | " \n", 333 | " \n", 334 | " \n", 335 | " \n", 336 | " \n", 337 | " \n", 338 | " \n", 339 | " \n", 340 | " \n", 341 | " \n", 342 | " \n", 343 | " \n", 344 | " \n", 345 | " \n", 346 | " \n", 347 | " \n", 348 | " \n", 349 | " \n", 350 | " \n", 351 | " \n", 352 | " \n", 353 | " \n", 354 | " \n", 355 | " \n", 356 | " \n", 357 | " \n", 358 | " \n", 359 | " \n", 360 | " \n", 361 | " \n", 362 | " \n", 363 | " \n", 364 | " \n", 365 | " \n", 366 | " \n", 367 | " \n", 368 | " \n", 369 | " \n", 370 | " \n", 371 | " \n", 372 | " \n", 373 | " \n", 374 | " \n", 375 | " \n", 376 | " \n", 377 | " \n", 378 | " \n", 379 | " \n", 380 | " \n", 381 | " \n", 382 | " \n", 383 | " \n", 384 | " \n", 385 | " \n", 386 | " \n", 387 | " \n", 388 | " \n", 389 | " \n", 390 | " \n", 391 | " \n", 392 | " \n", 393 | " \n", 394 | " \n", 395 | " \n", 396 | " \n", 397 | " \n", 398 | " \n", 399 | " \n", 400 | " \n", 401 | " \n", 402 | " \n", 403 | " \n", 404 | " \n", 405 | " \n", 406 | " \n", 407 | " \n", 408 | " \n", 409 | " \n", 410 | " \n", 411 | " \n", 412 | " \n", 413 | " \n", 414 | " \n", 415 | " \n", 416 | " \n", 417 | " \n", 418 | " \n", 419 | " \n", 420 | " \n", 421 | " \n", 422 | " \n", 423 | " \n", 424 | " \n", 425 | " \n", 426 | " \n", 427 | " \n", 428 | " \n", 429 | " \n", 430 | " \n", 431 | " \n", 432 | "
 bidbidSizeaskaskSizelastTradePricelastTradeVolumehighclosePCT_CHANGE
TSLAnannannannannannannannannan
RIVN10.9700003200.00000010.9800006800.00000010.970000200.000000nan11.450000-4.190000
QQQ439.800000800.000000439.810000300.000000439.800000100.000000nan438.0700000.390000
BABA76.300000200.00000076.350000200.00000076.310000100.000000nan76.1200000.250000
NVDA804.600000500.000000804.750000200.000000804.750000500.000000nan785.3800002.470000
METAnannannannannannannannannan
AAPLnannannannannannannannannan
\n" 433 | ], 434 | "text/plain": [ 435 | "" 436 | ] 437 | }, 438 | "metadata": {}, 439 | "output_type": "display_data" 440 | } 441 | ], 442 | "source": [ 443 | "ib.pendingTickersEvent+=onPendingTickersWithStyle" 444 | ] 445 | }, 446 | { 447 | "cell_type": "code", 448 | "execution_count": 17, 449 | "id": "b6360a92", 450 | "metadata": { 451 | "scrolled": true 452 | }, 453 | "outputs": [ 454 | { 455 | "data": { 456 | "text/html": [ 457 | "\n", 475 | "\n", 476 | " \n", 477 | " \n", 478 | " \n", 479 | " \n", 480 | " \n", 481 | " \n", 482 | " \n", 483 | " \n", 484 | " \n", 485 | " \n", 486 | " \n", 487 | " \n", 488 | " \n", 489 | " \n", 490 | " \n", 491 | " \n", 492 | " \n", 493 | " \n", 494 | " \n", 495 | " \n", 496 | " \n", 497 | " \n", 498 | " \n", 499 | " \n", 500 | " \n", 501 | " \n", 502 | " \n", 503 | " \n", 504 | " \n", 505 | " \n", 506 | " \n", 507 | " \n", 508 | " \n", 509 | " \n", 510 | " \n", 511 | " \n", 512 | " \n", 513 | " \n", 514 | " \n", 515 | " \n", 516 | " \n", 517 | " \n", 518 | " \n", 519 | " \n", 520 | " \n", 521 | " \n", 522 | " \n", 523 | " \n", 524 | " \n", 525 | " \n", 526 | " \n", 527 | " \n", 528 | " \n", 529 | " \n", 530 | " \n", 531 | " \n", 532 | " \n", 533 | " \n", 534 | " \n", 535 | " \n", 536 | " \n", 537 | " \n", 538 | " \n", 539 | " \n", 540 | " \n", 541 | " \n", 542 | " \n", 543 | " \n", 544 | " \n", 545 | " \n", 546 | " \n", 547 | " \n", 548 | " \n", 549 | " \n", 550 | " \n", 551 | " \n", 552 | " \n", 553 | " \n", 554 | " \n", 555 | " \n", 556 | " \n", 557 | " \n", 558 | " \n", 559 | " \n", 560 | " \n", 561 | " \n", 562 | " \n", 563 | " \n", 564 | " \n", 565 | " \n", 566 | " \n", 567 | " \n", 568 | " \n", 569 | " \n", 570 | " \n", 571 | " \n", 572 | " \n", 573 | " \n", 574 | " \n", 575 | " \n", 576 | "
 bidbidSizeaskaskSizelastTradePricelastTradeVolumehighclosePCT_CHANGE
TSLA192.270000100.000000192.2900001100.000000192.280000100.000000197.570000197.410000-2.600000
RIVN10.220000103200.00000010.230000126400.00000010.230000100.00000011.02000011.450000-10.660000
QQQ436.960000700.000000436.9700001200.000000436.960000100.000000440.590000438.070000-0.250000
BABA75.920000500.00000075.9300004200.00000075.920000100.00000076.93000076.120000-0.260000
NVDA789.880000300.000000790.090000100.000000789.980000100.000000823.940000785.3800000.590000
META483.840000300.000000483.910000400.000000483.890000100.000000494.360000486.130000-0.460000
AAPL182.5900005800.000000182.600000900.000000182.590000100.000000185.040000184.370000-0.970000
\n" 577 | ], 578 | "text/plain": [ 579 | "" 580 | ] 581 | }, 582 | "metadata": {}, 583 | "output_type": "display_data" 584 | } 585 | ], 586 | "source": [ 587 | "df.style.apply(color_row,axis=1)" 588 | ] 589 | }, 590 | { 591 | "cell_type": "markdown", 592 | "id": "d674392c", 593 | "metadata": {}, 594 | "source": [ 595 | "###### " 596 | ] 597 | }, 598 | { 599 | "cell_type": "code", 600 | "execution_count": null, 601 | "id": "ac4c3f32", 602 | "metadata": {}, 603 | "outputs": [], 604 | "source": [] 605 | }, 606 | { 607 | "cell_type": "code", 608 | "execution_count": null, 609 | "id": "1a871004", 610 | "metadata": {}, 611 | "outputs": [], 612 | "source": [] 613 | }, 614 | { 615 | "cell_type": "code", 616 | "execution_count": null, 617 | "id": "d57fe818", 618 | "metadata": {}, 619 | "outputs": [], 620 | "source": [] 621 | } 622 | ], 623 | "metadata": { 624 | "kernelspec": { 625 | "display_name": "py310", 626 | "language": "python", 627 | "name": "py310" 628 | }, 629 | "language_info": { 630 | "codemirror_mode": { 631 | "name": "ipython", 632 | "version": 3 633 | }, 634 | "file_extension": ".py", 635 | "mimetype": "text/x-python", 636 | "name": "python", 637 | "nbconvert_exporter": "python", 638 | "pygments_lexer": "ipython3", 639 | "version": "3.10.13" 640 | } 641 | }, 642 | "nbformat": 4, 643 | "nbformat_minor": 5 644 | } 645 | -------------------------------------------------------------------------------- /old_videos/hello_dash_actual.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "9a60cd30", 6 | "metadata": {}, 7 | "source": [ 8 | "### Makes width larger for Jupyter notebook" 9 | ] 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": 1, 14 | "id": "2d6da19b", 15 | "metadata": {}, 16 | "outputs": [ 17 | { 18 | "data": { 19 | "text/html": [ 20 | "\n", 21 | "\n" 24 | ], 25 | "text/plain": [ 26 | "" 27 | ] 28 | }, 29 | "execution_count": 1, 30 | "metadata": {}, 31 | "output_type": "execute_result" 32 | } 33 | ], 34 | "source": [ 35 | "from IPython.core.display import HTML,Markdown\n", 36 | "\n", 37 | "HTML(\"\"\"\n", 38 | "\n", 41 | "\"\"\")" 42 | ] 43 | }, 44 | { 45 | "cell_type": "markdown", 46 | "id": "11371444-3f3b-4263-af4a-87388f2e41dc", 47 | "metadata": {}, 48 | "source": [ 49 | "# Goal of Video:\n", 50 | "* Introduce dash \n", 51 | "* Create a simple Yahoo finance dashboard that we will great improve in subsequent videos and eventually turn into a website" 52 | ] 53 | }, 54 | { 55 | "cell_type": "markdown", 56 | "id": "a3c84281-010f-4cd4-ab9e-dde9b7d2dc31", 57 | "metadata": {}, 58 | "source": [ 59 | "### Dash Tutorial\n", 60 | "* Make sure you have latest version of dash so it will work in Jupyter\n", 61 | " - !pip install --upgrade dash\n", 62 | "* Strong Open source + Enterprise Support\n", 63 | "* Limitation of JupyterDash is multipages: https://dash.plotly.com/dash-in-jupyter\n", 64 | "* Examples:\n", 65 | " - https://plotly.com/examples/\n", 66 | "* App Layout\n", 67 | "* Dash Componenets\n", 68 | " - Dash HTML Components (html)\n", 69 | " - i.e. H1 + div\n", 70 | " - Dash Core Components (dcc)\n", 71 | " - i.e. Graph: dcc.graph\n", 72 | " - Dash DataTable (dash_table)\n", 73 | " - dash_table.DataTable\n", 74 | "* Callbacks\n", 75 | "#### NOTE CAN VIEW ON localhost:8050" 76 | ] 77 | }, 78 | { 79 | "cell_type": "markdown", 80 | "id": "b1e39f93-35d5-412c-87c0-8fabc791c7b8", 81 | "metadata": {}, 82 | "source": [ 83 | "- **`

` Tag:**\n", 84 | " - Stands for \"Heading 1.\"\n", 85 | " - Main title of the content.\n", 86 | "- **`
` Tag:**\n", 87 | " - Defines a section/division.\n", 88 | " - Container for HTML elements.\n", 89 | " - No inherent semantic meaning.\n", 90 | " - Groups elements for CSS/JS.\n" 91 | ] 92 | }, 93 | { 94 | "cell_type": "markdown", 95 | "id": "4abdb473-16b0-49ca-8395-76594a42e9f2", 96 | "metadata": { 97 | "tags": [] 98 | }, 99 | "source": [ 100 | "### App Layout\n", 101 | "* Some html element like a div..\n", 102 | "* Div has children which are its elements" 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "execution_count": 2, 108 | "id": "e01f60cd-5e0f-4327-b85d-9e6cd0590ac6", 109 | "metadata": { 110 | "tags": [] 111 | }, 112 | "outputs": [ 113 | { 114 | "data": { 115 | "text/html": [ 116 | "\n", 117 | " \n", 125 | " " 126 | ], 127 | "text/plain": [ 128 | "" 129 | ] 130 | }, 131 | "metadata": {}, 132 | "output_type": "display_data" 133 | } 134 | ], 135 | "source": [ 136 | "from dash import html,Dash\n", 137 | "app = Dash()\n", 138 | "\n", 139 | "app.layout = html.Div(children=[html.H1(\"Trade Mamba\"),\n", 140 | " html.H2(\"Select a Ticker\")\n", 141 | " ])\n", 142 | "\n", 143 | "app.run()" 144 | ] 145 | }, 146 | { 147 | "cell_type": "markdown", 148 | "id": "12e890ac-1268-496a-ae4c-5396e1d11dc9", 149 | "metadata": { 150 | "tags": [] 151 | }, 152 | "source": [ 153 | "### Let's add a dropdown to select a stock \n", 154 | "* Use id to uniquely identify the component which is needed for callbacks" 155 | ] 156 | }, 157 | { 158 | "cell_type": "code", 159 | "execution_count": 3, 160 | "id": "cf91bb26-0e4b-418f-8dcf-cfedf9a727e6", 161 | "metadata": { 162 | "tags": [] 163 | }, 164 | "outputs": [ 165 | { 166 | "data": { 167 | "text/html": [ 168 | "\n", 169 | " \n", 177 | " " 178 | ], 179 | "text/plain": [ 180 | "" 181 | ] 182 | }, 183 | "metadata": {}, 184 | "output_type": "display_data" 185 | } 186 | ], 187 | "source": [ 188 | "from dash import dcc\n", 189 | "symbol_list = ['TSLA','NVDA','AMD','META','RIVN','BABA','SPY','QQQ']\n", 190 | "\n", 191 | "app.layout = html.Div(children=[html.H1(\"Trade Mamba\"),\n", 192 | " html.H2(\"Select a Ticker\"),\n", 193 | " dcc.Dropdown(options=symbol_list,value='SPY',id='stock_picker')\n", 194 | " ])\n", 195 | "app.run()" 196 | ] 197 | }, 198 | { 199 | "cell_type": "markdown", 200 | "id": "5e473ad7-6b0b-4b07-8cb9-ba6eb4bccf32", 201 | "metadata": {}, 202 | "source": [ 203 | "### Let's add a dummy graph\n", 204 | "* We will fill in the graph later via the callback" 205 | ] 206 | }, 207 | { 208 | "cell_type": "code", 209 | "execution_count": 4, 210 | "id": "f0535ed1-233e-46c0-8013-cfd7cf6b133d", 211 | "metadata": { 212 | "tags": [] 213 | }, 214 | "outputs": [ 215 | { 216 | "data": { 217 | "text/html": [ 218 | "\n", 219 | " \n", 227 | " " 228 | ], 229 | "text/plain": [ 230 | "" 231 | ] 232 | }, 233 | "metadata": {}, 234 | "output_type": "display_data" 235 | } 236 | ], 237 | "source": [ 238 | "from dash import dcc\n", 239 | "import plotly.express as px\n", 240 | "\n", 241 | "\n", 242 | "app.layout = html.Div(children=[html.H1(\"Trade Mamba\"),\n", 243 | " html.H2(\"Select a Ticker\"),\n", 244 | " dcc.Dropdown(options=symbol_list,value='SPY',id='stock_picker'),\n", 245 | " dcc.Graph(id='stock-plot')\n", 246 | " ])\n", 247 | "app.run()" 248 | ] 249 | }, 250 | { 251 | "cell_type": "markdown", 252 | "id": "e7d48737-18e0-43b1-bafd-21b9e135dfd3", 253 | "metadata": {}, 254 | "source": [ 255 | "### Let's add dummy data table\n", 256 | "* We will fill in the table later via the callback" 257 | ] 258 | }, 259 | { 260 | "cell_type": "code", 261 | "execution_count": 5, 262 | "id": "c6df3bfa-84cb-40ed-a32d-f47e4e03aaa6", 263 | "metadata": { 264 | "tags": [] 265 | }, 266 | "outputs": [ 267 | { 268 | "data": { 269 | "text/html": [ 270 | "\n", 271 | " \n", 279 | " " 280 | ], 281 | "text/plain": [ 282 | "" 283 | ] 284 | }, 285 | "metadata": {}, 286 | "output_type": "display_data" 287 | } 288 | ], 289 | "source": [ 290 | "from dash import dash_table\n", 291 | "\n", 292 | "app.layout = html.Div(children=[html.H1(\"Trade Mamba\"),\n", 293 | " html.H2(\"Select a Ticker\"),\n", 294 | " dcc.Dropdown(options=symbol_list,value='SPY',id='stock_picker'),\n", 295 | " dcc.Graph(id='stock_plot'),\n", 296 | " dash_table.DataTable(id='data_table',page_size=20,)\n", 297 | " ])\n", 298 | "app.run()" 299 | ] 300 | }, 301 | { 302 | "cell_type": "markdown", 303 | "id": "9bd80451", 304 | "metadata": {}, 305 | "source": [ 306 | "##### Asside: Datable example" 307 | ] 308 | }, 309 | { 310 | "cell_type": "code", 311 | "execution_count": 6, 312 | "id": "1c0cd539", 313 | "metadata": {}, 314 | "outputs": [ 315 | { 316 | "data": { 317 | "text/html": [ 318 | "\n", 319 | " \n", 327 | " " 328 | ], 329 | "text/plain": [ 330 | "" 331 | ] 332 | }, 333 | "metadata": {}, 334 | "output_type": "display_data" 335 | } 336 | ], 337 | "source": [ 338 | "\n", 339 | "from dash import Dash, dash_table\n", 340 | "import pandas as pd\n", 341 | "\n", 342 | "df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv')\n", 343 | "\n", 344 | "app.layout = dash_table.DataTable(data=df.to_dict('records'), columns=[{\"name\": i, \"id\": i} for i in df.columns])\n", 345 | "\n", 346 | "app.run()\n" 347 | ] 348 | }, 349 | { 350 | "cell_type": "markdown", 351 | "id": "ecadc9f9-e2e4-4413-8e8c-da397c03dbd8", 352 | "metadata": {}, 353 | "source": [ 354 | "### Let's add some callbacks to make this make more sense" 355 | ] 356 | }, 357 | { 358 | "cell_type": "markdown", 359 | "id": "352110e6-b17c-479d-a9c2-bad62a304bac", 360 | "metadata": {}, 361 | "source": [ 362 | "##### Assside on getting data from Yahoo Finance with yfinance" 363 | ] 364 | }, 365 | { 366 | "cell_type": "code", 367 | "execution_count": 7, 368 | "id": "f41b3166-63d5-446c-8345-bf9f7412835b", 369 | "metadata": { 370 | "tags": [] 371 | }, 372 | "outputs": [ 373 | { 374 | "name": "stderr", 375 | "output_type": "stream", 376 | "text": [ 377 | "[*********************100%%**********************] 1 of 1 completed\n" 378 | ] 379 | }, 380 | { 381 | "data": { 382 | "text/html": [ 383 | "
\n", 384 | "\n", 397 | "\n", 398 | " \n", 399 | " \n", 400 | " \n", 401 | " \n", 402 | " \n", 403 | " \n", 404 | " \n", 405 | " \n", 406 | " \n", 407 | " \n", 408 | " \n", 409 | " \n", 410 | " \n", 411 | " \n", 412 | " \n", 413 | " \n", 414 | " \n", 415 | " \n", 416 | " \n", 417 | " \n", 418 | " \n", 419 | " \n", 420 | " \n", 421 | " \n", 422 | " \n", 423 | " \n", 424 | " \n", 425 | " \n", 426 | " \n", 427 | " \n", 428 | " \n", 429 | " \n", 430 | " \n", 431 | " \n", 432 | " \n", 433 | " \n", 434 | " \n", 435 | " \n", 436 | " \n", 437 | " \n", 438 | " \n", 439 | " \n", 440 | " \n", 441 | " \n", 442 | " \n", 443 | " \n", 444 | " \n", 445 | " \n", 446 | " \n", 447 | " \n", 448 | " \n", 449 | " \n", 450 | " \n", 451 | " \n", 452 | " \n", 453 | " \n", 454 | " \n", 455 | " \n", 456 | " \n", 457 | " \n", 458 | " \n", 459 | " \n", 460 | " \n", 461 | " \n", 462 | " \n", 463 | " \n", 464 | " \n", 465 | " \n", 466 | " \n", 467 | " \n", 468 | " \n", 469 | " \n", 470 | " \n", 471 | " \n", 472 | " \n", 473 | " \n", 474 | " \n", 475 | " \n", 476 | " \n", 477 | " \n", 478 | " \n", 479 | " \n", 480 | " \n", 481 | " \n", 482 | " \n", 483 | " \n", 484 | " \n", 485 | " \n", 486 | " \n", 487 | " \n", 488 | " \n", 489 | " \n", 490 | " \n", 491 | " \n", 492 | " \n", 493 | " \n", 494 | " \n", 495 | " \n", 496 | " \n", 497 | " \n", 498 | " \n", 499 | " \n", 500 | " \n", 501 | " \n", 502 | " \n", 503 | " \n", 504 | " \n", 505 | " \n", 506 | " \n", 507 | " \n", 508 | " \n", 509 | " \n", 510 | "
DateOpenHighLowCloseVolume
02010-06-291.2666671.6666671.1693331.592667281494500
12010-06-301.7193332.0280001.5533331.588667257806500
22010-07-011.6666671.7280001.3513331.464000123282000
32010-07-021.5333331.5400001.2473331.28000077097000
42010-07-061.3333331.3333331.0553331.074000103003500
.....................
35102024-06-10176.059998178.570007173.169998173.78999350869700
35112024-06-11173.919998174.750000167.410004170.66000464761900
35122024-06-12171.119995180.550003169.800003177.28999390389400
35132024-06-13188.389999191.080002181.229996182.470001118984100
35142024-06-14185.800003186.000000176.919998178.00999581361700
\n", 511 | "

3515 rows × 6 columns

\n", 512 | "
" 513 | ], 514 | "text/plain": [ 515 | " Date Open High Low Close Volume\n", 516 | "0 2010-06-29 1.266667 1.666667 1.169333 1.592667 281494500\n", 517 | "1 2010-06-30 1.719333 2.028000 1.553333 1.588667 257806500\n", 518 | "2 2010-07-01 1.666667 1.728000 1.351333 1.464000 123282000\n", 519 | "3 2010-07-02 1.533333 1.540000 1.247333 1.280000 77097000\n", 520 | "4 2010-07-06 1.333333 1.333333 1.055333 1.074000 103003500\n", 521 | "... ... ... ... ... ... ...\n", 522 | "3510 2024-06-10 176.059998 178.570007 173.169998 173.789993 50869700\n", 523 | "3511 2024-06-11 173.919998 174.750000 167.410004 170.660004 64761900\n", 524 | "3512 2024-06-12 171.119995 180.550003 169.800003 177.289993 90389400\n", 525 | "3513 2024-06-13 188.389999 191.080002 181.229996 182.470001 118984100\n", 526 | "3514 2024-06-14 185.800003 186.000000 176.919998 178.009995 81361700\n", 527 | "\n", 528 | "[3515 rows x 6 columns]" 529 | ] 530 | }, 531 | "execution_count": 7, 532 | "metadata": {}, 533 | "output_type": "execute_result" 534 | } 535 | ], 536 | "source": [ 537 | "import yfinance as yf\n", 538 | "def get_data_from_yfinance(ticker):\n", 539 | " data = yf.download(ticker, period='max', auto_adjust=True)\n", 540 | " data.reset_index(inplace=True)\n", 541 | " return data\n", 542 | "get_data_from_yfinance('TSLA')" 543 | ] 544 | }, 545 | { 546 | "cell_type": "markdown", 547 | "id": "7ae49234-afe1-471d-9244-44b7492c7eae", 548 | "metadata": {}, 549 | "source": [ 550 | "### Callbacks\n", 551 | "* Use @app.callback \n", 552 | "* Must be defined after defining app=Dash()\n", 553 | "* Input: List of Input or Single Input\n", 554 | "* Output: List of Output or Single Output\n", 555 | "* Callback function below it\n", 556 | "* component_id: tells dash what element to work on via the \"id\" field\n", 557 | "* component_property: what property type we are changing" 558 | ] 559 | }, 560 | { 561 | "cell_type": "code", 562 | "execution_count": 14, 563 | "id": "49b888b6-7aa4-4d60-8e9c-76b4380cc426", 564 | "metadata": { 565 | "tags": [] 566 | }, 567 | "outputs": [ 568 | { 569 | "data": { 570 | "text/html": [ 571 | "\n", 572 | " \n", 580 | " " 581 | ], 582 | "text/plain": [ 583 | "" 584 | ] 585 | }, 586 | "metadata": {}, 587 | "output_type": "display_data" 588 | }, 589 | { 590 | "name": "stderr", 591 | "output_type": "stream", 592 | "text": [ 593 | "[*********************100%%**********************] 1 of 1 completed\n", 594 | "[*********************100%%**********************] 1 of 1 completed\n", 595 | "[*********************100%%**********************] 1 of 1 completed\n", 596 | "[*********************100%%**********************] 1 of 1 completed\n" 597 | ] 598 | } 599 | ], 600 | "source": [ 601 | "from dash.dependencies import Output, Input\n", 602 | "\n", 603 | "app = Dash()\n", 604 | "\n", 605 | "@app.callback(\n", 606 | " [Output(component_id='stock_plot',component_property='figure'),\n", 607 | " Output(component_id='data_table',component_property='data'),\n", 608 | " Output(component_id='data_table',component_property='columns')],\n", 609 | " Input(component_id='stock_picker',component_property='value')\n", 610 | ")\n", 611 | "def update_graph(ticker):\n", 612 | " df = get_data_from_yfinance(ticker)\n", 613 | " fig = px.line(data_frame=df,x='Date',y='Close')\n", 614 | " df.sort_values('Date',ascending=False,inplace=True)\n", 615 | " columns=[{\"name\": i, \"id\": i} for i in df.columns]\n", 616 | " data = df.to_dict('records')\n", 617 | " return fig,data,columns\n", 618 | " \n", 619 | "app.layout = html.Div(children=[html.H1(\"Trade Mamba\"),\n", 620 | " html.H2(\"Select a Ticker\"),\n", 621 | " dcc.Dropdown(options=symbol_list,value='SPY',id='stock_picker'),\n", 622 | " dcc.Graph(id='stock_plot'),\n", 623 | " dash_table.DataTable(id='data_table',page_size=20,)\n", 624 | " ])\n", 625 | "\n", 626 | "app.run()" 627 | ] 628 | }, 629 | { 630 | "cell_type": "markdown", 631 | "id": "37f5dd3d-cc2c-4902-9cd0-524824d9f6fd", 632 | "metadata": {}, 633 | "source": [ 634 | "### Let's make tabs one for the chart and one for \n", 635 | "* Use dcc.Tabs\n", 636 | "* label is tab's name" 637 | ] 638 | }, 639 | { 640 | "cell_type": "code", 641 | "execution_count": 16, 642 | "id": "431442ff-ccfa-4542-a160-2607704f70ec", 643 | "metadata": { 644 | "tags": [] 645 | }, 646 | "outputs": [ 647 | { 648 | "data": { 649 | "text/html": [ 650 | "\n", 651 | " \n", 659 | " " 660 | ], 661 | "text/plain": [ 662 | "" 663 | ] 664 | }, 665 | "metadata": {}, 666 | "output_type": "display_data" 667 | }, 668 | { 669 | "name": "stderr", 670 | "output_type": "stream", 671 | "text": [ 672 | "[*********************100%%**********************] 1 of 1 completed\n", 673 | "[*********************100%%**********************] 1 of 1 completed\n" 674 | ] 675 | } 676 | ], 677 | "source": [ 678 | "tabs = dcc.Tabs(children=\n", 679 | " [\n", 680 | " dcc.Tab(label='Chart',children=dcc.Graph(id='stock_plot')),\n", 681 | " dcc.Tab(label='Table',children=dash_table.DataTable(id='data_table',page_size=20,))\n", 682 | " \n", 683 | " ]\n", 684 | " )\n", 685 | "app.layout = html.Div(children=[html.H1(\"Trade Mamba\"),\n", 686 | " html.H2(\"Select a Ticker\"),\n", 687 | " dcc.Dropdown(options=symbol_list,value='SPY',id='stock_picker'),\n", 688 | " tabs\n", 689 | " ])\n", 690 | "\n", 691 | "app.run()" 692 | ] 693 | }, 694 | { 695 | "cell_type": "markdown", 696 | "id": "9cbf61a6-ab91-48db-b881-76ac696797f8", 697 | "metadata": {}, 698 | "source": [ 699 | "### Full App with Style and Color\n", 700 | "* label is usually text label\n", 701 | "* style is where we add the style. We can add it to any dash component like core and html and containers and individual elements" 702 | ] 703 | }, 704 | { 705 | "cell_type": "code", 706 | "execution_count": 18, 707 | "id": "fdd1b3dd-e4ed-428e-b850-1ff3140ff795", 708 | "metadata": { 709 | "tags": [] 710 | }, 711 | "outputs": [ 712 | { 713 | "data": { 714 | "text/html": [ 715 | "\n", 716 | " \n", 724 | " " 725 | ], 726 | "text/plain": [ 727 | "" 728 | ] 729 | }, 730 | "metadata": {}, 731 | "output_type": "display_data" 732 | }, 733 | { 734 | "name": "stderr", 735 | "output_type": "stream", 736 | "text": [ 737 | "[*********************100%%**********************] 1 of 1 completed\n" 738 | ] 739 | } 740 | ], 741 | "source": [ 742 | "from dash import html,Dash,dcc,dash_table\n", 743 | "from dash.dependencies import Input, Output\n", 744 | "import plotly.express as px\n", 745 | "import yfinance as yf\n", 746 | "\n", 747 | "# Assuming get_data_from_yfinance and symbol_list are defined elsewhere\n", 748 | "# from some_module import get_data_from_yfinance, symbol_list\n", 749 | "symbol_list = ['TSLA', 'NVDA', 'AMD', 'META', 'BABA', 'SPY', 'QQQ']\n", 750 | "\n", 751 | "app = Dash()\n", 752 | "\n", 753 | "@app.callback(\n", 754 | " [Output(component_id='stock_plot', component_property='figure'),\n", 755 | " Output(component_id='data_table', component_property='data')],\n", 756 | " [Input(component_id='ticker_selection', component_property='value')]\n", 757 | ")\n", 758 | "def update_graph(ticker):\n", 759 | " dff = get_data_from_yfinance(ticker)\n", 760 | " fig = px.line(dff, x='Date', y='Close')\n", 761 | " fig.update_layout(\n", 762 | " plot_bgcolor='#D1C4E9', # Light purplish background for the plot area\n", 763 | " paper_bgcolor='#E6B0AA', # Light reddish-purple background for the surrounding area\n", 764 | " font=dict(color='#4B0082') # Optional: Adjust the font color for better readability\n", 765 | " )\n", 766 | " dff = dff.sort_values('Date', ascending=False)\n", 767 | " columns = [{\"name\": i, \"id\": i} for i in dff.columns]\n", 768 | " data = dff.to_dict('records')\n", 769 | " return fig, data\n", 770 | "\n", 771 | "def get_data_from_yfinance(ticker):\n", 772 | " data = yf.download(ticker, period='max', auto_adjust=True)\n", 773 | " data.reset_index(inplace=True)\n", 774 | " return data\n", 775 | "\n", 776 | "\n", 777 | "background_style = {\n", 778 | " 'backgroundColor': '#A1887F', # Soft purplish background color\n", 779 | " 'padding': '20px' # Padding around the content\n", 780 | "}\n", 781 | "\n", 782 | "tab_style = {\n", 783 | " 'backgroundColor': '#D1C4E9', # Soft reddish-purple background color\n", 784 | " 'padding': '20px', # Padding around the tab content\n", 785 | " 'border': 'none'\n", 786 | "}\n", 787 | "\n", 788 | "selected_tab_style = {\n", 789 | " 'backgroundColor': '#E6B0AA', # Soft purplish background color for selected tab\n", 790 | " 'padding': '20px', # Padding around the tab content\n", 791 | " 'border': 'none'\n", 792 | "}\n", 793 | "\n", 794 | "data_table_style = {\n", 795 | " 'backgroundColor': '#E6B0AA' # Soft reddish-purple background color for the table\n", 796 | "}\n", 797 | "\n", 798 | "dropdown_style = {\n", 799 | " 'backgroundColor': '#F8BBD0', # Reddish-brown background color \n", 800 | " 'color': '#4B2E2A', # Text color\n", 801 | " 'border': 'none', # No border\n", 802 | " 'padding': '10px', # Padding inside the dropdown\n", 803 | " 'font-size': '16px' # Font size\n", 804 | "}\n", 805 | "\n", 806 | "graph_style = {'backgroundColor': '#E0F7FA'}\n", 807 | " \n", 808 | "\n", 809 | "tabs = dcc.Tabs(children=[ \n", 810 | " dcc.Tab(label='Chart', children=dcc.Graph(id='stock_plot', style=graph_style), style=tab_style, selected_style=selected_tab_style),\n", 811 | " dcc.Tab(\n", 812 | " label='Table', \n", 813 | " children=dash_table.DataTable(\n", 814 | " id='data_table', \n", 815 | " page_size=10, \n", 816 | " style_table={'backgroundColor': '#E6B0AA'}, # Table background color\n", 817 | " style_data={'backgroundColor': '#E6B0AA', 'color': '#4B0082'}, # Data cell background and text color\n", 818 | " style_header={'backgroundColor': '#E0F7FA', 'color': '#4B0082'} # Header cell background and text color\n", 819 | " ), \n", 820 | " style=tab_style, selected_style=selected_tab_style\n", 821 | " )\n", 822 | "])\n", 823 | "\n", 824 | "app.layout = html.Div(style=background_style, children=[\n", 825 | " html.H1(\"Yahoo Finance App\", style={'text-align': 'center'}),\n", 826 | " html.Div(children=[\n", 827 | " html.H2(\"Select a stock\"),\n", 828 | " dcc.Dropdown(options=[{'label': sym, 'value': sym} for sym in symbol_list], id='ticker_selection', value='QQQ',style=dropdown_style),\n", 829 | " tabs\n", 830 | " ])\n", 831 | "\n", 832 | "])\n", 833 | "\n", 834 | "app.run()\n" 835 | ] 836 | }, 837 | { 838 | "cell_type": "code", 839 | "execution_count": null, 840 | "id": "3c8b37c3-092f-4881-ac03-a128239447db", 841 | "metadata": {}, 842 | "outputs": [], 843 | "source": [] 844 | }, 845 | { 846 | "cell_type": "code", 847 | "execution_count": null, 848 | "id": "a9628713", 849 | "metadata": {}, 850 | "outputs": [], 851 | "source": [] 852 | }, 853 | { 854 | "cell_type": "code", 855 | "execution_count": null, 856 | "id": "807fd682", 857 | "metadata": {}, 858 | "outputs": [], 859 | "source": [] 860 | }, 861 | { 862 | "cell_type": "code", 863 | "execution_count": null, 864 | "id": "65c6d05c", 865 | "metadata": {}, 866 | "outputs": [], 867 | "source": [] 868 | }, 869 | { 870 | "cell_type": "code", 871 | "execution_count": null, 872 | "id": "a4d35fd5", 873 | "metadata": {}, 874 | "outputs": [], 875 | "source": [] 876 | }, 877 | { 878 | "cell_type": "code", 879 | "execution_count": null, 880 | "id": "51ff9aee", 881 | "metadata": {}, 882 | "outputs": [], 883 | "source": [] 884 | } 885 | ], 886 | "metadata": { 887 | "kernelspec": { 888 | "display_name": "py310", 889 | "language": "python", 890 | "name": "py310" 891 | }, 892 | "language_info": { 893 | "codemirror_mode": { 894 | "name": "ipython", 895 | "version": 3 896 | }, 897 | "file_extension": ".py", 898 | "mimetype": "text/x-python", 899 | "name": "python", 900 | "nbconvert_exporter": "python", 901 | "pygments_lexer": "ipython3", 902 | "version": "3.10.13" 903 | } 904 | }, 905 | "nbformat": 4, 906 | "nbformat_minor": 5 907 | } 908 | --------------------------------------------------------------------------------