27 lines
880 B
Python
27 lines
880 B
Python
"""Signal-driven multi-stock strategy."""
|
|
import backtrader as bt
|
|
import pandas as pd
|
|
|
|
|
|
class AlphaStrategy(bt.Strategy):
|
|
"""Trade each feed based on its precomputed ``signal`` line.
|
|
|
|
The strategy delegates the buy/sell/hold decision to a portfolio builder
|
|
(e.g. ``ThresholdBuilder``) and sizes entries with ``order_target_percent``.
|
|
"""
|
|
|
|
def __init__(self, builder):
|
|
self.builder = builder
|
|
|
|
def next(self):
|
|
for data in self.datas:
|
|
sig = data.signal[0]
|
|
if pd.isna(sig):
|
|
continue
|
|
in_position = bool(self.getposition(data).size)
|
|
action = self.builder.build(float(sig), in_position)
|
|
if action.action == "buy":
|
|
self.order_target_percent(data=data, target=action.size_pct)
|
|
elif action.action == "sell":
|
|
self.close(data=data)
|