junfan02
junfan02

Reputation: 161

What is the point of passing in params to an abstract base class in this manner?

I was trying to understand how the backtesting.py module is written and came across this code.

class Strategy(metaclass=ABCMeta):
    """
    A trading strategy base class. Extend this class and
    override methods
    `backtesting.backtesting.Strategy.init` and
    `backtesting.backtesting.Strategy.next` to define
    your own strategy.
    """
    def __init__(self, broker, data, params):
        self._indicators = []
        self._broker: _Broker = broker
        self._data: _Data = data
        self._params = self._check_params(params)



    def __repr__(self):
        return '<Strategy ' + str(self) + '>'

    def __str__(self):
        params = ','.join(f'{i[0]}={i[1]}' for i in zip(self._params.keys(),
                                                        map(_as_str, self._params.values())))
        if params:
            params = '(' + params + ')'
        return f'{self.__class__.__name__}{params}'

    def _check_params(self, params):
        for k, v in params.items():
            if not hasattr(self, k):
                raise AttributeError(
                    f"Strategy '{self.__class__.__name__}' is missing parameter '{k}'."
                    "Strategy class should define parameters as class variables before they "
                    "can be optimized or run with.")
            setattr(self, k, v)
        return params

From what I have understood it seems that the to instantiate an object of the strategy class we need three arguments broker, data, params It seems that valid form of the params is supposed to be a dictionary with keys already being present as attributes. So does that mean params = {broker : "blah", data: "blahblah"} is the form that needs to be passed? WHat is the point of doing this in such a manner instead of directly passing the values to data and broker?

I tried to instantiate an object of the Strategy class using arbitrary dictionaries, just to understand what's going on.

This code q = Strategy("nn", [],{"b":33, "a":44}) gives the following error:

Strategy 'Strategy' is missing parameter 'b'.Strategy class should define parameters as class variables before they can be optimized or run with.

However if I do this:

q = Strategy("nn", [],{"_broker":33, "_data":44})

The code runs without errors.

Whatpurpose does this serve?

Upvotes: 0

Views: 131

Answers (0)

Related Questions