edtechre / pybroker

Algorithmic Trading in Python with Machine Learning
https://www.pybroker.com
Other
2.09k stars 261 forks source link

[Question] symbol for indicator but not for trading #99

Closed none2003 closed 9 months ago

none2003 commented 10 months ago

Hello all,

There is a strategy: if the S&P 500 is bullish, then go long on individual stocks (based on some indicators on individual stocks), otherwise short.

Since the S&P 500 is only used as a condition and not for trading, it's obviously not appropriate to put it in the symbols parameter of strategy.add_execution along with other individual stocks.

Currently, my approach is to generate bullish/bearish signal of S&P 500 as a series and merge it into each individual stock's df, as the datasource of pyb strategy, then register_columns and use it in the trading funtion during backtesting, which is very tedious, is there a better way to do it?

Thanks.

edtechre commented 9 months ago

Hi @none2003,

I believe calculating this signal yourself as an additional DataFrame column is a good way to handle this.

Alternatively, you could place SPY into the list of symbols and then choose to ignore the trading rules for it in your execution:

if ctx.symbol == "SPY":
   return
# Run trading rules

You can then get data for SPY or any another symbol using ctx.foreign.