{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2000b27d-9007-44ad-af8a-8a070d3d0e72",
   "metadata": {},
   "source": [
    "# How to backtest a multi-timeframe strategy"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "44334242-c4cd-4656-987b-7e407ab99c76",
   "metadata": {},
   "source": [
    "Multi-timeframe (MTF) analysis is an essential trading approach that involves analyzing an asset's price in different timeframes."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "208ebc3d-f05a-4f28-95cb-3a26c89583cd",
   "metadata": {},
   "source": [
    "Despite its popularity, MTF analysis comes with several pitfalls when working with arrays, including look-ahead bias and information loss."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0a915599-672d-4609-b800-c3b32c38bcdd",
   "metadata": {},
   "source": [
    "Many native pandas implementations mistakenly assume that events, such as indicator calculations, take place at the same timestamp as the data provided by the exchange, which is typically the opening time of a bar."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b0a48b90-2dbe-4f1a-8924-6cddb8ba9e8c",
   "metadata": {},
   "source": [
    "VBT operates under the assumption that the exact timing of most events is unknown and occurs at some point between the opening (best-case) and closing (worst-case) times of a bar. Consequently, VBT employs a set of features designed to resample data in the most sensitive way, without looking into the future."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e964afe5-96c3-4048-96b8-81ed67bdd138",
   "metadata": {},
   "source": [
    "In today's newsletter, we'll use VectorBT PRO to backtest trading on multiple timeframes simultaneously."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f759738c-4e8e-471b-b668-65962de10b2f",
   "metadata": {},
   "source": [
    "## Imports and set up"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4b057b37-ca17-4430-bec6-58181442610c",
   "metadata": {},
   "source": [
    "In the newer versions of VBT PRO, the star-import (*) loads all the relevant stuff for us, such as `np` for NumPy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "369e2d5c-1daa-4c54-ac86-ab91455b6f75",
   "metadata": {},
   "outputs": [],
   "source": [
    "from vectorbtpro import *"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "efd90f21-1fa5-4c34-b903-73ec2fb5e163",
   "metadata": {},
   "source": [
    "Configure our graphs to be dark and gap-free."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "765bee33-e30a-4dde-ae59-40c0ab5b5b3d",
   "metadata": {},
   "outputs": [],
   "source": [
    "vbt.settings.set_theme(\"dark\")\n",
    "vbt.settings.plotting.auto_rangebreaks = True"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dacf0e6a-061c-4c45-9a2d-edb919cce63e",
   "metadata": {},
   "source": [
    "Grab the data of a higher frequency for your favorite asset. We'll use hourly TSLA."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "16bf34cc-5386-44fa-9af1-7a8969d3f4b9",
   "metadata": {},
   "outputs": [],
   "source": [
    "data = vbt.YFData.pull(\"TSLA\", start=\"2023\", end=\"2024\", timeframe=\"hourly\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4681de1a-5101-4df7-90cf-ceffa53a6112",
   "metadata": {},
   "source": [
    "## Multi-timeframe indicators"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8c7c88cb-43dd-459f-ac82-5a5614e26dd2",
   "metadata": {},
   "source": [
    "Instruct VBT to calculate the fast and slow SMA indicators across multiple timeframes."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad633ac3-6820-4d64-ba6f-8a480f3eaeb8",
   "metadata": {},
   "source": [
    "Under the hood, data is first resampled to the target timeframe; then, the actual TA-Lib indicator is applied exclusively to non-missing values. Finally, the result is realigned back to the original timeframe in a manner that eliminates the possibility of look-ahead bias."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e6780b81-129f-40b3-8708-679c0fc91f29",
   "metadata": {},
   "outputs": [],
   "source": [
    "fast_sma = data.run(\n",
    "    \"talib:sma\", \n",
    "    timeframe=[\"1h\", \"4h\", \"1d\"], \n",
    "    timeperiod=vbt.Default(20),\n",
    "    skipna=True\n",
    ")\n",
    "slow_sma = data.run(\n",
    "    \"talib:sma\", \n",
    "    timeframe=[\"1h\", \"4h\", \"1d\"], \n",
    "    timeperiod=vbt.Default(50),\n",
    "    skipna=True\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d6ad5284-3fc3-4340-b925-28ac252bde69",
   "metadata": {},
   "source": [
    "The result of each call is a DataFrame with three columns, one for each timeframe."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f855ae03-5539-4d4d-8bd3-fe2709a33258",
   "metadata": {},
   "source": [
    "If we plot the DataFrame, we'll observe that the line corresponding to the highest frequency is smooth, whereas the line representing the lowest frequency appears stepped since the indicator values are updated less frequently."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ec9149ca-2c71-4b4a-97e5-6970cd3b0f44",
   "metadata": {},
   "outputs": [],
   "source": [
    "fast_sma.real.vbt.plot().show_svg()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4ac4ea89-6cc9-48e6-91a6-522fd4922279",
   "metadata": {},
   "source": [
    "## Unified portfolio"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "015840e4-cd91-4fb3-97cc-389d39cf9e9d",
   "metadata": {},
   "source": [
    "Next, we'll set up a portfolio in which we go long whenever the fast SMA crosses above the slow SMA and go short when the opposite occurs, across each timeframe."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6d998b85-66d7-4149-8160-ee5fff38dc6f",
   "metadata": {},
   "source": [
    "However, since hourly signals occur more frequently than daily signals, we'll allocate less capital to more frequent signals. For instance, we'll allocate 5% of the equity to hourly signals, 10% to 4-hour signals, and 20% to daily signals."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9aa20269-769d-48ec-ba70-da1c73b508bb",
   "metadata": {},
   "source": [
    "We'll begin with a cash balance of $10,000, shared across all timeframes. Additionally, we'll implement a 20% trailing stop loss (TSL)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8a8eb991-51de-46de-8650-06e1d1c141d2",
   "metadata": {},
   "outputs": [],
   "source": [
    "pf = vbt.PF.from_signals(\n",
    "    data, \n",
    "    long_entries=fast_sma.real_crossed_above(slow_sma), \n",
    "    short_entries=fast_sma.real_crossed_below(slow_sma), \n",
    "    size=[[0.05, 0.1, 0.2]],\n",
    "    size_type=\"valuepercent\",\n",
    "    init_cash=10_000,\n",
    "    group_by=[\"pf\", \"pf\", \"pf\"],\n",
    "    cash_sharing=True,\n",
    "    tsl_stop=0.2\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d613367f-2eab-4b8e-8fb0-3ae9b4c278e6",
   "metadata": {},
   "source": [
    "Plot the cumulative return for each timeframe and compare these to the cumulative return of the entire portfolio."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d39b31f1-3f88-458b-ac20-88ed7c383bdb",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = pf.get_cumulative_returns().vbt.plot(trace_kwargs=dict(line_color=\"gray\", line_dash=\"dot\"))\n",
    "fig = pf.get_cumulative_returns(group_by=False).vbt.plot(fig=fig)\n",
    "fig.show_svg()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9ab33146-d1ac-48ad-bd0b-948c67342dd6",
   "metadata": {},
   "source": [
    "To delve deeper into one of the timeframes, we can plot the indicators alongside the executed trade signals."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5c0f7a7c-8a40-4528-869a-a2ffdfd60735",
   "metadata": {},
   "source": [
    "Here, we can observe that the majority of positions on the daily timeframe were closed out by the TSL."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c0dbd82e-1b70-4373-904f-a023d9983782",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = fast_sma.real.vbt.plot(column=\"1d\", trace_kwargs=dict(name=\"Fast\", line_color=\"limegreen\"))\n",
    "fig = slow_sma.real.vbt.plot(column=\"1d\", trace_kwargs=dict(name=\"Slow\", line_color=\"orangered\"), fig=fig)\n",
    "fig = pf.plot_trade_signals(column=\"1d\", fig=fig)\n",
    "fig.show_svg()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9f1fd30d-a43a-4435-a64c-35eb98c40b6c",
   "metadata": {},
   "source": [
    "## Timeframe product"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "989f08bb-14b2-4630-84a7-126920c69918",
   "metadata": {},
   "source": [
    "Since our MTF indicators share the same index, we can combine one timeframe with another. For instance, we can generate signals from the crossover of two timeframes and identify the pair of timeframes that yield the highest expectancy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "05d70299-4215-49bd-82ec-d52dbc29f678",
   "metadata": {},
   "outputs": [],
   "source": [
    "fast_sma_real = fast_sma.real.vbt.rename_levels({\"sma_timeframe\": \"fast_sma_timeframe\"})\n",
    "slow_sma_real = slow_sma.real.vbt.rename_levels({\"sma_timeframe\": \"slow_sma_timeframe\"})\n",
    "fast_sma_real, slow_sma_real = fast_sma_real.vbt.x(slow_sma_real)\n",
    "long_entries = fast_sma_real.vbt.crossed_above(slow_sma_real)\n",
    "short_entries = fast_sma_real.vbt.crossed_below(slow_sma_real)\n",
    "pf = vbt.PF.from_signals(data, long_entries=long_entries, short_entries=short_entries)\n",
    "pf.trades.expectancy.sort_values(ascending=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e573717-8f4c-402b-aef6-cab06f9df044",
   "metadata": {},
   "source": [
    "## Next steps"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9b042ef0-9041-4722-bde7-bea35c9ca2ec",
   "metadata": {},
   "source": [
    "Timeframe is yet another parameter of your strategy that can be tweaked. For example, you can go to uncharted territory and test more unconventional timeframes like \"1h 30min\" to discover potentially novel insights. Similar to other parameters, timeframes should also undergo cross-validation."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9233c24e-59f5-4947-b1d5-5c4b5c409ebe",
   "metadata": {},
   "source": [
    "However, unlike regular parameters, timeframes should be regarded as a distinct dimension that provides a unique perspective on your strategy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9395716f-2f53-4e0a-a48b-205bdbe6c1fd",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
