{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ad42f7ef",
   "metadata": {},
   "source": [
    "# Data Retrieval"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "1ceb704d-c4cd-4cc3-965a-b8596bde08d0",
   "metadata": {},
   "source": [
    "OneTick is a time series database meaning that each record has a timestamp and timestamps of consecutive records are non-decreasing. Multiple time series are stored in OneTick. An individual time series is identified by the symbol (aka ticker, financial instrument, security), tick type (i.e., the type of data such as trades or quotes), and the name of the database where the time series is stored."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fa14e1fa-a1c7-458b-90f5-4741058ea8ac",
   "metadata": {},
   "outputs": [],
   "source": [
    "import onetick.py as otp\n",
    "\n",
    "s = otp.dt(2024, 2, 1, 9, 30)\n",
    "e = otp.dt(2024, 2, 1, 9, 30, 1)\n",
    "\n",
    "# we can retrieve the list of databases available on the server\n",
    "# (note that not all databases may be readable by your user,\n",
    "#  but the _SAMPLE databases should be)\n",
    "dbs = otp.databases()\n",
    "list(db for db in dbs if db.endswith('_SAMPLE'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "01eb7800-2d4f-43a9-8835-f1062e87bba2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# the list of dates with data for the db\n",
    "dbs['US_COMP_SAMPLE'].dates()[-5:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "90557e70-7808-4df8-9366-92e88a7d1db2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# or just the last day with data\n",
    "dbs['US_COMP_SAMPLE'].last_date"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "39d6e0af-f219-4439-841e-5f39b4ecdbf1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# and the list of tick types\n",
    "dbs['US_COMP_SAMPLE'].tick_types()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad7292a2",
   "metadata": {},
   "source": [
    "OneTick Cloud Standard Tables:\n",
    "| Table    | Description\n",
    "---------- | -----------\n",
    "| DAY      | End of Day Record typically covering Closing Price plus Open Interest for Derivatives Markets\n",
    "| IND      | Indicative Prices occurring during Auction phases\n",
    "| QTE      | Quote Events\n",
    "| STAT     | Static Reference Data for the Instrument\n",
    "| TRD      | Trade Events\n",
    "| NBBO     | National Best Bid & Offer Quotes\n",
    "| PRL      | Book Depth - Market By Level\n",
    "| PRL_FULL | Book Depth - Market by Order\n",
    "| MKTCAL   | Market Holiday & Trading Hours\n",
    "| TRD_1M   | 1 Minute Trade Bar\n",
    "| QTE_1M   | 1 Minute Quote Bar"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "b5e390ca-8396-41ba-97c0-afa0a4427ef8",
   "metadata": {},
   "source": [
    "We can now retrieve symbols traded in a given time range. (In many financial markets, there are properties that remain constant throughout the trading day. Examples include the name of a financial instrument and the set of instruments traded)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fe30bf21-201c-4ac8-949e-3dc13e8e2e48",
   "metadata": {},
   "outputs": [],
   "source": [
    "symbols = otp.Symbols('US_COMP_SAMPLE')\n",
    "otp.run(symbols, start=otp.dt(2024, 2, 1), end=otp.dt(2024, 2, 2))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c19aa09b-4b03-484b-bcf2-c6350c7929ff",
   "metadata": {},
   "source": [
    "We used the {func}`otp.run <onetick.py.run>` method above,\n",
    "which executed a query that retrieved the list of symbols. \n",
    "\n",
    "The start and end timestamps were specified with `onetick-py`'s datetime class\n",
    "{class}`otp.dt <onetick.py.datetime>`."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "63125d3b-b49c-48d7-a173-f4a4816abd80",
   "metadata": {},
   "source": [
    "Now that we have database names, tick types, and symbols, we are ready to query a time series."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d7614b09-c381-406c-8c7b-3f5baaa4c05e",
   "metadata": {},
   "outputs": [],
   "source": [
    "q = otp.DataSource('US_COMP_SAMPLE', tick_type='TRD')\n",
    "otp.run(q, start=s, end=e, symbols=['AAPL'])"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "d051b530-da39-4075-8bcc-7013c78aca86",
   "metadata": {},
   "source": [
    "Note that we specified the start and end of the time series to retrieve the corresponding interval."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5db5680d",
   "metadata": {},
   "source": [
    "\n",
    "```{warning}\n",
    "\n",
    "In {class}`otp.DataSource <onetick.py.DataSource>` default value of the parameter `schema_policy`\n",
    "enables automatic deduction of the data schema.\n",
    "\n",
    "It works fine for simple cases like using `onetick-py` in Jupyter notebooks,\n",
    "but it is highly not recommended for production code.\n",
    "\n",
    "For details see {ref}`static/concepts/schema:Schema deduction mechanism`.\n",
    "```\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c4e0e559-56b7-44f4-958f-15f954c9090c",
   "metadata": {},
   "source": [
    "Let's just keep the columns we're interested in to make it more digestible."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "279f2c52-18fe-41ea-a275-f4f61598dbad",
   "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": "45b2d6d5-8afa-4149-adeb-2d55393e8b03",
   "metadata": {},
   "source": [
    "We can retrieve multiple time series."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "71da7662-31ce-417e-813d-3d52ea785853",
   "metadata": {},
   "outputs": [],
   "source": [
    "q = otp.DataSource('US_COMP_SAMPLE', tick_type='TRD')\n",
    "q = q[['PRICE', 'SIZE', 'COND', 'EXCHANGE']]\n",
    "mult = otp.run(q, start=s, end=e, symbols=['AAPL', 'MSFT'])\n",
    "mult"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "99a8b4f5-e362-4c45-b4cb-6b304fc9de59",
   "metadata": {},
   "source": [
    "Each time series is returned as the value of a dict keyed by the corresponding symbol."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "830d1abd-3134-4b68-9912-808ffa5472cf",
   "metadata": {},
   "outputs": [],
   "source": [
    "mult['MSFT']"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "3c405829-86e9-4d04-849b-b9be60c279c8",
   "metadata": {},
   "source": [
    "We can also retrieve all of the symbols from the database or all of the symbols matching a pattern."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d89dc08b-0ead-4b3d-98ae-442ab9901978",
   "metadata": {},
   "outputs": [],
   "source": [
    "q = otp.DataSource('US_COMP_SAMPLE', tick_type='TRD')\n",
    "q = q[['PRICE', 'SIZE', 'COND', 'EXCHANGE']]\n",
    "mult = otp.run(q, start=s, end=e, symbols=otp.Symbols('US_COMP_SAMPLE', pattern='AA%'))\n",
    "mult"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "409ef584-4ea7-4fcb-8caa-ba64706ba489",
   "metadata": {},
   "source": [
    "We can merge all of the time series by time by using {meth}`otp.merge <onetick.py.merge>` function.\n",
    "\n",
    "Parameter `identify_input_ts` here automatically adds `SYMBOL_NAME` and `TICK_TYPE` columns\n",
    "to the output, so each tick can be identified."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "29e588e6-bf9a-4d4a-9bdd-e40d7a2cf88b",
   "metadata": {},
   "outputs": [],
   "source": [
    "q = otp.DataSource('US_COMP_SAMPLE', tick_type='TRD')\n",
    "q = q[['PRICE', 'SIZE', 'COND', 'EXCHANGE']]\n",
    "q = otp.merge([q], symbols=['AAPL', 'MSFT'], identify_input_ts=True)\n",
    "single = otp.run(q, start=s, end=e)\n",
    "single"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "e5810875-f2e7-401c-8c84-e0afe53370aa",
   "metadata": {},
   "source": [
    "The time range and symbols can be specified directly on the data source. This way we can have different times ranges for difference sources that we can later merge."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "99cf6179-b095-437c-aaef-6ae2c09a668b",
   "metadata": {},
   "outputs": [],
   "source": [
    "q = otp.DataSource('US_COMP_SAMPLE', tick_type='TRD', start=s, end=e, symbols=['AAPL'])\n",
    "otp.run(q)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c20e354f-3a32-41c6-84dc-68a91cd53686",
   "metadata": {},
   "source": [
    "For example, we can get the data from February 24 for AAPL and from March 20 for MSFT."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "180e6b06-06a5-40c5-8ba2-2ba766692ab5",
   "metadata": {},
   "outputs": [],
   "source": [
    "aapl = otp.DataSource('US_COMP_SAMPLE', tick_type='TRD', start=otp.dt(2024, 2, 24, 9, 30), end=otp.dt(2024, 2, 24, 9, 30, 1), symbols=['AAPL'])\n",
    "msft = otp.DataSource('US_COMP_SAMPLE', tick_type='TRD', start=otp.dt(2024, 3, 20, 9, 30), end=otp.dt(2024, 3, 20, 9, 30, 1), symbols=['MSFT'])\n",
    "merged = otp.merge([aapl, msft], identify_input_ts=True)\n",
    "merged = merged[['PRICE', 'SIZE', 'SYMBOL_NAME']]\n",
    "otp.run(merged)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "826dedb9-515b-4278-a1f4-ed89b7f34acc",
   "metadata": {},
   "source": [
    "We can also specify multiple symbols in the data source in which case they will be merged by time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9d78165c-3624-4850-a6a6-21dbb9983c64",
   "metadata": {},
   "outputs": [],
   "source": [
    "q = otp.DataSource('US_COMP_SAMPLE', tick_type='TRD', start=s, end=e, symbols=['AAPL', 'MSFT'])\n",
    "otp.run(q)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "7b7816bf",
   "metadata": {},
   "source": [
    "We can look up  symbols in multiple databases."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "36682b1a",
   "metadata": {},
   "outputs": [],
   "source": [
    "q = otp.DataSource(tick_type='TRD')\n",
    "q = q.table(PRICE=float, SIZE=int)\n",
    "q = otp.merge(q, symbols=['US_COMP_SAMPLE::AAPL', 'TDI_FUT_SAMPLE::ES_r_tdi'], identify_input_ts=True)\n",
    "otp.run(q, start=s, end=e, symbol_date=s)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "8cf5d654",
   "metadata": {},
   "source": [
    "We can also look up the same symbols in different databases (even if they have different tick types)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "461969e1",
   "metadata": {},
   "outputs": [],
   "source": [
    "qte = otp.DataSource('US_COMP_SAMPLE', tick_type='QTE')\n",
    "qte = qte[['BID_PRICE', 'ASK_PRICE']]\n",
    "nbbo = otp.DataSource('US_COMP_SAMPLE', tick_type='NBBO')\n",
    "nbbo = nbbo[['BID_PRICE', 'ASK_PRICE']]\n",
    "\n",
    "q = otp.merge([qte, nbbo], symbols=['AAPL', 'MSFT'], identify_input_ts=True)\n",
    "otp.run(q, start=s, end=s + otp.Milli(1))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "55c84b05",
   "metadata": {},
   "source": [
    "## Generating ticks"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "df671d1f",
   "metadata": {},
   "source": [
    "There are several ways to generate ticks without accessing the database.\n",
    "It's very useful in case you want to check some algorithm fast or to create a test-case.\n",
    "\n",
    "Classes {class}`otp.Tick <onetick.py.Tick>` and {class}`otp.Ticks <onetick.py.Ticks>` can be used for this purpose.\n",
    "\n",
    "{class}`otp.Tick <onetick.py.Tick>` can be used to generate a single tick for the whole time range:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "901d8e59",
   "metadata": {},
   "outputs": [],
   "source": [
    "data = otp.Tick(A=1)\n",
    "data['B'] = 2\n",
    "otp.run(data)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "888a377d",
   "metadata": {},
   "source": [
    "Or to generate ticks with some interval, for example every day:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5ea5d822",
   "metadata": {},
   "outputs": [],
   "source": [
    "data = otp.Tick(A=otp.math.rand(1, 100), bucket_interval=1, bucket_units='days')\n",
    "otp.run(data, start=otp.dt(2024, 2, 1), end=otp.dt(2024, 2, 6))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e0300979",
   "metadata": {},
   "source": [
    "And {class}`otp.Ticks <onetick.py.Ticks>` can be used to generate many ticks with different fixed values:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dbdbf360",
   "metadata": {},
   "outputs": [],
   "source": [
    "data = otp.Ticks({'A': list(range(5)), 'B': ['c', 'd', 'e', 'f', 'g']})\n",
    "otp.run(data)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41af7694",
   "metadata": {},
   "source": [
    "{class}`otp.Ticks <onetick.py.Ticks>` can also be used to generate ticks from `pandas.DataFrame`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b6341dec",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.DataFrame({'Time': [pd.Timestamp(2024, 2, 1, 1, 1, 1), pd.Timestamp(2024, 2, 2, 2, 2, 2)], 'A': [1, 2]})\n",
    "data = otp.LoadTicksFromDataFrame(df)\n",
    "otp.run(data, start=otp.dt(2024, 2, 1), end=otp.dt(2024, 2, 6))"
   ]
  }
 ],
 "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
}
