{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "57b7d32b-5db5-44bc-83b7-4b39de81c3e9",
   "metadata": {
    "tags": []
   },
   "source": [
    "# Variables and Data Structures"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "3d49431a-f6ec-4ab4-8481-cb70210d9e24",
   "metadata": {},
   "source": [
    "## Variables (aka 'state variables')"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "5f17e599-7a9a-4355-b4d2-6788478d0451",
   "metadata": {},
   "source": [
    "Variables can be used to keep track of state across ticks. The example below shows how we may keep track of P&L."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a93cd883-9d90-405a-826c-afb4466fc6a7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import onetick.py as otp\n",
    "s = otp.dt(2024, 2, 1, 9, 30)\n",
    "e = otp.dt(2024, 2, 1, 9, 30, 1)\n",
    "\n",
    "trd = otp.Ticks({'PRICE': [13.5, 13.6, 13.3, 14.0],\n",
    "                 'SIZE': [200, 100, 150, 200],\n",
    "                 'SIDE': ['B', 'S', 'B', 'S']})\n",
    "\n",
    "trd.state_vars['PROFIT'] = 0\n",
    "trd.state_vars['PROFIT'] += trd.apply(\n",
    "    lambda t: t['PRICE'] * t['SIZE'] if t['SIDE'] == 'S' else -(t['PRICE'] * t['SIZE'])\n",
    ")\n",
    "\n",
    "trd['PROFIT'] = trd.state_vars['PROFIT']\n",
    "\n",
    "otp.run(trd)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "67ade8dd-9aea-4944-b657-ce448e8ada76",
   "metadata": {},
   "source": [
    "The variable 'PROFIT' keeps a running total. In other words, it aggregates state across trades.\n",
    "\n",
    "Note that the same can be accomplished without variables by keeping the running total in a separate column."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e85c42c1-c38d-47aa-a08c-9fc085bbbc48",
   "metadata": {},
   "outputs": [],
   "source": [
    "trd = otp.Ticks({'PRICE': [13.5, 13.6, 13.3, 14.0],\n",
    "                 'SIZE': [200, 100, 150, 200],\n",
    "                 'SIDE': ['B', 'S', 'B', 'S']})\n",
    "trd['VALUE'] = trd.apply(\n",
    "    lambda t: t['PRICE'] * t['SIZE'] if t['SIDE'] == 'S' else -(t['PRICE'] * t['SIZE'])\n",
    ")\n",
    "trd = trd.agg({'PROFIT': otp.agg.sum('VALUE')}, running=True)\n",
    "otp.run(trd)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "e1d1ee63-7d33-4e89-b848-3ba69f5ca1d7",
   "metadata": {},
   "source": [
    "Below is an example of using variables that cannot be as easily implemented with running totals: remembering the value of the last tick and referring to it after grouping/aggregation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2d3b08e8-c6b3-4bda-bab8-7ea390a683da",
   "metadata": {},
   "outputs": [],
   "source": [
    "q = otp.Ticks(X=[-1, 3, -3, 4, 2], Y=[0, 1, 1, 0, 3])\n",
    "q.state_vars['last_x'] = 0\n",
    "q.state_vars['last_x'] = q['X']\n",
    "q = q.high('X', group_by=['Y'])\n",
    "q['last_x'] = q.state_vars['last_x']\n",
    "otp.run(q)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "58d44336-5591-4d58-8d10-b7c6a5dd4d0a",
   "metadata": {},
   "source": [
    "# Dictionaries / Maps (aka `tick sets`)\n",
    "## Looking up static data for every tick\n",
    "A map can be created with keys taken from one or more columns and holding entire ticks as values.\n",
    "\n",
    "The example below uses exchange reference data to create a map keyed by exchange code."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bcb1eea8-62af-4fce-bde2-acd467f14f0a",
   "metadata": {},
   "outputs": [],
   "source": [
    "exchanges = otp.Ticks(\n",
    "    EXCHANGE=['A', 'B', 'C', 'D', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],\n",
    "    NAME=['NYSE American (Amex)', 'Nasdaq BX', 'NYSE National (NSX)', 'FINRA ADF + NYSE/Nasdaq TRFs', 'MIAX Pearl', 'International Securities Exchange', 'Cboe EDGA', 'Cboe EDGX', 'Long-Term Stock Exchange (LTSE)', 'NYSE Chicago', 'New York Stock Exchange', 'NYSE Arca', 'Nasdaq (Tape C securities)', 'Consolidated Tape System (CTS)', 'Nasdaq (Tape A,B securities)', 'Members Exchange (MEMX)', \"The Investors' Exchange (IEX)\", 'CBOE Stock Exchange (CBSX)', 'Nasdaq PSX', 'Cboe BYX', 'Cboe BZX']\n",
    ")\n",
    "exchanges['LOCATION'] = 'US'\n",
    "otp.run(exchanges)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "eba643c4-04f8-4df7-a8fd-bfc95384f04b",
   "metadata": {},
   "source": [
    "We will add exchange name to trades. First let's examine the trades."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d0aa2e40-266d-4ea5-8fb0-226fb5f46ed0",
   "metadata": {},
   "outputs": [],
   "source": [
    "q = otp.DataSource('US_COMP_SAMPLE', tick_type='TRD')\n",
    "q = q[['PRICE', 'SIZE', 'COND', 'EXCHANGE']]\n",
    "otp.run(q, start=s, end=e, symbols=['AAPL'])"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "4b3d7ba1-c106-4dfa-9e2f-e8a69abfdd0a",
   "metadata": {},
   "source": [
    "The value of the `EXCHANGE` field from trades will be used to look up the name of the corresponding exchange."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ba306745-8c6a-414e-a3d2-3187a4906f9f",
   "metadata": {},
   "outputs": [],
   "source": [
    "q = otp.DataSource('US_COMP_SAMPLE', tick_type='TRD')\n",
    "q = q[['PRICE','SIZE','COND','EXCHANGE']]\n",
    "exchanges = otp.Ticks(\n",
    "    EXCHANGE=['A', 'B', 'C', 'D', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],\n",
    "    NAME=['NYSE American (Amex)', 'Nasdaq BX', 'NYSE National (NSX)', 'FINRA ADF + NYSE/Nasdaq TRFs', 'MIAX Pearl', 'International Securities Exchange', 'Cboe EDGA', 'Cboe EDGX', 'Long-Term Stock Exchange (LTSE)', 'NYSE Chicago', 'New York Stock Exchange', 'NYSE Arca', 'Nasdaq (Tape C securities)', 'Consolidated Tape System (CTS)', 'Nasdaq (Tape A,B securities)', 'Members Exchange (MEMX)', \"The Investors' Exchange (IEX)\", 'CBOE Stock Exchange (CBSX)', 'Nasdaq PSX', 'Cboe BYX', 'Cboe BZX']\n",
    ")\n",
    "\n",
    "q.state_vars['exchanges'] = otp.state.tick_set('latest', 'EXCHANGE', otp.eval(exchanges))\n",
    "q['exchange_name'] = q.state_vars['exchanges'].find('NAME', 'unknown')\n",
    "\n",
    "otp.run(q, start=s, end=e, symbols=['AAPL'])"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "0a0d24b2-5453-4e6f-8467-e0c3c2da06ad",
   "metadata": {},
   "source": [
    "## Checking if ticks are present in another time series\n",
    "A tick set can be used to check if (a small number of) ticks are present in another time series with potentially different time stamps.\n",
    "\n",
    "We generate two \"special\" ticks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "49db461e-fa91-48d2-82e8-f0a57a7216bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "ticks = otp.Ticks(PRICE=[184, 184], SIZE=[1, 2], INDEX=[1, 2])\n",
    "otp.run(ticks)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "aedfb084-06be-4793-a132-fb07289f03ea",
   "metadata": {},
   "source": [
    "We then check if any of the trades match these ticks by ``PRICE`` and ``SIZE``."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6b198189-b8cc-4fda-9610-092696e07a70",
   "metadata": {},
   "outputs": [],
   "source": [
    "q = otp.DataSource('US_COMP_SAMPLE', tick_type='TRD')\n",
    "q = q[['PRICE', 'SIZE', 'COND', 'EXCHANGE']]\n",
    "\n",
    "q.state_vars['special_ticks'] = otp.state.tick_set('latest', ['PRICE', 'SIZE'], otp.eval(ticks))\n",
    "q['SPECIAL'] = q.state_vars['special_ticks'].find('INDEX', -1)\n",
    "\n",
    "q = q.where(q['SPECIAL'] != -1)\n",
    "\n",
    "otp.run(q, start=s, end=e, symbols=['AAPL'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e5d70df",
   "metadata": {},
   "source": [
    "# Lists and Queues\n",
    "Lists and double-ended queues (deques) can be used to keep track of collections ticks.\n",
    "## Lists and Queues Use Cases\n",
    "[Realized P&L (FIFO)](../use_cases/realized_profit.ipynb)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
