|
| 1 | +from abc import ABC |
| 2 | +from typing import Dict, Optional |
| 3 | + |
| 4 | +import pandas as pd |
| 5 | + |
| 6 | +from contracts.asset import Asset, CashAsset |
| 7 | +from core.market_data import MarketData |
| 8 | +from strategies.stock.base import StrategyBase, StrategyFactory |
| 9 | + |
| 10 | + |
| 11 | +@StrategyFactory.register("stoploss") |
| 12 | +class StoplossStrategy(StrategyBase, ABC): |
| 13 | + def __init__(self, **kwargs): |
| 14 | + self.lookback_period = 7 |
| 15 | + self.has_bought: Optional[float] = None |
| 16 | + self.trail_pct: float = kwargs.get("trail_pct", 0.04) |
| 17 | + |
| 18 | + def get_name(self) -> str: |
| 19 | + return "stoploss" |
| 20 | + |
| 21 | + def get_config(self) -> Dict: |
| 22 | + return { |
| 23 | + "type": self.get_name() |
| 24 | + } |
| 25 | + |
| 26 | + def generate_signals(self, price_data: pd.DataFrame | Dict[str, pd.DataFrame], current_date: pd.Timestamp, |
| 27 | + positions: Dict[str, Asset], cash: float, **kwargs) -> Optional[Dict[str, int]]: |
| 28 | + """ |
| 29 | + Buy once and hold till perpetuity for the strategy. |
| 30 | + :param price_data: A DataFrame or dict of DataFrames containing price data for each asset. |
| 31 | + :param cash: |
| 32 | + :param current_date: |
| 33 | + :param positions: |
| 34 | + :return: |
| 35 | + """ |
| 36 | + ticker = list(positions.keys())[0] # Single ticker strategy |
| 37 | + signals = {} |
| 38 | + |
| 39 | + if self.has_bought: |
| 40 | + # If already bought, SELL if cur_price lower than trailing stop-loss |
| 41 | + cur_price = price_data[ticker]['Close'].loc[current_date] |
| 42 | + if cur_price < (self.has_bought * (1-self.trail_pct)): |
| 43 | + # SELL |
| 44 | + signals[ticker] = -positions[ticker].shares |
| 45 | + self.has_bought = None |
| 46 | + elif cur_price > self.has_bought: |
| 47 | + self.has_bought = cur_price |
| 48 | + |
| 49 | + else: |
| 50 | + pct_change = price_data[ticker]['Close'].pct_change().dropna() |
| 51 | + avg_pct_change = pct_change.mean() |
| 52 | + cur_pct_change = pct_change[-int(self.lookback_period/2):].mean() |
| 53 | + if cur_pct_change > 0 and cur_pct_change > avg_pct_change: |
| 54 | + cur_price = price_data[ticker]['Close'].loc[current_date] |
| 55 | + signals[ticker] = int(cash / cur_price) |
| 56 | + self.has_bought = cur_price |
| 57 | + |
| 58 | + return signals |
0 commit comments