Emmatassone / GEN-Bots

1 stars 0 forks source link

Reorganize code in backtesting project #4

Closed chao5monkey closed 9 months ago

chao5monkey commented 9 months ago

Project Structure

This PR is a suggestion on how code could be organized inside each individual sub-project. This MR organizes the trading strategies project as follows:

trading_strategies/
├─ ge/
│  ├─ data/
│  │  ├─ loader.py
│  ├─ trading/
│  │  ├─ indicators/
│  │  ├─ strategy/
├─ examples/
│  ├─ notebook_1.ipynb
│  ├─ notebook_2.ipynb
├─ runnable_script_1.py
├─ runnable_script_2.py

The root directory holds directories ge, examples, as well as runnable scripts. These items are meant as follows:

Strategy Classes

This PR proposes a new way of defining entry/exit point identification strategies. Strategies are defined in the package ge.trading.strategy and there is one file per strategy. The following are examples of two strategies that were adapted from the version before this PR:

import numpy as np

class Threshold:

    def __init__(self, buy: float, sell: float):
        self.__buy = buy
        self.__sell = sell

    def entries_and_exits(self, signal: np.ndarray):
        # Initialize entries.
        entries = np.zeros_like(signal, dtype=np.bool_)
        entries[signal < self.__buy] = True
        # Initialize exits.
        exits = np.zeros_like(signal, dtype=np.bool_)
        exits[signal > self.__sell] = True
        # Return both.
        return entries, exits
import numpy as np
import vectorbt as vbt

class DMAC:

    def __init__(self, fast_ma: int = 10, slow_ma: int = 20):
        self.__fast = fast_ma
        self.__slow = slow_ma

    def entries_and_exits(self, signal: np.ndarray):
        fast_ma = vbt.MA.run(signal, self.__fast, short_name='fast')
        slow_ma = vbt.MA.run(signal, self.__slow, short_name='slow')
        entries = fast_ma.ma_crossed_above(slow_ma)
        exits = fast_ma.ma_crossed_below(slow_ma)
        return entries.values, exits.values