Skip to content

Commit

Permalink
debug
Browse files Browse the repository at this point in the history
  • Loading branch information
VladKochetov007 committed Apr 20, 2022
1 parent 8046c8b commit b7a66b3
Show file tree
Hide file tree
Showing 12 changed files with 1,607 additions and 7,451 deletions.
9 changes: 2 additions & 7 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,20 +1,15 @@
*/__pycache__
__pycache__
__pycache__/
*.log
MANIFEST
build
dist
.pypirc
*.pyc
.pyc
quick_trade.egg-info
.DS_Store
*.dat
/__pycache__
/*__pycache__
**/__pycache__
*__pycache__
**__pycache__
__pycache__/
*.py[cod]
*.csv
!examples/dataframes/BNBUSDT1d.csv
3 changes: 2 additions & 1 deletion examples/price_channel_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,6 @@

trader.connect_graph(graph)

trader.strategy_price_channel(100, 100, 1)
trader.strategy_price_channel()
trader.inverse_strategy() # trend strategy
trader.backtest(deposit=300, commission=0.075)
3,193 changes: 745 additions & 2,448 deletions examples/volatility_validation3/returns-0.json

Large diffs are not rendered by default.

5,720 changes: 766 additions & 4,954 deletions examples/volatility_validation3/volatility_tuner_global.json

Large diffs are not rendered by default.

12 changes: 8 additions & 4 deletions examples/walkforward_2.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from quick_trade.tuner.avoid_overfitting import WalkForward
from quick_trade.trading_sys import ExampleStrategies
from quick_trade.tuner import Arange
from quick_trade.tuner import Arange, Linspace
from custom_client import BinanceTradingClient

from quick_trade.plots import BasePlotlyGraph, make_figure
Expand All @@ -10,16 +10,19 @@
[
{
'plot': False,
'window': Arange(10, 200, 20),
'window': Arange(10, 200, 5),
'window_dev': 1
}
]
}
sample_length = 2*24*30*2

graph = BasePlotlyGraph(make_figure(700, 1400))

client = BinanceTradingClient()
walkforward_optimizer = WalkForward(client=client)
walkforward_optimizer = WalkForward(client=client,
chunk_length=sample_length,
insample_chunks=4)

walkforward_optimizer.run_analysis('ETH/USDT',
'30m',
Expand All @@ -35,7 +38,8 @@
color='white')
graph.plot_line(line=walkforward_optimizer.average_growth,
width=2,
color='blue')
color='blue',
name='exponential regression')
print(walkforward_optimizer.info())
graph.log_y()
graph.show()
17 changes: 9 additions & 8 deletions examples/walkforward_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@

ticker = 'BTC/USDT'
timeframe = '1h'
validation_split = 0.
validation_split = 0
sort_by = 'profit/deviation ratio'

fig = BasePlotlyGraph(make_figure(rows=2))
client = BinanceTradingClient()
df = client.get_data_historical(ticker, interval=timeframe)
df = df[:len(df)*2//3]

chunk_len = len(df)//10

chunk_len = len(df)//15

splits = slice_frame(df, validation_split=validation_split)
df_train = splits['train']
Expand All @@ -35,11 +36,11 @@
tuner_configs = [
{
'strategy_bollinger_breakout':
[
[
{'window_dev': 1,
'plot': False,
'window': Arange(20, 100, 5)}
]
'window': Arange(5, 200, 10)}
]
}
]
for cfg in tuner_configs:
Expand All @@ -55,7 +56,7 @@
config=config,
tuner_instance=QuickTradeTuner,
trader_instance=ExampleStrategies,
sort_by='profit/deviation ratio',
sort_by=sort_by,
commission=0.12)
results.append(WF_train.profit_deviation_ratio)
trains.append(WF_train)
Expand All @@ -70,7 +71,7 @@
config=best_config,
tuner_instance=QuickTradeTuner,
trader_instance=ExampleStrategies,
sort_by='profit/deviation ratio',
sort_by=sort_by,
commission=0.12)
print(WF_val.info())

Expand Down
24 changes: 17 additions & 7 deletions quick_trade/indicators.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import numpy as np
import pandas as pd
import ta.volatility
from numpy import nan
from pandas import DataFrame
from pandas import Series
from ta.volatility import AverageTrueRange
from .utils import BUY, SELL
from typing import Union

