{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# CANDLEGAPS\n", "\n", "* gaps on second based bars indicates short-term up/down move\n", "\n", "TODO:\n", "* dodělat shorty\n", "* přidat kombinace angle nebo nějaké podobné krátkodobé momentum jako doplňkový indikátor\n", "* vyzkouset ruzne timeframe (sec a min) + hodnotu gapu a dalsi podminky" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "from dotenv import load_dotenv\n", "\n", "#as V2realbot is client , load env variables here\n", "env_file = \"/Users/davidbrazda/Documents/Development/python/.env\"\n", "# Load the .env file\n", "load_dotenv(env_file)\n", "\n", "from v2realbot.utils.utils import zoneNY\n", "import pandas as pd\n", "import numpy as np\n", "import vectorbtpro as vbt\n", "# from itables import init_notebook_mode, show\n", "import datetime\n", "from itertools import product\n", "from v2realbot.config import DATA_DIR\n", "from lightweight_charts import JupyterChart, chart, Panel, PlotAccessor\n", "from IPython.display import display\n", "\n", "# init_notebook_mode(all_interactive=True)\n", "\n", "vbt.settings.set_theme(\"dark\")\n", "vbt.settings['plotting']['layout']['width'] = 1280\n", "vbt.settings.plotting.auto_rangebreaks = True\n", "# Set the option to display with pagination\n", "pd.set_option('display.notebook_repr_html', True)\n", "pd.set_option('display.max_rows', 10) # Number of rows per page" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "trades_df-BAC-2024-01-01T09_30_00-2024-05-14T16_00_00-CO4B7VPWUZF-100.parquet\n", "trades_df-BAC-2024-01-11T09:30:00-2024-01-12T16:00:00.parquet\n", "trades_df-SPY-2024-01-01T09:30:00-2024-05-14T16:00:00.parquet\n", "trades_df-BAC-2023-01-01T09_30_00-2024-05-25T16_00_00-47BCFOPUVWZ-100.parquet\n", "ohlcv_df-BAC-2024-01-11T09:30:00-2024-01-12T16:00:00.parquet\n", "trades_df-BAC-2024-05-15T09_30_00-2024-05-25T16_00_00-47BCFOPUVWZ-100.parquet\n", "ohlcv_df-BAC-2024-01-01T09_30_00-2024-05-25T16_00_00-47BCFOPUVWZ-100.parquet\n", "ohlcv_df-SPY-2024-01-01T09:30:00-2024-05-14T16:00:00.parquet\n", "ohlcv_df-BAC-2024-01-01T09_30_00-2024-05-14T16_00_00-CO4B7VPWUZF-100.parquet\n", "ohlcv_df-BAC-2023-01-01T09_30_00-2024-05-25T16_00_00-47BCFOPUVWZ-100.parquet\n", "ohlcv_df-BAC-2023-01-01T09_30_00-2024-05-25T15_30_00-47BCFOPUVWZ-100.parquet\n" ] }, { "data": { "text/plain": [ "5" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Define the market open and close times\n", "market_open = datetime.time(9, 30)\n", "market_close = datetime.time(16, 0)\n", "entry_window_opens = 1\n", "entry_window_closes = 370\n", "forced_exit_start = 380\n", "forced_exit_end = 390\n", "\n", "#LOAD FROM PARQUET\n", "#list all files is dir directory with parquet extension\n", "dir = DATA_DIR + \"/notebooks/\"\n", "import os\n", "files = [f for f in os.listdir(dir) if f.endswith(\".parquet\")]\n", "print('\\n'.join(map(str, files)))\n", "file_name = \"ohlcv_df-BAC-2023-01-01T09_30_00-2024-05-25T15_30_00-47BCFOPUVWZ-100.parquet\"\n", "ohlcv_df = pd.read_parquet(dir+file_name,engine='pyarrow')\n", "#filter ohlcv_df to certain date range (assuming datetime index)\n", "ohlcv_df = ohlcv_df.loc[\"2024-02-12 9:30\":\"2024-02-19 16:00\"]\n", "\n", "#add vwap column to ohlcv_df\n", "#ohlcv_df[\"hlcc4\"] = (ohlcv_df[\"close\"] + ohlcv_df[\"high\"] + ohlcv_df[\"low\"] + ohlcv_df[\"close\"]) / 4\n", "\n", "basic_data = vbt.Data.from_data(vbt.symbol_dict({\"BAC\": ohlcv_df}), tz_convert=zoneNY)\n", "ohlcv_df= None\n", "basic_data.wrapper.index.normalize().nunique()" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\n", "basic_data.wrapper.index.normalize().nunique()" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "DatetimeIndex: 57966 entries, 2024-02-12 09:30:00-05:00 to 2024-02-16 15:59:59-05:00\n", "Data columns (total 10 columns):\n", " # Column Non-Null Count Dtype \n", "--- ------ -------------- ----- \n", " 0 open 57966 non-null float64 \n", " 1 high 57966 non-null float64 \n", " 2 low 57966 non-null float64 \n", " 3 close 57966 non-null float64 \n", " 4 volume 57966 non-null float64 \n", " 5 trades 57966 non-null float64 \n", " 6 updated 57966 non-null datetime64[us, US/Eastern]\n", " 7 vwap 57966 non-null float64 \n", " 8 buyvolume 57966 non-null float64 \n", " 9 sellvolume 57966 non-null float64 \n", "dtypes: datetime64[us, US/Eastern](1), float64(9)\n", "memory usage: 4.9 MB\n" ] } ], "source": [ "basic_data.data[\"BAC\"].info()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Add resample function to custom columns" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "from vectorbtpro.utils.config import merge_dicts, Config, HybridConfig\n", "from vectorbtpro import _typing as tp\n", "from vectorbtpro.generic import nb as generic_nb\n", "\n", "_feature_config: tp.ClassVar[Config] = HybridConfig(\n", " {\n", " \"buyvolume\": dict(\n", " resample_func=lambda self, obj, resampler: obj.vbt.resample_apply(\n", " resampler,\n", " generic_nb.sum_reduce_nb,\n", " )\n", " ),\n", " \"sellvolume\": dict(\n", " resample_func=lambda self, obj, resampler: obj.vbt.resample_apply(\n", " resampler,\n", " generic_nb.sum_reduce_nb,\n", " )\n", " ),\n", " \"trades\": dict(\n", " resample_func=lambda self, obj, resampler: obj.vbt.resample_apply(\n", " resampler,\n", " generic_nb.sum_reduce_nb,\n", " )\n", " )\n", " }\n", ")\n", "\n", "basic_data._feature_config = _feature_config" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "ename": "TypingError", "evalue": "Failed in nopython mode pipeline (step: nopython frontend)\nNo implementation of function Function() found for signature:\n \n >>> _realign_nb(array(float64, 2d, C), array(datetime64[us], 1d, C), array(datetime64[us], 1d, C), timedelta64[ns], timedelta64[ns], bool, bool, float64, bool)\n \nThere are 2 candidate implementations:\n - Of which 1 did not match due to:\n Overload in function '_realign_nb': File: vectorbtpro/generic/nb/base.py: Line 1673.\n With argument(s): '(array(float64, 2d, C), array(datetime64[us], 1d, C), array(datetime64[us], 1d, C), timedelta64[ns], timedelta64[ns], bool, bool, float64, bool)':\n Rejected as the implementation raised a specific error:\n TypingError: Failed in nopython mode pipeline (step: nopython frontend)\n Failed in nopython mode pipeline (step: nopython frontend)\n No implementation of function Function() found for signature:\n \n >>> _realign_1d_nb(array(float64, 1d, A), array(datetime64[us], 1d, C), array(datetime64[us], 1d, C), timedelta64[ns], timedelta64[ns], bool, bool, float64, bool)\n \n There are 2 candidate implementations:\n - Of which 2 did not match due to:\n Overload in function '_realign_1d_nb': File: vectorbtpro/generic/nb/base.py: Line 1509.\n With argument(s): '(array(float64, 1d, A), array(datetime64[us], 1d, C), array(datetime64[us], 1d, C), timedelta64[ns], timedelta64[ns], bool, bool, float64, bool)':\n Rejected as the implementation raised a specific error:\n TypingError: Failed in nopython mode pipeline (step: nopython frontend)\n Cannot unify datetime64[ns] and datetime64[us] for 'source_val.4', defined at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1577)\n \n File \"../../.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py\", line 1577:\n def impl(\n \n target_val = target_index[i] + target_freq\n if source_val > target_val:\n ^\n \n During: typing of assignment at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1577)\n \n File \"../../.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py\", line 1577:\n def impl(\n \n target_val = target_index[i] + target_freq\n if source_val > target_val:\n ^\n \n raised from /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/numba/core/typeinfer.py:1091\n \n During: resolving callee type: Function()\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1660)\n \n \n File \"../../.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py\", line 1660:\n def realign_1d_nb(\n \n If `arr` contains bar data, both indexes must represent the opening time.\"\"\"\n return _realign_1d_nb(\n ^\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n \n File \"../../.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py\", line 1706:\n def impl(\n \n for col in prange(arr.shape[1]):\n out[:, col] = realign_1d_nb(\n ^\n\n raised from /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/numba/core/typeinfer.py:1091\n - Of which 1 did not match due to:\n Overload in function '_realign_nb': File: vectorbtpro/generic/nb/base.py: Line 1673.\n With argument(s): '(array(float64, 2d, C), array(datetime64[us], 1d, C), array(datetime64[us], 1d, C), timedelta64[ns], timedelta64[ns], bool, bool, float64, bool)':\n Rejected as the implementation raised a specific error:\n TypingError: Failed in nopython mode pipeline (step: nopython frontend)\n Failed in nopython mode pipeline (step: nopython frontend)\n No implementation of function Function() found for signature:\n \n >>> _realign_1d_nb(array(float64, 1d, A), array(datetime64[us], 1d, C), array(datetime64[us], 1d, C), timedelta64[ns], timedelta64[ns], bool, bool, float64, bool)\n \n There are 2 candidate implementations:\n - Of which 2 did not match due to:\n Overload in function '_realign_1d_nb': File: vectorbtpro/generic/nb/base.py: Line 1509.\n With argument(s): '(array(float64, 1d, A), array(datetime64[us], 1d, C), array(datetime64[us], 1d, C), timedelta64[ns], timedelta64[ns], bool, bool, float64, bool)':\n Rejected as the implementation raised a specific error:\n TypingError: Failed in nopython mode pipeline (step: nopython frontend)\n Cannot unify datetime64[ns] and datetime64[us] for 'source_val.4', defined at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1577)\n \n File \"../../.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py\", line 1577:\n def impl(\n \n target_val = target_index[i] + target_freq\n if source_val > target_val:\n ^\n \n During: typing of assignment at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1577)\n \n File \"../../.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py\", line 1577:\n def impl(\n \n target_val = target_index[i] + target_freq\n if source_val > target_val:\n ^\n \n raised from /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/numba/core/typeinfer.py:1091\n \n During: resolving callee type: Function()\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1660)\n \n \n File \"../../.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py\", line 1660:\n def realign_1d_nb(\n \n If `arr` contains bar data, both indexes must represent the opening time.\"\"\"\n return _realign_1d_nb(\n ^\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n \n File \"../../.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py\", line 1706:\n def impl(\n \n for col in prange(arr.shape[1]):\n out[:, col] = realign_1d_nb(\n ^\n\n raised from /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/numba/core/typeinfer.py:1091\n\nDuring: resolving callee type: Function()\nDuring: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1766)\n\n\nFile \"../../.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py\", line 1766:\ndef realign_nb(\n \n \"\"\"2-dim version of `realign_1d_nb`.\"\"\"\n return _realign_nb(\n ^\n", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypingError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[18], line 25\u001b[0m\n\u001b[1;32m 23\u001b[0m \u001b[38;5;66;03m#resample on specific index \u001b[39;00m\n\u001b[1;32m 24\u001b[0m resampler \u001b[38;5;241m=\u001b[39m vbt\u001b[38;5;241m.\u001b[39mResampler(t30data\u001b[38;5;241m.\u001b[39mindex, s1data\u001b[38;5;241m.\u001b[39mindex, source_freq\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m30T\u001b[39m\u001b[38;5;124m\"\u001b[39m, target_freq\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m1s\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m---> 25\u001b[0m t30close_realigned \u001b[38;5;241m=\u001b[39m \u001b[43mt30close\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mvbt\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrealign_closing\u001b[49m\u001b[43m(\u001b[49m\u001b[43mresampler\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 27\u001b[0m \u001b[38;5;66;03m#resample 1min to s\u001b[39;00m\n\u001b[1;32m 28\u001b[0m resampler_s \u001b[38;5;241m=\u001b[39m vbt\u001b[38;5;241m.\u001b[39mResampler(t1data\u001b[38;5;241m.\u001b[39mindex, s1data\u001b[38;5;241m.\u001b[39mindex, source_freq\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m1T\u001b[39m\u001b[38;5;124m\"\u001b[39m, target_freq\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m1s\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n", "File \u001b[0;32m~/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/accessors.py:2471\u001b[0m, in \u001b[0;36mGenericAccessor.realign_closing\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m 2465\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mrealign_closing\u001b[39m(\u001b[38;5;28mself\u001b[39m, \u001b[38;5;241m*\u001b[39margs, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs) \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m>\u001b[39m tp\u001b[38;5;241m.\u001b[39mMaybeSeriesFrame:\n\u001b[1;32m 2466\u001b[0m \u001b[38;5;250m \u001b[39m\u001b[38;5;124;03m\"\"\"`GenericAccessor.realign` but creating a resampler and using the right bound\u001b[39;00m\n\u001b[1;32m 2467\u001b[0m \u001b[38;5;124;03m of the source and target index.\u001b[39;00m\n\u001b[1;32m 2468\u001b[0m \n\u001b[1;32m 2469\u001b[0m \u001b[38;5;124;03m !!! note\u001b[39;00m\n\u001b[1;32m 2470\u001b[0m \u001b[38;5;124;03m The timestamps in the source and target index should denote the open time.\"\"\"\u001b[39;00m\n\u001b[0;32m-> 2471\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrealign\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43msource_rbound\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mTrue\u001b[39;49;00m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mtarget_rbound\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mTrue\u001b[39;49;00m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n", "File \u001b[0;32m~/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/accessors.py:2443\u001b[0m, in \u001b[0;36mGenericAccessor.realign\u001b[0;34m(self, index, freq, nan_value, ffill, source_rbound, target_rbound, jitted, chunked, wrap_kwargs, silence_warnings)\u001b[0m\n\u001b[1;32m 2441\u001b[0m func \u001b[38;5;241m=\u001b[39m jit_reg\u001b[38;5;241m.\u001b[39mresolve_option(nb\u001b[38;5;241m.\u001b[39mrealign_nb, jitted)\n\u001b[1;32m 2442\u001b[0m func \u001b[38;5;241m=\u001b[39m ch_reg\u001b[38;5;241m.\u001b[39mresolve_option(func, chunked)\n\u001b[0;32m-> 2443\u001b[0m out \u001b[38;5;241m=\u001b[39m \u001b[43mfunc\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 2444\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mto_2d_array\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2445\u001b[0m \u001b[43m \u001b[49m\u001b[43mresampler\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43msource_index\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mvalues\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2446\u001b[0m \u001b[43m \u001b[49m\u001b[43mresampler\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mtarget_index\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mvalues\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2447\u001b[0m \u001b[43m \u001b[49m\u001b[43msource_freq\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43msource_freq\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2448\u001b[0m \u001b[43m \u001b[49m\u001b[43mtarget_freq\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mtarget_freq\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2449\u001b[0m \u001b[43m \u001b[49m\u001b[43msource_rbound\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43muse_source_rbound\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2450\u001b[0m \u001b[43m \u001b[49m\u001b[43mtarget_rbound\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43muse_target_rbound\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2451\u001b[0m \u001b[43m \u001b[49m\u001b[43mnan_value\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mnan_value\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2452\u001b[0m \u001b[43m \u001b[49m\u001b[43mffill\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mffill\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2453\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 2454\u001b[0m wrap_kwargs \u001b[38;5;241m=\u001b[39m merge_dicts(\u001b[38;5;28mdict\u001b[39m(index\u001b[38;5;241m=\u001b[39mindex), wrap_kwargs)\n\u001b[1;32m 2455\u001b[0m out \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mwrapper\u001b[38;5;241m.\u001b[39mwrap(out, group_by\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mFalse\u001b[39;00m, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mwrap_kwargs)\n", "File \u001b[0;32m~/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/numba/core/dispatcher.py:423\u001b[0m, in \u001b[0;36m_DispatcherBase._compile_for_args\u001b[0;34m(self, *args, **kws)\u001b[0m\n\u001b[1;32m 419\u001b[0m msg \u001b[38;5;241m=\u001b[39m (\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mstr\u001b[39m(e)\u001b[38;5;241m.\u001b[39mrstrip()\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m \u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;124mThis error may have been caused \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 420\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mby the following argument(s):\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;132;01m{\u001b[39;00margs_str\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m 421\u001b[0m e\u001b[38;5;241m.\u001b[39mpatch_message(msg)\n\u001b[0;32m--> 423\u001b[0m \u001b[43merror_rewrite\u001b[49m\u001b[43m(\u001b[49m\u001b[43me\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43mtyping\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m)\u001b[49m\n\u001b[1;32m 424\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m errors\u001b[38;5;241m.\u001b[39mUnsupportedError \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[1;32m 425\u001b[0m \u001b[38;5;66;03m# Something unsupported is present in the user code, add help info\u001b[39;00m\n\u001b[1;32m 426\u001b[0m error_rewrite(e, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124munsupported_error\u001b[39m\u001b[38;5;124m'\u001b[39m)\n", "File \u001b[0;32m~/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/numba/core/dispatcher.py:364\u001b[0m, in \u001b[0;36m_DispatcherBase._compile_for_args..error_rewrite\u001b[0;34m(e, issue_type)\u001b[0m\n\u001b[1;32m 362\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m e\n\u001b[1;32m 363\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[0;32m--> 364\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m e\u001b[38;5;241m.\u001b[39mwith_traceback(\u001b[38;5;28;01mNone\u001b[39;00m)\n", "\u001b[0;31mTypingError\u001b[0m: Failed in nopython mode pipeline (step: nopython frontend)\nNo implementation of function Function() found for signature:\n \n >>> _realign_nb(array(float64, 2d, C), array(datetime64[us], 1d, C), array(datetime64[us], 1d, C), timedelta64[ns], timedelta64[ns], bool, bool, float64, bool)\n \nThere are 2 candidate implementations:\n - Of which 1 did not match due to:\n Overload in function '_realign_nb': File: vectorbtpro/generic/nb/base.py: Line 1673.\n With argument(s): '(array(float64, 2d, C), array(datetime64[us], 1d, C), array(datetime64[us], 1d, C), timedelta64[ns], timedelta64[ns], bool, bool, float64, bool)':\n Rejected as the implementation raised a specific error:\n TypingError: Failed in nopython mode pipeline (step: nopython frontend)\n Failed in nopython mode pipeline (step: nopython frontend)\n No implementation of function Function() found for signature:\n \n >>> _realign_1d_nb(array(float64, 1d, A), array(datetime64[us], 1d, C), array(datetime64[us], 1d, C), timedelta64[ns], timedelta64[ns], bool, bool, float64, bool)\n \n There are 2 candidate implementations:\n - Of which 2 did not match due to:\n Overload in function '_realign_1d_nb': File: vectorbtpro/generic/nb/base.py: Line 1509.\n With argument(s): '(array(float64, 1d, A), array(datetime64[us], 1d, C), array(datetime64[us], 1d, C), timedelta64[ns], timedelta64[ns], bool, bool, float64, bool)':\n Rejected as the implementation raised a specific error:\n TypingError: Failed in nopython mode pipeline (step: nopython frontend)\n Cannot unify datetime64[ns] and datetime64[us] for 'source_val.4', defined at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1577)\n \n File \"../../.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py\", line 1577:\n def impl(\n \n target_val = target_index[i] + target_freq\n if source_val > target_val:\n ^\n \n During: typing of assignment at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1577)\n \n File \"../../.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py\", line 1577:\n def impl(\n \n target_val = target_index[i] + target_freq\n if source_val > target_val:\n ^\n \n raised from /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/numba/core/typeinfer.py:1091\n \n During: resolving callee type: Function()\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1660)\n \n \n File \"../../.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py\", line 1660:\n def realign_1d_nb(\n \n If `arr` contains bar data, both indexes must represent the opening time.\"\"\"\n return _realign_1d_nb(\n ^\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n \n File \"../../.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py\", line 1706:\n def impl(\n \n for col in prange(arr.shape[1]):\n out[:, col] = realign_1d_nb(\n ^\n\n raised from /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/numba/core/typeinfer.py:1091\n - Of which 1 did not match due to:\n Overload in function '_realign_nb': File: vectorbtpro/generic/nb/base.py: Line 1673.\n With argument(s): '(array(float64, 2d, C), array(datetime64[us], 1d, C), array(datetime64[us], 1d, C), timedelta64[ns], timedelta64[ns], bool, bool, float64, bool)':\n Rejected as the implementation raised a specific error:\n TypingError: Failed in nopython mode pipeline (step: nopython frontend)\n Failed in nopython mode pipeline (step: nopython frontend)\n No implementation of function Function() found for signature:\n \n >>> _realign_1d_nb(array(float64, 1d, A), array(datetime64[us], 1d, C), array(datetime64[us], 1d, C), timedelta64[ns], timedelta64[ns], bool, bool, float64, bool)\n \n There are 2 candidate implementations:\n - Of which 2 did not match due to:\n Overload in function '_realign_1d_nb': File: vectorbtpro/generic/nb/base.py: Line 1509.\n With argument(s): '(array(float64, 1d, A), array(datetime64[us], 1d, C), array(datetime64[us], 1d, C), timedelta64[ns], timedelta64[ns], bool, bool, float64, bool)':\n Rejected as the implementation raised a specific error:\n TypingError: Failed in nopython mode pipeline (step: nopython frontend)\n Cannot unify datetime64[ns] and datetime64[us] for 'source_val.4', defined at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1577)\n \n File \"../../.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py\", line 1577:\n def impl(\n \n target_val = target_index[i] + target_freq\n if source_val > target_val:\n ^\n \n During: typing of assignment at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1577)\n \n File \"../../.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py\", line 1577:\n def impl(\n \n target_val = target_index[i] + target_freq\n if source_val > target_val:\n ^\n \n raised from /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/numba/core/typeinfer.py:1091\n \n During: resolving callee type: Function()\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1660)\n \n \n File \"../../.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py\", line 1660:\n def realign_1d_nb(\n \n If `arr` contains bar data, both indexes must represent the opening time.\"\"\"\n return _realign_1d_nb(\n ^\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n During: resolving callee type: type(CPUDispatcher())\n During: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1706)\n \n \n File \"../../.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py\", line 1706:\n def impl(\n \n for col in prange(arr.shape[1]):\n out[:, col] = realign_1d_nb(\n ^\n\n raised from /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/numba/core/typeinfer.py:1091\n\nDuring: resolving callee type: Function()\nDuring: typing of call at /Users/davidbrazda/Documents/Development/python/strategy-lab1/.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py (1766)\n\n\nFile \"../../.venv/lib/python3.10/site-packages/vectorbtpro/generic/nb/base.py\", line 1766:\ndef realign_nb(\n \n \"\"\"2-dim version of `realign_1d_nb`.\"\"\"\n return _realign_nb(\n ^\n" ] } ], "source": [ "s1data = basic_data[['open', 'high', 'low', 'close', 'volume','vwap','buyvolume','trades','sellvolume']]\n", "\n", "s2data = s1data.resample(\"2s\")\n", "s2data = s2data.transform(lambda df: df.between_time('09:30', '16:00').dropna())\n", "\n", "s5data = s1data.resample(\"5s\")\n", "s5data = s5data.transform(lambda df: df.between_time('09:30', '16:00').dropna())\n", "\n", "t1data = basic_data[['open', 'high', 'low', 'close', 'volume','vwap','buyvolume','trades','sellvolume']].resample(\"1T\")\n", "t1data = t1data.transform(lambda df: df.between_time('09:30', '16:00').dropna())\n", "# t1data.data[\"BAC\"].info()\n", "\n", "t30data = basic_data[['open', 'high', 'low', 'close', 'volume','vwap','buyvolume','trades','sellvolume']].resample(\"30T\")\n", "t30data = t30data.transform(lambda df: df.between_time('09:30', '16:00').dropna())\n", "# t30data.data[\"BAC\"].info()\n", "\n", "s2close = s2data.close\n", "s1close = s1data.close\n", "t1close = t1data.close\n", "t30close = t30data.close\n", "t30volume = t30data.volume\n", "\n", "#resample on specific index \n", "resampler = vbt.Resampler(t30data.index, s1data.index, source_freq=\"30T\", target_freq=\"1s\")\n", "t30close_realigned = t30close.vbt.realign_closing(resampler)\n", "\n", "#resample 1min to s\n", "resampler_s = vbt.Resampler(t1data.index, s1data.index, source_freq=\"1T\", target_freq=\"1s\")\n", "t1close_realigned = t1close.vbt.realign_closing(resampler_s)\n", "\n", "resampler_s = vbt.Resampler(s2data.index, s1data.index, source_freq=\"2s\", target_freq=\"1s\")\n", "s2close_realigned = s2close.vbt.realign_closing(resampler_s)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "vbt.IF.list_indicators(\"*vwap\")\n", "vbt.phelp(vbt.VWAP.run)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# VWAP" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "t1vwap_h = vbt.VWAP.run(t1data.high, t1data.low, t1data.close, t1data.volume, anchor=\"H\")\n", "t1vwap_d = vbt.VWAP.run(t1data.high, t1data.low, t1data.close, t1data.volume, anchor=\"D\")\n", "t1vwap_t = vbt.VWAP.run(t1data.high, t1data.low, t1data.close, t1data.volume, anchor=\"T\")\n", "\n", "t1vwap_h_real = t1vwap_h.vwap.vbt.realign_closing(resampler_s)\n", "t1vwap_d_real = t1vwap_d.vwap.vbt.realign_closing(resampler_s)\n", "t1vwap_t_real = t1vwap_t.vwap.vbt.realign_closing(resampler_s)\n", "\n", "#t1vwap_5t.xloc[\"2024-01-3 09:30:00\":\"2024-01-03 16:00:00\"].plot()\n", "\n", "div_rel = (s1data.close.vbt - t1vwap_h_real) - 1\n", "\n", "div_rel" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#m30data.close.lw.plot()\n", "#quick few liner\n", "pane1 = Panel(\n", " histogram=[\n", " #(s1data.volume, \"volume\",None, 0.8),\n", " #(m30volume, \"m30volume\",None, 1)\n", " ], # [(series, name, \"rgba(53, 94, 59, 0.6)\", opacity)]\n", " right=[\n", " (s1data.close, \"1s close\"),\n", " (s2data.close, \"1s close\"),\n", " (t1data.close, \"1min close\"),\n", " (t1vwap_t, \"1mvwap_t\"),\n", " (t1vwap_h, \"1mvwap_h\"),\n", " (t1vwap_d, \"1mvwap_d\"),\n", " (t1vwap_t_real, \"1mvwap_t_real\"),\n", " (t1vwap_h_real, \"1mvwap_h_real\"),\n", " (t1vwap_d_real, \"1mvwap_d_real\")\n", " # (t1close_realigned, \"1min close realigned\"),\n", " # (m30data.close, \"30min-close\"),\n", " # (m30close_realigned, \"30min close realigned\"),\n", " ],\n", " left = [\n", " (div_rel, \"reldiv1s_1Hvwap\",)\n", " ]\n", ")\n", "ch = chart([pane1], size=\"s\", xloc=slice(\"2024-05-1 09:30:00\",\"2024-05-5 16:00:00\"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# SUPERTREND" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "supertrend_s1 = vbt.SUPERTREND.run(s1data.high, s1data.low, s1data.close, period=5, multiplier=3)\n", "direction_series_s1 = supertrend_s1.direction\n", "supertrend_t1 = vbt.SUPERTREND.run(t1data.high, t1data.low, t1data.close, period=14, multiplier=3)\n", "direction_series_t1 = supertrend_t1.direction\n", "supertrend_t30 = vbt.SUPERTREND.run(t30data.high, t30data.low, t30data.close, period=14, multiplier=3)\n", "direction_series_t30 = supertrend_t30.direction\n", "\n", "resampler_1t_sec = vbt.Resampler(direction_series_t1.index, direction_series_s1.index, source_freq=\"1T\", target_freq=\"1s\")\n", "resampler_30t_sec = vbt.Resampler(direction_series_t30.index, direction_series_s1.index, source_freq=\"30T\", target_freq=\"1s\")\n", "direction_series_t1_realigned = direction_series_t1.vbt.realign_closing(resampler_1t_sec)\n", "direction_series_t30_realigned = direction_series_t30.vbt.realign_closing(resampler_30t_sec)\n", "\n", "#supertrend_s1.xloc[\"2024-01-3 09:30:00\":\"2024-01-03 16:00:00\"].plot()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# aligned_ups= pd.Series(False, index=direction_real.index)\n", "# aligned_downs= pd.Series(False, index=direction_real.index)\n", "\n", "# aligned_ups = direction_real == 1 & supertrend.direction == 1\n", "# aligned_ups" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s5close = s5data.data[\"BAC\"].close\n", "s5open = s5data.data[\"BAC\"].open\n", "s5high = s5data.data[\"BAC\"].high\n", "s5low = s5data.data[\"BAC\"].low\n", "s5close_prev = s5close.shift(1)\n", "s5open_prev = s5open.shift(1)\n", "s5high_prev = s5high.shift(1)\n", "s5low_prev = s5low.shift(1)\n", "#gap nahoru od byci svicky a nevraci se zpet na jeji uroven\n", "entry_ups = (s5close_prev > s5open_prev) & (s5open > s5high_prev + 0.010) & (s5close > s5close_prev) & (s5close > s5open)\n", "\n", "print(entry_ups.value_counts())\n", "\n", "entry_downs = (s5close_prev < s5open_prev) & (s5open < s5low_prev - 0.012) & (s5close < s5close_prev)\n", "\n", "print(entry_downs.value_counts())\n", "\n", "#entry_ups.info()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Entry window" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "market_open = datetime.time(9, 30)\n", "market_close = datetime.time(16, 0)\n", "entry_window_opens = 10\n", "entry_window_closes = 370\n", "forced_exit_start = 380\n", "forced_exit_end = 390" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#entry_ups = pd.Series(False, index=s5data.index)\n", "\n", "entry_window_open= pd.Series(False, index=entry_ups.index)\n", "# Calculate the time difference in minutes from market open for each timestamp\n", "elapsed_min_from_open = (entry_ups.index.hour - market_open.hour) * 60 + (entry_ups.index.minute - market_open.minute)\n", "entry_window_open[(elapsed_min_from_open >= entry_window_opens) & (elapsed_min_from_open < entry_window_closes)] = True\n", "entry_ups = entry_ups & entry_window_open\n", "# entry_ups\n", "\n", "entry_down_window_open= pd.Series(False, index=entry_downs.index)\n", "entry_down_window_open[(elapsed_min_from_open >= entry_window_opens) & (elapsed_min_from_open < entry_window_closes)] = True\n", "entry_downs = entry_downs & entry_down_window_open\n", "\n", "forced_exits = pd.Series(False, index=s5data.index)\n", "forced_exits[(elapsed_min_from_open >= forced_exit_start) & (elapsed_min_from_open < forced_exit_end)] = True\n", "\n", "# forced_exits\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "entry_ups.value_counts()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s5vwap_h = vbt.VWAP.run(s5data.high, s5data.low, s5data.close, s5data.volume, anchor=\"H\")\n", "s5vwap_d = vbt.VWAP.run(s5data.high, s5data.low, s5data.close, s5data.volume, anchor=\"D\")\n", "\n", "# s5vwap_h_real = s5vwap_h.vwap.vbt.realign_closing(resampler_s)\n", "# s5vwap_d_real = s5vwap_d.vwap.vbt.realign_closing(resampler_s)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pane1 = Panel(\n", " ohlcv=(s5data.data[\"BAC\"],), #(series, entries, exits, other_markers)\n", " histogram=[], # [(series, name, \"rgba(53, 94, 59, 0.6), opacity\")]\n", " right=[#(bbands,), #[(series, name, entries, exits, other_markers)]\n", " (s5data.data[\"BAC\"].close, \"close\", entry_ups, entry_downs),\n", " (s5data.data[\"BAC\"].open, \"open\"),\n", " (s5vwap_h, \"vwap5s_H\",),\n", " (s5vwap_d, \"vwap5s_D\",)\n", " # (t1data.data[\"BAC\"].vwap, \"vwap\"),\n", " # (t1data.close, \"1min close\"),\n", " # (supertrend_s1.trend,\"STtrend\"),\n", " # (supertrend_s1.long,\"STlong\"),\n", " # (supertrend_s1.short,\"STshort\")\n", " ],\n", " left = [\n", " #(direction_series_s1,\"direction_s1\"),\n", " # (direction_series_t1,\"direction_t1\"),\n", " # (direction_series_t30,\"direction_t30\")\n", " \n", " ],\n", " # right=[(bbands.upperband, \"upperband\",),\n", " # (bbands.lowerband, \"lowerband\",),\n", " # (bbands.middleband, \"middleband\",)\n", " # ], #[(series, name, entries, exits, other_markers)]\n", " middle1=[],\n", " middle2=[],\n", ")\n", "\n", "# pane2 = Panel(\n", "# ohlcv=(t1data.data[\"BAC\"],uptrend_m30, downtrend_m30), #(series, entries, exits, other_markers)\n", "# histogram=[], # [(series, name, \"rgba(53, 94, 59, 0.6), opacity\")]\n", "# left=[#(bbands,), #[(series, name, entries, exits, other_markers)]\n", "# (direction_real,\"direction30min_real\"),\n", "# ],\n", "# # left = [(supertrendm30.direction,\"STdirection30\")],\n", "# # # right=[(bbands.upperband, \"upperband\",),\n", "# # # (bbands.lowerband, \"lowerband\",),\n", "# # # (bbands.middleband, \"middleband\",)\n", "# # # ], #[(series, name, entries, exits, other_markers)]\n", "# middle1=[],\n", "# middle2=[],\n", "# title = \"1m\")\n", "\n", "ch = chart([pane1], sync=True, size=\"s\", xloc=slice(\"2024-05-20 09:30:00\",\"2024-05-25 16:00:00\"), precision=6)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pd.set_option('display.max_rows', None)\n", "# data = s5data.xloc[\"2024-01-03 09:30:00\":\"2024-03-10 16:00:00\"]\n", "# entry = entry_ups.vbt.xloc[\"2024-01-03 09:30:00\":\"2024-03-10 16:00:00\"].obj\n", "\n", "pf = vbt.Portfolio.from_signals(close=s5data, entries=entry_ups, exits=forced_exits, direction=\"longonly\", sl_stop=0.05/100, tp_stop = 0.05/100, fees=0.0167/100, freq=\"5s\")\n", "pf.stats()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pf.xloc[\"2024-02-20 09:30:00\":\"2024-05-25 16:00:00\"].plot()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "vbt.pdir(pf)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pf.xloc[\"2024-05-20 09:30:00\":\"2024-05-25 16:00:00\"].asset_value" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "hourly_returns = pf.returns.resample(\"h\").get()\n", "hourly_returns.plot()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pf.returns" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pf.value" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pf.value.vbt.lineplot()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pf5 = pf.xloc[\"2024-05-20 09:30:00\":\"2024-05-25 16:00:00\"]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "monthly_returns = pf5.returns_acc.resample(\"5T\").get()\n", "monthly_returns = monthly_returns[monthly_returns!=0]\n", "\n", "monthly_returns\n", "#monthly_returns.vbt.heatmap() \n", "# fig = monthly_returns.vbt.heatmap() \n", "# fig = monthly_returns.vbt.ts_heatmap() " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pd.set_option('display.max_rows', None)\n", "pf.stats()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pf.plot().save_png()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pf.trades.records_readable.sort_values(by=\"PnL\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pf.xloc[\"2024-03-13 09:30:00\":\"2024-03-20 16:00:00\"].plot()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pf.xloc[\"2024-01-26 09:30:00\":\"2024-01-28 16:00:00\"].plot()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pd.set_option('display.max_rows', None)\n", "pf.stats()\n", "# pf.xloc[\"monday\"].stats()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "buyvolume = t1data.data[\"BAC\"].buyvolume\n", "sellvolume = t1data.data[\"BAC\"].sellvolume\n", "totalvolume = buyvolume + sellvolume\n", "\n", "#adjust to minimal value to avoid division by zero\n", "sellvolume_adjusted = sellvolume.replace(0, 1e-10)\n", "oibratio = buyvolume / sellvolume\n", "\n", "#cumulative order flow (net difference)\n", "cof = buyvolume - sellvolume\n", "\n", "# Calculate the order imbalance (net differene) normalize the order imbalance by calculating the difference between buy and sell volumes and then scaling it by the total volume.\n", "order_imbalance = cof / totalvolume\n", "order_imbalance = order_imbalance.fillna(0) #nan nahradime 0\n", "\n", "order_imbalance_allvolume = cof / t1data.data[\"BAC\"].volume\n", "\n", "order_imbalance_sma = vbt.indicator(\"talib:EMA\").run(order_imbalance, timeperiod=5)\n", "short_signals = order_imbalance.vbt < -0.5\n", "#short_entries = oibratio.vbt < 0.01\n", "short_signals.value_counts()\n", "short_signals.name = \"short_entries\"\n", "#.fillna(False)\n", "short_exits = short_signals.shift(-2).fillna(False).astype(bool)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pane1 = Panel(\n", " ohlcv=(t1data.data[\"BAC\"],), #(series, entries, exits, other_markers)\n", " histogram=[(order_imbalance_allvolume, \"oib_allvolume\", \"rgba(53, 94, 59, 0.6)\",0.5),\n", " (t1data.data[\"BAC\"].trades, \"trades\",None,0.4),\n", " ], # [(series, name, \"rgba(53, 94, 59, 0.6)\", opacity)]\n", " # right=[\n", " # (supertrend.trend,\"STtrend\"),\n", " # (supertrend.long,\"STlong\"),\n", " # (supertrend.short,\"STshort\")\n", " # ],\n", " # left = [(supertrend.direction,\"STdirection\")],\n", " # right=[(bbands.upperband, \"upperband\",),\n", " # (bbands.lowerband, \"lowerband\",),\n", " # (bbands.middleband, \"middleband\",)\n", " # ], #[(series, name, entries, exits, other_markers)]\n", " middle1=[],\n", " middle2=[],\n", ")\n", "\n", "pane2 = Panel(\n", " ohlcv=(basic_data.data[\"BAC\"],), #(series, entries, exits, other_markers)\n", " left=[(basic_data.data[\"BAC\"].trades, \"trades\")],\n", " histogram=[(basic_data.data[\"BAC\"].trades, \"trades_hist\", \"white\", 0.5)], #\"rgba(53, 94, 59, 0.6)\"\n", " # ], # [(series, name, \"rgba(53, 94, 59, 0.6)\")]\n", " # right=[\n", " # (supertrend.trend,\"STtrend\"),\n", " # (supertrend.long,\"STlong\"),\n", " # (supertrend.short,\"STshort\")\n", " # ],\n", " # left = [(supertrend.direction,\"STdirection\")],\n", " # right=[(bbands.upperband, \"upperband\",),\n", " # (bbands.lowerband, \"lowerband\",),\n", " # (bbands.middleband, \"middleband\",)\n", " # ], #[(series, name, entries, exits, other_markers)]\n", " middle1=[],\n", " middle2=[],\n", ")\n", "\n", "\n", "ch = chart([pane1, pane2], size=\"m\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#short_signal = t1slope.real_below(t1_th) & t2slope.real_below(t2_th) & t3slope.real_below(t3_th) & t4slope.real_below(t4_th)\n", "#long_signal = t1slope.real_above(t1_th) & t2slope.real_above(t2_th) & t3slope.real_above(t3_th) & t4slope.real_above(t4_th)\n", "\n", "#test na daily s reversem crossed 0\n", "short_signal = t2slope.vbt < -0.01 & t3slope.vbt < -0.01 #min value of threshold\n", "long_signal = t2slope.vbt > 0.01 & t3slope.vbt > 0.01 #min\n", "\n", "# thirty_up_signal = t3slope.vbt.crossed_above(0.01)\n", "# thirty_down_signal = t3slope.vbt.crossed_below(-0.01)\n", "\n", "fig = plot_2y_close(priminds=[], secinds=[t3slope], close=t1data.close)\n", "#short_signal.vbt.signals.plot_as_entries(basic_data.close, fig=fig)\n", "\n", "short_signal.vbt.signals.plot_as_entries(t1data.close, fig=fig, trace_kwargs=dict(name=\"SHORTS\",\n", " line=dict(color=\"#ffe476\"),\n", " marker=dict(color=\"red\", symbol=\"triangle-down\"),\n", " fill=None,\n", " connectgaps=True,\n", " ))\n", "long_signal.vbt.signals.plot_as_entries(t1data.close, fig=fig, trace_kwargs=dict(name=\"LONGS\",\n", " line=dict(color=\"#ffe476\"),\n", " marker=dict(color=\"limegreen\"),\n", " fill=None,\n", " connectgaps=True,\n", " ))\n", "\n", "# thirty_down_signal.vbt.signals.plot_as_entries(t1data.close, fig=fig, trace_kwargs=dict(name=\"DOWN30\",\n", "# line=dict(color=\"#ffe476\"),\n", "# marker=dict(color=\"yellow\", symbol=\"triangle-down\"),\n", "# fill=None,\n", "# connectgaps=True,\n", "# ))\n", "# thirty_up_signal.vbt.signals.plot_as_entries(t1data.close, fig=fig, trace_kwargs=dict(name=\"UP30\",\n", "# line=dict(color=\"#ffe476\"),\n", "# marker=dict(color=\"grey\"),\n", "# fill=None,\n", "# connectgaps=True,\n", "# ))\n", "\n", "# thirtymin_slope_to_compare.vbt.plot(fig=fig, add_trace_kwargs=dict(secondary_y=True), trace_kwargs=dict(name=\"30min slope\",\n", "# line=dict(color=\"yellow\"), \n", "# fill=None,\n", "# connectgaps=True,\n", "# ))\n", "\n", "fig.show()\n", "# print(\"short signal\")\n", "# print(short_signal.value_counts())\n", "\n", "#forced_exit = pd.Series(False, index=close.index)\n", "forced_exit = basic_data.symbol_wrapper.fill(False)\n", "#entry_window_open = pd.Series(False, index=close.index)\n", "entry_window_open= basic_data.symbol_wrapper.fill(False)\n", "\n", "# Calculate the time difference in minutes from market open for each timestamp\n", "elapsed_min_from_open = (forced_exit.index.hour - market_open.hour) * 60 + (forced_exit.index.minute - market_open.minute)\n", "\n", "entry_window_open[(elapsed_min_from_open >= entry_window_opens) & (elapsed_min_from_open < entry_window_closes)] = True\n", "\n", "#print(entry_window_open.value_counts())\n", "\n", "forced_exit[(elapsed_min_from_open >= forced_exit_start) & (elapsed_min_from_open < forced_exit_end)] = True\n", "short_entries = (short_signal & entry_window_open)\n", "short_exits = forced_exit\n", "\n", "entries = (long_signal & entry_window_open)\n", "exits = forced_exit\n", "#long_entries.info()\n", "#number of trues and falses in long_entries\n", "# print(short_exits.value_counts())\n", "# print(short_entries.value_counts())\n", "\n", "#fig = plot_2y_close([],[momshort, rocp], close)\n", "#short_signal.vbt.signals.plot_as_entries(close, fig=fig, add_trace_kwargs=dict(secondary_y=False))\n", "#print(sl_stop)\n", "#short_entries=short_entries, short_exits=short_exits,\n", "# pf = vbt.Portfolio.from_signals(close=basic_data, entries=short_entries, exits=exits, tsl_stop=0.005, tp_stop = 0.05, fees=0.0167/100, freq=\"1s\") #sl_stop=sl_stop, tp_stop = sl_stop,\n", "\n", "# pf.stats()\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "forced_exit = t1data.symbol_wrapper.fill(False)\n", "#entry_window_open = pd.Series(False, index=close.index)\n", "entry_window_open= t1data.symbol_wrapper.fill(False)\n", "\n", "# Calculate the time difference in minutes from market open for each timestamp\n", "elapsed_min_from_open = (forced_exit.index.hour - market_open.hour) * 60 + (forced_exit.index.minute - market_open.minute)\n", "\n", "entry_window_open[(elapsed_min_from_open >= entry_window_opens) & (elapsed_min_from_open < entry_window_closes)] = True\n", "\n", "#print(entry_window_open.value_counts())\n", "\n", "forced_exit[(elapsed_min_from_open >= forced_exit_start) & (elapsed_min_from_open < forced_exit_end)] = True\n", "short_entries = (short_signals & entry_window_open)\n", "short_exits = forced_exit\n", "\n", "entries = (long_signals & entry_window_open)\n", "exits = forced_exit\n", "\n", "pf = vbt.Portfolio.from_signals(close=t1data, entries=entries, exits=exits, short_entries=short_entries, short_exits=exits,\n", "td_stop=2, time_delta_format=\"rows\",\n", "tsl_stop=0.005, tp_stop = 0.005, fees=0.0167/100)#, freq=\"1s\") #sl_stop=sl_stop, tp_stop = sl_stop,\n", "\n", "pf.stats()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pf.plot()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pf.get_drawdowns().records_readable" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pf.orders.records_readable" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "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.10.11" } }, "nbformat": 4, "nbformat_minor": 2 }