You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm struggling with this: how do I limit the entries to only 930-1030? I know there's the discussion here (#156) and the Jupyter notebook here (https://nbviewer.org/github/polakowo/vectorbt/blob/master/examples/TradingSessions.ipynb) but I'm lost to how this applies to my use case and I get different errors depending on what I try. I've tried to simplify the code as much as possible. Here it is:
import pandas as pd
import numpy as np
import vectorbt as vbt
import glob
from pathlib import Path
from IPython.display import display
df_gapper_list = []
df_intraday_analysis = []
def GET_CHARTS(date, ticker):
folder = "intraday_bars_gapped_new/{}*.csv".format(ticker)
take_profit = 1
for fname in glob.glob(folder)[:25]:
ticker = Path(fname).stem
df = pd.read_csv(fname, index_col='datetime', usecols=["open", "high", "low", "close", "volume", "datetime", "date", "time"], parse_dates=True)
# get the current day bars
df_current_day = df[(df['date'] == date)]
# get the market hours
df_market_hours_idx = df_current_day.between_time('9:30', '16:00', include_end=True).index
df_market_hours = df_current_day.loc[df_market_hours_idx]
# get the first hour of the open
df_open_hours_idx = df_current_day.between_time('9:30', '10:30', include_end=True).index
df_open_hours = df_current_day.loc[df_open_hours_idx]
# only enter during open bars
df_open_hours['bull_c'] = np.where(((df_open_hours['close'] < df_open_hours['open'])), True, False)
# just a placeholder so it runs
df_current_day['bear_c'] = np.where((df_current_day['close'] >= (df_current_day['open'] + take_profit)), True, False)
entries = df_open_hours['bull_c']
exits = df_current_day['bear_c']
# return the entries / exits which are inside the open and market hours
entries = entries[df_open_hours_idx]
exits = exits[df_market_hours_idx]
if not df_market_hours.empty:
pf = vbt.Portfolio.from_signals(df_market_hours['close'], entries, exits, fees=0.005, sl_stop=0.05)
print(pf.stats())
pf.trades.plot().show_svg()
# print(df_current_day.[0], 'df_current_day')
fig = df_market_hours.vbt.ohlcv.plot()
fig.show_svg()
df = pd.read_csv('mikeys-spreadsheet.csv', usecols=['date', 'ticker', 'PM 200 ema hit'])
# return only the days where the 200 ema was not hit during pre market
df_filtered = df[df['PM 200 ema hit'] == False]
for index, row in df_filtered.iterrows():
date, ticker = row['date'], row['ticker']
GET_CHARTS(date, ticker)
And here's the error:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
c:\Users\audac\Documents\trading\backtesting\vectorbt.ipynb Cell 2' in <cell line: 44>()
44 for index, row in df_filtered.iterrows():
45 date, ticker = row['date'], row['ticker']
---> 46 GET_CHARTS(date, ticker)
c:\Users\audac\Documents\trading\backtesting\vectorbt.ipynb Cell 2' in GET_CHARTS(date, ticker)
29 exits = exits[df_market_hours_idx]
31 if not df_market_hours.empty:
---> 32 pf = vbt.Portfolio.from_signals(df_market_hours['close'], entries, exits, fees=0.005, sl_stop=0.05)
33 print(pf.stats())
34 pf.trades.plot().show_svg()
File c:\Users\audac\anaconda3\envs\vectorbt\lib\site-packages\vectorbt\portfolio\base.py:2898, in Portfolio.from_signals(cls, close, entries, exits, short_entries, short_exits, signal_func_nb, signal_args, size, size_type, price, fees, fixed_fees, slippage, min_size, max_size, size_granularity, reject_prob, lock_cash, allow_partial, raise_reject, log, accumulate, upon_long_conflict, upon_short_conflict, upon_dir_conflict, upon_opposite_entry, direction, val_price, open, high, low, sl_stop, sl_trail, tp_stop, stop_entry_price, stop_exit_price, upon_stop_exit, upon_stop_update, adjust_sl_func_nb, adjust_sl_args, adjust_tp_func_nb, adjust_tp_args, use_stops, init_cash, cash_sharing, call_seq, ffill_val_price, update_value, max_orders, max_logs, seed, group_by, broadcast_named_args, broadcast_kwargs, template_mapping, wrapper_kwargs, freq, attach_call_seq, **kwargs)
2893 keep_raw[close_idx] = False
2894 broadcast_kwargs = merge_dicts(dict(
2895 keep_raw=keep_raw,
2896 require_kwargs=dict(requirements='W')
2897 ), broadcast_kwargs)
-> 2898 broadcasted_args = broadcast(*broadcastable_args.values(), **broadcast_kwargs)
2899 broadcasted_args = dict(zip(broadcastable_args.keys(), broadcasted_args))
2900 close = broadcasted_args['close']
File c:\Users\audac\anaconda3\envs\vectorbt\lib\site-packages\vectorbt\base\reshape_fns.py:567, in broadcast(to_shape, to_pd, to_frame, align_index, align_columns, index_from, columns_from, require_kwargs, keep_raw, return_meta, *args, **kwargs)
565 # Get final shape
566 if to_shape is None:
--> 567 to_shape = _broadcast_shape(*map(np.asarray, arr_args_2d))
569 # Perform broadcasting
570 new_args = []
File c:\Users\audac\anaconda3\envs\vectorbt\lib\site-packages\numpy\lib\stride_tricks.py:421, in _broadcast_shape(*args)
416 """Returns the shape of the arrays that would result from broadcasting the
417 supplied arrays against each other.
418 """
419 # use the old-iterator because np.nditer does not handle size 0 arrays
420 # consistently
--> 421 b = np.broadcast(*args[:32])
422 # unfortunately, it cannot handle 32 or more arguments directly
423 for pos in range(32, len(args), 31):
424 # ironically, np.broadcast does not properly handle np.broadcast
425 # objects (it treats them as scalars)
426 # use broadcasting to avoid allocating the full array
ValueError: shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 23 with shape (185,) and arg 31 with shape (4,).
Can someone please point me in the right direction please?
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
I'm struggling with this: how do I limit the entries to only 930-1030? I know there's the discussion here (#156) and the Jupyter notebook here (https://nbviewer.org/github/polakowo/vectorbt/blob/master/examples/TradingSessions.ipynb) but I'm lost to how this applies to my use case and I get different errors depending on what I try. I've tried to simplify the code as much as possible. Here it is:
And here's the error:
Can someone please point me in the right direction please?
Beta Was this translation helpful? Give feedback.
All reactions