class Indicator:
pass
Expand Down Expand Up @@ -102,16 +104,14 @@ def __init__(self,
self._part = channel_part
self._run()

def __run_lev(self, func, period):
channel = [np.nan] * period
for roll in self._low.rolling(period):
@staticmethod
def _run_lev(func, period, prices):
channel = []
for roll in prices.rolling(period):
channel.append(func(roll))
return channel

def _run(self):
support = self.__run_lev(lambda x: x.min(), self._support_period)
resistance = self.__run_lev(lambda x: x.max(), self._resistance_period)

def _handle_levels(self, support, resistance):
self.high = []
self.low = []

Expand All @@ -125,6 +125,16 @@ def _run(self):
self.high.append(new_high)
self.low.append(new_low)

def _run(self):
support = self._run_lev(lambda x: x.min(),
self._support_period,
self._low)
resistance = self._run_lev(lambda x: x.max(),
self._resistance_period,
self._high)
self._handle_levels(support=support,
resistance=resistance)

def higher_line(self):
return self.high

Expand Down
18 changes: 9 additions & 9 deletions quick_trade/plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,24 +298,24 @@ def connect_analyzer(self, analyzer):
self.analyzer.fig = self

def plot_frame(self):
if utils.STOP_BEFORE_INTEGER_AS_INDEX:
if utils.VALIDATION_ANALYSIS_INTEGER_AS_INDEX:
index = None
else:
index = self.analyzer.profit_keys
self.plot_line(line=self.analyzer.frame['train'],
index=index,
width=utils.STOP_BEFORE_TRAIN_WIDTH,
opacity=utils.STOP_BEFORE_TRAIN_ALPHA,
color=utils.STOP_BEFORE_TRAIN_COLOR,
name=utils.STOP_BEFORE_TRAIN_NAME,
width=utils.VALIDATION_ANALYSIS_TRAIN_WIDTH,
opacity=utils.VALIDATION_ANALYSIS_TRAIN_ALPHA,
color=utils.VALIDATION_ANALYSIS_TRAIN_COLOR,
name=utils.VALIDATION_ANALYSIS_TRAIN_NAME,
_row=self.test_row,
_col=self.test_col)

self.plot_line(line=self.analyzer.frame['validation'],
index=index,
width=utils.STOP_BEFORE_VAL_WIDTH,
opacity=utils.STOP_BEFORE_VAL_ALPHA,
color=utils.STOP_BEFORE_VAL_COLOR,
name=utils.STOP_BEFORE_VAL_NAME,
width=utils.VALIDATION_ANALYSIS_VAL_WIDTH,
opacity=utils.VALIDATION_ANALYSIS_VAL_ALPHA,
color=utils.VALIDATION_ANALYSIS_VAL_COLOR,
name=utils.VALIDATION_ANALYSIS_VAL_NAME,
_row=self.test_row,
_col=self.test_col)
26 changes: 25 additions & 1 deletion quick_trade/trading_sys.py
Original file line number Diff line number Diff line change
Expand Up @@ -1152,6 +1152,14 @@ def trailing_stop(self):
sl = sl_before
self.stop_losses[i] = sl

def profit_distribution(self, steps: int = 100) -> pd.Series:
equity = np.array(self.deposit_history)
x_returns = equity[:-1] / equity[1:]

hist = np.histogram(x_returns, steps)
return pd.Series(hist[0], index=hist[1][:-1])


class ExampleStrategies(Trader):

def _window_(self,
Expand Down Expand Up @@ -1911,7 +1919,8 @@ def strategy_pump_detector(self,
def strategy_price_channel(self,
support_period: int = 20,
resistance_period: int = 20,
channel_part: float = 0.8):
channel_part: float = 0.8,
plot: bool = True):
PC = indicators.PriceChannel(high=self.df['High'],
low=self.df['Low'],
support_period=support_period,
Expand All @@ -1926,3 +1935,18 @@ def strategy_price_channel(self,
elif price < low:
flag = utils.BUY
self.returns.append(flag)
if plot:
self.fig.plot_line(PC.lower_line(),
width=utils.PRICE_CHANNEL_LOWER_WIDTH,
color=utils.PRICE_CHANNEL_LOWER_COLOR,
name=utils.PRICE_CHANNEL_LOWER_NAME,
opacity=utils.PRICE_CHANNEL_LOWER_ALPHA,
_row=self.fig.data_row,
_col=self.fig.data_col)
self.fig.plot_line(PC.higher_line(),
width=utils.PRICE_CHANNEL_UPPER_WIDTH,
color=utils.PRICE_CHANNEL_UPPER_COLOR,
name=utils.PRICE_CHANNEL_UPPER_NAME,
opacity=utils.PRICE_CHANNEL_UPPER_ALPHA,
_row=self.fig.data_row,
_col=self.fig.data_col)
3 changes: 2 additions & 1 deletion quick_trade/tuner/tuner.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ def tune(
else:
df = DataFrame()
frames = {t: self._get_df(ticker=t, interval=interval, limit=limit) for t in ticker}
if '_dataframes' in backtest_kwargs:
backtest_kwargs['_dataframes'] = frames
for strategy, kwargs in self._strategies:
trader = trading_class(ticker='ALL/ALL' if self.multi_test else ticker, df=df, interval=interval)
trader.set_client(self.client)
Expand All @@ -106,7 +108,6 @@ def tune(
for ticker_ in ticker:
kwargs_m[ticker_] = [{strategy: kwargs}]
trader.multi_backtest(test_config=kwargs_m,
_dataframes=frames,
**backtest_kwargs)
else:
trader._get_attr(strategy)(**kwargs)
Expand Down
31 changes: 21 additions & 10 deletions quick_trade/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,17 +162,28 @@
LOWER_BB_WIDTH: float = 2
LOWER_BB_ALPHA: float = 1.0

STOP_BEFORE_TRAIN_NAME: str = 'train'
STOP_BEFORE_TRAIN_COLOR: str = 'red'
STOP_BEFORE_TRAIN_WIDTH: float = 1.0
STOP_BEFORE_TRAIN_ALPHA: float = 1.0
VALIDATION_ANALYSIS_TRAIN_NAME: str = 'train'
VALIDATION_ANALYSIS_TRAIN_COLOR: str = 'red'
VALIDATION_ANALYSIS_TRAIN_WIDTH: float = 1.0
VALIDATION_ANALYSIS_TRAIN_ALPHA: float = 1.0

STOP_BEFORE_VAL_NAME: str = 'validation'
STOP_BEFORE_VAL_COLOR: str = 'green'
STOP_BEFORE_VAL_WIDTH: float = 1.0
STOP_BEFORE_VAL_ALPHA: float = 1.0
VALIDATION_ANALYSIS_VAL_NAME: str = 'validation'
VALIDATION_ANALYSIS_VAL_COLOR: str = 'green'
VALIDATION_ANALYSIS_VAL_WIDTH: float = 1.0
VALIDATION_ANALYSIS_VAL_ALPHA: float = 1.0

VALIDATION_ANALYSIS_INTEGER_AS_INDEX: bool = True

PRICE_CHANNEL_LOWER_NAME: str = 'price channel lower'
PRICE_CHANNEL_LOWER_COLOR: str = 'green'
PRICE_CHANNEL_LOWER_WIDTH: float = 1.0
PRICE_CHANNEL_LOWER_ALPHA: float = 1.0

PRICE_CHANNEL_UPPER_NAME: str = 'price channel upper'
PRICE_CHANNEL_UPPER_COLOR: str = 'red'
PRICE_CHANNEL_UPPER_WIDTH: float = 1.0
PRICE_CHANNEL_UPPER_ALPHA: float = 1.0

STOP_BEFORE_INTEGER_AS_INDEX: bool = True

RESERVE: float = 0.99 # squeeze-protect

Expand All @@ -188,7 +199,7 @@
max drawdown: {}%
profit/deviation ratio: {}""" # .format(Trader.losses, Trader.trades, ...)

__version__: str = "7.9.0"
__version__: str = "7.9.1"
__author__: str = 'Vlad Kochetov'
__credits__: List[str] = [
"Hemerson Tacon -- Stack overflow",
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
with open('README.md') as file:
long_desc = file.read()

__version__ = "7.9.0"
__version__ = "7.9.1"

setup(
name='quick_trade',
Expand Down

0 comments on commit b7a66b3

Please sign in to comment.