I've seen similar questions posted here and here, but they don't really answer the problem that I'm having, maybe someone can explain this error to me.
I'm using this backtesting package to create a stock backtesting environment, but I'm making some modifications in my implementation of it. I've created a minimal reproducible example of my main code below:
# pip install backtesting
from backtesting import Strategy
class StrategyParentClass:
def __init__(self, whatever=True):
self.whatever=whatever
class StrategyChildClass(StrategyParentClass, Strategy):
def __init__(self):
super().__init__()
self.title="StrategyTitle"
def next(self):
print("YAY")
child_class_object = StrategyChildClass()
The code right now gives the error:
Traceback (most recent call last):
File "test2.py", line 16, in <module>
child_class_object = StrategyChildClass()
TypeError: Can't instantiate abstract class StrategyChildClass with abstract methods init, next
To explain, I have a parent strategy class, and a child strategy class. The child strategy class inherits the attributes from the parent class, as well as the Strategy
class from the backtesting package. When you look at the example code they provide, your strategy class should look like this. So your child class should have a next
method in it, which mine does.
However, I'm trying to make my child class inherit from 2 parent classes, which I think is what's giving me the grief. When you delete the , Strategy
in the StrategyChildClass(StrategyParentClass, Strategy):
line, it'll run without giving an error.
So in this case, how can I instantiate a parent class of my own, and have the child class inherit from IT, AND the imported Strategy
class parent, without giving this error? The backtesting package uses this child class' attributes and next
method when running the trades.
I cannot speak to your implementation here, but generally speaking, you must implement abstract methods of any base class in a subclass that calls it. (the two abstract methods in 'Strategy' are 'init' and 'next' and you only had the 'next' method in your subclass. This code should solve it, though may not behave how you intend)
# pip install backtesting
from backtesting import Strategy
class StrategyParentClass:
def __init__(self, whatever=True):
self.whatever=whatever
class StrategyChildClass(StrategyParentClass, Strategy):
def __init__(self):
super().__init__()
self.title="StrategyTitle"
def next(self):
print("YAY")
def init(self):
pass
child_class_object = StrategyChildClass()
A good resource that covers this: https://python-course.eu/oop/the-abc-of-abstract-base-classes.php#:~:text=An%20abstract%20method%20is%20a,implementations%20for%20the%20abstract%20methods.