Skip to content

Commit

Permalink
changed rounding to 2 instead of 3
Browse files Browse the repository at this point in the history
  • Loading branch information
quantfreedom committed May 17, 2024
1 parent 710df84 commit de72cb3
Show file tree
Hide file tree
Showing 22 changed files with 319 additions and 161 deletions.
23 changes: 12 additions & 11 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,24 +1,25 @@
z_logs/
*.pkl
logs/
docs/
site/
logs/
ignore_me/

dist
numba_cache

quantfreedom.egg-info
thinking.txt

.ipynb_checkpoints
.vscode
.idea
.mypy_cache
.pytest_cache

*.mustache
*.csv
*.h5
dist
quantfreedom.egg-info
numba_cache
thinking.txt
*.todo
.todo
todo
zlogs/
*.pkl

# Byte-compiled / optimized / DLL files
__pycache__/
Expand Down Expand Up @@ -180,4 +181,4 @@ cython_debug/
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
#.idea/
55 changes: 14 additions & 41 deletions quantfreedom/backtesters/bt_regular.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,16 @@
from multiprocessing import Pool
from multiprocessing.pool import ApplyResult
from quantfreedom.helpers.custom_logger import set_loggers
from quantfreedom.helpers.helper_funcs import get_qf_score, order_records_to_df
from quantfreedom.helpers.helper_funcs import get_qf_score, order_records_to_df, make_bt_df
from quantfreedom.order_handler.order import OrderHandler
from quantfreedom.core.plotting_base import plot_or_results
from quantfreedom.core.strategy import Strategy
from quantfreedom.core.enums import (
BacktestSettings,
CandleBodyType,
CurrentFootprintCandleTuple,
DecreasePosition,
ExchangeSettings,
FootprintCandlesTuple,
OrderStatus,
RejectedOrder,
StaticOrderSettings,
or_dt,
)
from quantfreedom.helpers.utils import pretty_qf
Expand Down Expand Up @@ -113,43 +109,20 @@ def run_df_backtest(
error_callback=handler,
)
results.append(r)

print("\n" + "looping through results")
for r in results:
r.wait()

p.close()
p.join()
print("creating datafram")
column_names = (
[
"total_trades",
"wins",
"losses",
"gains_pct",
"win_rate",
"qf_score",
"fees_paid",
"total_pnl",
"ending_eq",
]
+ list(strategy.og_dos_tuple._fields)
+ list(strategy.og_ind_set_tuple._fields)
)
backtest_df = pd.DataFrame(data=strategy_result_records, columns=column_names).dropna()
backtest_df.set_index(backtest_df["settings_index"].values.astype(np.int_), inplace=True)

