Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/add notebooks #107

Merged
merged 14 commits into from
Dec 11, 2023
52 changes: 52 additions & 0 deletions quants_lab/controllers/supertrend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import time

import pandas as pd
from pydantic import Field

from hummingbot.smart_components.executors.position_executor.position_executor import PositionExecutor
from hummingbot.smart_components.strategy_frameworks.data_types import OrderLevel
from hummingbot.smart_components.strategy_frameworks.directional_trading.directional_trading_controller_base import (
DirectionalTradingControllerBase,
DirectionalTradingControllerConfigBase,
)


class SuperTrendConfig(DirectionalTradingControllerConfigBase):
strategy_name: str = "supertrend"
length: int = Field(default=20, ge=5, le=200)
multiplier: float = Field(default=4.0, ge=2.0, le=7.0)
percentage_threshold: float = Field(default=0.01, ge=0.005, le=0.05)


class SuperTrend(DirectionalTradingControllerBase):
def __init__(self, config: SuperTrendConfig):
super().__init__(config)
self.config = config

def early_stop_condition(self, executor: PositionExecutor, order_level: OrderLevel) -> bool:
# If an executor has an active position, should we close it based on a condition. This feature is not available
# for the backtesting yet
return False

def cooldown_condition(self, executor: PositionExecutor, order_level: OrderLevel) -> bool:
# After finishing an order, the executor will be in cooldown for a certain amount of time.
# This prevents the executor from creating a new order immediately after finishing one and execute a lot
# of orders in a short period of time from the same side.
if executor.close_timestamp and executor.close_timestamp + order_level.cooldown_time > time.time():
return True
return False

def get_processed_data(self) -> pd.DataFrame:
df = self.candles[0].candles_df
df.ta.supertrend(length=self.config.length, multiplier=self.config.multiplier, append=True)
df["percentage_distance"] = abs(df["close"] - df[f"SUPERT_{self.config.length}_{self.config.multiplier}"]) / df["close"]

# Generate long and short conditions
long_condition = (df[f"SUPERTd_{self.config.length}_{self.config.multiplier}"] == 1) & (df["percentage_distance"] < self.config.percentage_threshold)
short_condition = (df[f"SUPERTd_{self.config.length}_{self.config.multiplier}"] == -1) & (df["percentage_distance"] < self.config.percentage_threshold)

# Choose side
df['signal'] = 0
df.loc[long_condition, 'signal'] = 1
df.loc[short_condition, 'signal'] = -1
return df
215 changes: 215 additions & 0 deletions quants_lab/research_notebooks/01_strategy_design_supertrend.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
{
"cells": [
{
"cell_type": "markdown",
"source": [
"# RESEARCH NOTEBOOK --> SUPERTREND"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"import pandas as pd\n",
"import pandas_ta as ta # noqa: F401\n",
"\n",
"candles = pd.read_csv(\n",
" \"/Users/dardonacci/Documents/work/dashboard/data/candles/candles_binance_perpetual_WLD-USDT_3m.csv\")"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"candles.head()"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"super_trend_lenght = 20\n",
"super_trend_multiplier = 3\n",
"candles.ta.supertrend(length=super_trend_lenght, multiplier=super_trend_multiplier)"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"candles.ta.supertrend(length=super_trend_lenght, multiplier=super_trend_multiplier, append=True)"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"candles[\"date\"] = pd.to_datetime(candles[\"timestamp\"], unit='ms')\n",
"candles.head()"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"import plotly.graph_objects as go\n",
"\n",
"# We are going to use just a subset to see the graph better\n",
"candles = candles.tail(800)\n",
"\n",
"# Create a candlestick chart\n",
"fig = go.Figure(data=[go.Candlestick(\n",
" x=candles['date'],\n",
" open=candles['open'],\n",
" high=candles['high'],\n",
" low=candles['low'],\n",
" close=candles['close'])\n",
"])\n",
"fig.show()"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"super_trend_long = candles[candles[\"SUPERTd_20_3.0\"] == 1]\n",
"super_trend_short = candles[candles[\"SUPERTd_20_3.0\"] == -1]\n",
"# Add the SuperTrend line\n",
"fig.add_trace(go.Scatter(x=super_trend_long['date'], y=super_trend_long['SUPERT_20_3.0'],\n",
" mode='markers',\n",
" name='SuperTrend Long',\n",
" line=dict(color=\"green\"),\n",
" ))\n",
"# Add the SuperTrend line\n",
"fig.add_trace(go.Scatter(x=super_trend_short['date'], y=super_trend_short['SUPERT_20_3.0'],\n",
" mode='markers',\n",
" name='SuperTrend Short',\n",
" line=dict(color=\"red\")))"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"percentage_threshold = 0.01 # This is an example threshold value\n",
"\n",
"candles[\"percentage_distance\"] = abs(candles[\"close\"] - candles[\"SUPERT_20_3.0\"]) / candles[\"close\"]\n",
"\n",
"candles[\"signal\"] = 0\n",
"long_condition = (candles[\"SUPERTd_20_3.0\"] == 1) & (candles[\"percentage_distance\"] < percentage_threshold)\n",
"short_condition = (candles[\"SUPERTd_20_3.0\"] == -1) & (candles[\"percentage_distance\"] < percentage_threshold)\n",
"\n",
"candles.loc[long_condition, \"signal\"] = 1\n",
"candles.loc[short_condition, \"signal\"] = -1"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"from plotly.subplots import make_subplots\n",
"\n",
"fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.02, subplot_titles=('OHLC', 'Signal'),\n",
" row_heights=[0.7, 0.3])\n",
"\n",
"# Add candlestick\n",
"fig.add_trace(go.Candlestick(\n",
" x=candles['date'],\n",
" open=candles['open'],\n",
" high=candles['high'],\n",
" low=candles['low'],\n",
" close=candles['close']),\n",
" row=1, col=1)\n",
"\n",
"# Add the SuperTrend line\n",
"fig.add_trace(go.Scatter(x=super_trend_long['date'], y=super_trend_long['SUPERT_20_3.0'],\n",
" mode='markers',\n",
" name='SuperTrend Long',\n",
" line=dict(color=\"green\")),\n",
" row=1, col=1)\n",
"# Add the SuperTrend line\n",
"fig.add_trace(go.Scatter(x=super_trend_short['date'], y=super_trend_short['SUPERT_20_3.0'],\n",
" mode='markers',\n",
" name='SuperTrend Short',\n",
" line=dict(color=\"red\")),\n",
" row=1, col=1)\n",
"\n",
"# Add the signal line\n",
"fig.add_trace(go.Scatter(x=candles['date'], y=candles['signal'],\n",
" mode='lines',\n",
" name='SuperTrend',\n",
" line=dict(color=\"white\")),\n",
" row=2, col=1)\n",
"\n",
"# Update x-axis and grid properties\n",
"fig.update_xaxes(showline=True, linewidth=2, linecolor='grey', gridcolor='lightgrey')\n",
"fig.update_yaxes(showline=True, linewidth=2, linecolor='grey', gridcolor='lightgrey')\n",
"\n",
"# Update layout to adjust the size and title\n",
"fig.update_layout(height=800, title_text=\"OHLC Chart with SuperTrend and Signals\",\n",
" yaxis_title='Price',\n",
" xaxis_rangeslider_visible=False)\n"
],
"metadata": {
"collapsed": false
}
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Loading