Skip to content

Instantly share code, notes, and snippets.

View lamres's full-sized avatar

Sergey Malchevskiy lamres

View GitHub Profile
def show_worst_drawdown_periods(returns, top=5):
"""
Prints information about the worst drawdown periods.
Prints peak dates, valley dates, recovery dates, and net
drawdowns.
Parameters
----------
returns : pd.Series
import backtrader as bt
import pandas as pd
import numpy as np
class PivotPointLine(bt.Indicator):
lines = ('pivot_up', 'pivot_down', 'pl_value', 'direction',)
params = (
('pivot_window_len', 12),
('history_bars_as_multiple_pwl', 30)
import backtrader as bt
from PivotPointLineIndicator import PivotPointLine
# Create a Strategy
class TrendBreakerPL(bt.Strategy):
params = (
('pivot_window_len', 12),
('history_bars_as_multiple_pwl', 30),
('fixed_tp', 0.08),
('fixed_sl_as_multiple_tp', 0.15),
import backtrader.feeds as btfeed
class FinamHLOC(btfeed.GenericCSVData):
params = (
('dtformat', ('%Y%m%d')),
('tmformat', ('%H%M%S')),
('datetime', 2),
('time', 3),
('high', 5),
import backtrader as bt
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
from DataFeedFormat import FinamHLOC
from TrendBreakerPLStrategy import TrendBreakerPL
import pyfolio as pf
import seaborn as sns
sns.set_style("whitegrid")
from BacktestTrendBreakerPL import BacktestTrendBreakerPL
import backtrader as bt
import warnings
warnings.filterwarnings("ignore")
from pyswarm import pso
# The objective function for optimization
def obj_fun(x):
print('')
run_algorithm(
capital_base = 100000,
data_frequency = 'minute',
initialize = initialize,
handle_data = handle_data,
analyze = analyze,
exchange_name = 'bitfinex',
quote_currency = 'usd',
start = pd.to_datetime('2018-1-1', utc = True),
end = pd.to_datetime('2019-5-22', utc = True))
def analyze(context, perf):
sns.set()
# Summary output
print("Total return: " + str(perf.algorithm_period_return[-1]))
print("Sortino coef: " + str(perf.sortino[-1]))
print("Max drawdown: " + str(np.min(perf.max_drawdown[-1])))
print("alpha: " + str(perf.alpha[-1]))
print("beta: " + str(perf.beta[-1]))
def handle_data(context, data):
current_date = get_datetime().date()
current_time = get_datetime().time()
# Just one time in a day (first minute)
if current_time.hour == 0 and current_time.minute == 0 and current_time.second == 0:
prices = pd.DataFrame()
volumes = pd.DataFrame()
try:
def initialize(context):
context.asset = symbol('btc_usd')
context.leverage = 1.0
context.std_period = 10
context.ma_period = 10
context.price_deviation_period = 10
context.volume_deviation_period = 10
context.n_periods = 5 + int(np.max([context.std_period, context.ma_period,
context.price_deviation_period, context.volume_deviation_period]))