backtest_df["sl_bcb_type"] = backtest_df["sl_bcb_type"].apply(lambda x: CandleBodyType._fields[int(x)])
backtest_df["trail_sl_bcb_type"] = backtest_df["trail_sl_bcb_type"].apply(lambda x: CandleBodyType._fields[int(x)])
backtest_df["sl_to_be_cb_type"] = backtest_df["sl_to_be_cb_type"].apply(lambda x: CandleBodyType._fields[int(x)])
backtest_df["account_pct_risk_per_trade"] = backtest_df["account_pct_risk_per_trade"].apply(
lambda x: round(x * 100, 2)

backtest_df = make_bt_df(
strategy=strategy,
strategy_result_records=strategy_result_records,
)
backtest_df["sl_based_on_add_pct"] = backtest_df["sl_based_on_add_pct"].apply(lambda x: round(x * 100, 2))
backtest_df["sl_to_be_when_pct"] = backtest_df["sl_to_be_when_pct"].apply(lambda x: round(x * 100, 2))
backtest_df["trail_sl_by_pct"] = backtest_df["trail_sl_by_pct"].apply(lambda x: round(x * 100, 2))
backtest_df["trail_sl_when_pct"] = backtest_df["trail_sl_when_pct"].apply(lambda x: round(x * 100, 2))
backtest_df.sort_values("gains_pct", ascending=False, inplace=True)

return backtest_df


Expand Down Expand Up @@ -360,7 +333,7 @@ def multiprocess_backtest(
raise Exception(f"Exception hit in eval strat -> {e}")

# Checking if gains
gains_pct = round(((order.equity - starting_equity) / starting_equity) * 100, 3)
gains_pct = round(((order.equity - starting_equity) / starting_equity) * 100, 2)
wins_and_losses_array = pnl_array[~np.isnan(pnl_array)]
total_trades_closed = wins_and_losses_array.size
logger.debug(
Expand Down Expand Up @@ -388,7 +361,7 @@ def multiprocess_backtest(
win_loss = np.where(wins_and_losses_array_no_be < 0, 0, 1)
wins = np.count_nonzero(win_loss)
losses = win_loss.size - wins
win_rate = round(wins / win_loss.size * 100, 3)
win_rate = round(wins / win_loss.size * 100, 2)

total_pnl = wins_and_losses_array.sum()
tuple_results = (
Expand All @@ -399,7 +372,7 @@ def multiprocess_backtest(
gains_pct,
win_rate,
qf_score,
round(total_fees_paid, 3),
round(total_fees_paid, 2),
total_pnl,
order.equity,
)
Expand Down Expand Up @@ -429,11 +402,11 @@ def handler(error):

def or_backtest(
candles: FootprintCandlesTuple,
disable_logger: bool,
strategy: Strategy,
set_idx: int,
plot_results: bool = False,
disable_logger: bool = True,
logger_level: str = "INFO",
plot_results: bool = False,
):
if disable_logger:
set_loggers(
Expand Down Expand Up @@ -481,9 +454,9 @@ def or_backtest(
order_records = np.empty(shape=int(total_bars / 3), dtype=or_dt)

for bar_index in range(strategy.static_os_tuple.starting_bar - 1, total_bars):
logger.info("\n\n")
logger.debug("\n\n")
datetime = candles.candle_open_datetimes[bar_index]
logger.info(f"set_idx= {set_idx} bar_idx= {bar_index} datetime= {datetime}")
logger.debug(f"set_idx= {set_idx} bar_idx= {bar_index} datetime= {datetime}")

if order.position_size_usd > 0:
try:
Expand Down
23 changes: 23 additions & 0 deletions quantfreedom/core/plotting_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,29 @@ def plot_or_results(
)
except:
pass
try:
# avg Entries
fig.add_trace(
go.Scatter(
x=entries_dt,
y=entries_df["average_entry"],
mode="markers",
name="Avgerage Entries",
marker=dict(
size=10,
symbol="circle",
color="#DE66FF",
line=dict(
width=1,
color="DarkSlateGrey",
),
),
),
col=1,
row=1,
)
except:
pass
try:
fig.add_trace(
# Stop Losses
Expand Down
10 changes: 5 additions & 5 deletions quantfreedom/core/strategy.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,17 +132,17 @@ def set_cur_dos_tuple(
logger.info(
f"""
Settings Index= {self.og_dos_tuple.settings_index[set_idx]}
account_pct_risk_per_trade={round(self.cur_dos_tuple.account_pct_risk_per_trade * 100, 3)}
account_pct_risk_per_trade={round(self.cur_dos_tuple.account_pct_risk_per_trade * 100, 2)}
max_trades={self.cur_dos_tuple.max_trades}
risk_reward={self.cur_dos_tuple.risk_reward}
sl_based_on_add_pct={round(self.cur_dos_tuple.sl_based_on_add_pct * 100, 3)}
sl_based_on_add_pct={round(self.cur_dos_tuple.sl_based_on_add_pct * 100, 2)}
sl_based_on_lookback={self.cur_dos_tuple.sl_based_on_lookback}
sl_bcb_type={self.cur_dos_tuple.sl_bcb_type}
sl_to_be_cb_type={self.cur_dos_tuple.sl_to_be_cb_type}
sl_to_be_when_pct={round(self.cur_dos_tuple.sl_to_be_when_pct * 100, 3)}
sl_to_be_when_pct={round(self.cur_dos_tuple.sl_to_be_when_pct * 100, 2)}
trail_sl_bcb_type={self.cur_dos_tuple.trail_sl_bcb_type}
trail_sl_by_pct={round(self.cur_dos_tuple.trail_sl_by_pct * 100, 3)}
trail_sl_when_pct={round(self.cur_dos_tuple.trail_sl_when_pct * 100, 3)}
trail_sl_by_pct={round(self.cur_dos_tuple.trail_sl_by_pct * 100, 2)}
trail_sl_when_pct={round(self.cur_dos_tuple.trail_sl_when_pct * 100, 2)}
"""
)

Expand Down
2 changes: 1 addition & 1 deletion quantfreedom/helpers/email_sender.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def email_plotting(

def email_pnl(self, pnl: float):
subject = "Updated PNL"
body = f"We got a new pnl ... i hope it is positive ${round(pnl, 3)}"
body = f"We got a new pnl ... i hope it is positive ${round(pnl, 2)}"
self._send_email(subject=subject, body=body)

def email_error_msg(self, msg):
Expand Down
47 changes: 46 additions & 1 deletion quantfreedom/helpers/helper_funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import pandas as pd
from logging import getLogger
from datetime import datetime
from quantfreedom.core.enums import AccountState, FootprintCandlesTuple, OrderResult
from quantfreedom.core.enums import CandleBodyType, FootprintCandlesTuple
from quantfreedom.core.strategy import Strategy
from quantfreedom.exchanges.binance_usdm import BinanceUSDM
from quantfreedom.exchanges.bybit import Bybit
Expand Down Expand Up @@ -261,3 +261,48 @@ def order_records_to_df(
{0: np.nan}
)
return order_records_df


def make_bt_df(
strategy: Strategy,
strategy_result_records: np.ndarray,
):
def cbt_to_field(x):
field_name = CandleBodyType._fields[int(x)]
return field_name

def rounder(x):
rounded = round(x * 100, 2)
return rounded

column_names = (
[
"total_trades",
"wins",
"losses",
"gains_pct",
"win_rate",
"qf_score",
"fees_paid",
"total_pnl",
"ending_eq",
]
+ list(strategy.og_dos_tuple._fields)
+ list(strategy.og_ind_set_tuple._fields)
)
backtest_df = pd.DataFrame(data=strategy_result_records, columns=column_names).dropna()
backtest_df.set_index(backtest_df["settings_index"].values.astype(np.int_), inplace=True)

backtest_df["sl_bcb_type"] = backtest_df["sl_bcb_type"].apply(cbt_to_field)
backtest_df["trail_sl_bcb_type"] = backtest_df["trail_sl_bcb_type"].apply(cbt_to_field)
backtest_df["sl_to_be_cb_type"] = backtest_df["sl_to_be_cb_type"].apply(cbt_to_field)

backtest_df["account_pct_risk_per_trade"] = backtest_df["account_pct_risk_per_trade"].apply(rounder)
backtest_df["sl_based_on_add_pct"] = backtest_df["sl_based_on_add_pct"].apply(rounder)
backtest_df["sl_to_be_when_pct"] = backtest_df["sl_to_be_when_pct"].apply(rounder)
backtest_df["trail_sl_by_pct"] = backtest_df["trail_sl_by_pct"].apply(rounder)
backtest_df["trail_sl_when_pct"] = backtest_df["trail_sl_when_pct"].apply(rounder)

backtest_df.sort_values("gains_pct", ascending=False, inplace=True)

return backtest_df
2 changes: 1 addition & 1 deletion quantfreedom/helpers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def generate_candles(

periods = number_of_candles * 48

prices = np.around(30000 + np.random.normal(scale=1, size=periods).cumsum(), 3)
prices = np.around(30000 + np.random.normal(scale=1, size=periods).cumsum(), 2)

data = pd.DataFrame(
prices,
Expand Down
12 changes: 4 additions & 8 deletions quantfreedom/nb_funcs/nb_helper_funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def nb_get_qf_score(

if gains_pct <= 0:
qf_score = -(qf_score)
return round(qf_score, 3)
return round(qf_score, 2)


@njit(cache=True)
Expand Down Expand Up @@ -184,7 +184,7 @@ def nb_float_to_str(x: float):
else:
offset_x = x
l1, l2 = nb_get_n_digits(x)
l2 = max(1, 3) # Will have at least .0
l2 = max(1, 2) # Will have at least .0

use_dec = l2 > 0

Expand Down Expand Up @@ -262,12 +262,8 @@ def nb_fill_order_records(
order_records["position_size_asset"] = order_result.position_size_asset
order_records["position_size_usd"] = order_result.position_size_usd
order_records["realized_pnl"] = account_state.realized_pnl
order_records["sl_pct"] = round(order_result.sl_pct * 100, 3)
order_records["sl_pct"] = round(order_result.sl_pct * 100, 2)
order_records["sl_price"] = order_result.sl_price
order_records["tp_pct"] = round(order_result.tp_pct * 100, 3)
order_records["tp_pct"] = round(order_result.tp_pct * 100, 2)
order_records["tp_price"] = order_result.tp_price
return or_index + 1




Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def nb_long_pnl_calc(
exit_price: float,
position_size_asset: float,
):
return round((exit_price - average_entry) * position_size_asset, 3) # math checked
return round((exit_price - average_entry) * position_size_asset, 2) # math checked


@njit(cache=True)
Expand All @@ -19,7 +19,7 @@ def nb_short_pnl_calc(
exit_price: float,
position_size_asset: float,
):
return round((average_entry - exit_price) * position_size_asset, 3) # math checked
return round((average_entry - exit_price) * position_size_asset, 2) # math checked


@njit(cache=True)
Expand Down Expand Up @@ -47,10 +47,10 @@ def nb_decrease_position(
fee_open = position_size_asset * average_entry * market_fee_pct # math checked
fee_close = position_size_asset * exit_price * exit_fee_pct # math checked
fees_paid = fee_open + fee_close # math checked
realized_pnl = round(pnl - fees_paid, 3) # math checked
realized_pnl = round(pnl - fees_paid, 2) # math checked

# Setting new equity
equity = round(realized_pnl + equity, 3)
equity = round(realized_pnl + equity, 2)
logger(
"nb_decrease_position.py - nb_decrease_position() -"
+ "\nrealized_pnl= "
Expand Down
Loading

0 comments on commit de72cb3

Please sign in to comment.