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

80 strategies validations metrics #106

Draft
wants to merge 19 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
6464f4b
added 1 line to test errors (all with 0 are fine)
jmaskiew Nov 11, 2022
ba252e1
place for benchmark model. As I need to reinstall sp2137 let it be here
jmaskiew Nov 11, 2022
b1da346
place for benchmark model. As I need to reinstall sp2137 let it be here
jmaskiew Nov 11, 2022
40ac2ae
place for benchmark model. As I need to reinstall sp2137 let it be here
jmaskiew Nov 11, 2022
5fac060
place for benchmark model. As I need to reinstall sp2137 let it be here
jmaskiew Nov 11, 2022
a73ad19
new type of trading method for benchmark
jmaskiew Nov 12, 2022
b6f41c8
add type of trading used for benchmark
jmaskiew Nov 12, 2022
e22eb67
Merge branch 'master' of https://github.com/lpiekarski/SP2137
jmaskiew Nov 14, 2022
c3075dd
Merge branch 'master' of https://github.com/lpiekarski/SP2137 into 76…
jmaskiew Nov 15, 2022
0a41102
edited code to make write errors
jmaskiew Nov 15, 2022
92a5239
edited code to make write errors
jmaskiew Nov 15, 2022
a0da3fa
edited code to make write errors
jmaskiew Nov 15, 2022
ea77b0f
edited code to make write errors
jmaskiew Nov 15, 2022
f77f878
edited code to make write errors
jmaskiew Nov 15, 2022
503ece0
edited code to know where are possible errors
jmaskiew Nov 15, 2022
ecf97f5
Merge branch 'master' of https://github.com/lpiekarski/SP2137 into 95…
jmaskiew Nov 15, 2022
acf01bc
benchmark + cagr ratio
jmaskiew Nov 17, 2022
01c0e9e
Merge branch 'master' into 80-strategies-validations-metrics
lpiekarski Nov 17, 2022
ee34c64
Update labels.py
lpiekarski Nov 17, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added commons/validation/__init__.py
Empty file.
59 changes: 59 additions & 0 deletions commons/validation/benchmark.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
from backtesting import Backtest, Strategy

import warnings
import pandas as pd
import numpy as np


np.seterr(divide='ignore')


def func_benchmark(dataset, cash, time_tag):
df = dataset.df
data = df.resample(f'{time_tag}').agg({
'Open': 'first',
'High': 'max',
'Low': 'min',
'Close': 'last'})
data["B"] = data['Open'] <= data['Open'].shift(-1)

if data.loc[data.index[-1], f'Open'] < data.loc[data.index[-1], f'Close']:
data.loc[data.index[-1], 'B'] = 1
else:
data.loc[data.index[-1], 'B'] = 0

y_pred = data["B"].shift(0)
y_pred = pd.concat([y_pred, y_pred.iloc[:1]])
data = pd.concat([df.iloc[:2], data])

class benchmark(Strategy):
def init(self):
self.id = 0

def next(self):
self.position.close()
pred = y_pred[self.id]
if pred > 0.5:
self.buy()
elif pred < 0.5:
self.sell()
self.id += 1

bt = Backtest(data,
benchmark,
cash=cash,
commission=0,
exclusive_orders=True)

stats = bt.run()
return stats['Equity Final [$]']


BENCHMARK = ['10y', '1y', '2Q', '1Q', '1m', '1w']


def benchmark(df, cash, equity):
for params in BENCHMARK:
if equity < func_benchmark(df, cash, params):
return params
break
2 changes: 2 additions & 0 deletions commons/validation/cagr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
def cagr_ratio(equity_strat, equity_end, time):
return ((equity_end / equity_strat)**(1 / time) - 1) * 100
13 changes: 13 additions & 0 deletions model/steps/run_backtesting.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import json
import logging
import pandas as pd

from backtesting import Backtest, Strategy

from commons.drivepath import cache
from commons.timing import step
from commons.validation.cagr import cagr_ratio
from commons.validation.benchmark import benchmark
from commons.data.utils import log_change

LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -38,6 +42,15 @@ def run_backtesting(
trade_on_close=True)

backtest_results = bt.run()
benchmark_lvl = benchmark(dataset,
starting_cash,
backtest_results['Equity Final [$]'])
cagr = cagr_ratio(starting_cash,
backtest_results['Equity Final [$]'],
backtest_results['Duration'].days / 365.25)
backtest_results = pd.DataFrame(backtest_results)
#backtest_results["CAGR Ratio"] = cagr
#backtest_results["Benchmark"] = benchmark_lvl
LOGGER.info(backtest_results)
bt.plot(resample=False)
return dict(backtest=bt, backtest_results=backtest_results)