Welcome to 100 Days of Hell with Python Algo Trading – Day 10!
Today we are 10% of the way into this century, which means that we have understood many important Python Algorithmic Trading concepts. In the previous session, we learned:
What is a Constructor Function
The importance of the self keyword
The Golden Rule of OOP: “Only objects can access the methods and attributes of a class”
Today we will understand these concepts a little more deeply and then unlock the power of Python’s Magic Methods (also known as Dunder Methods) – which are especially useful for Quantitative Traders.
Previous Session – Quick Review

Whenever we create an object of a class, the Constructor Function (__init__) is automatically run.
The self keyword acts as a link between the methods and variables of the class.
And yes, remember the Golden Rule: “Only objects can access the methods and properties of a class.”
For example:
class TradingStrategy:
def __init__(self, symbol, amount):
self.symbol = symbol
self.amount = amount
When we create the object:
momentum = TradingStrategy(“ETH”, 3000)
Here the momentum object is automatically passed as self.
Is self necessary?
A question that often comes up is: can we write something else instead of self?
Yes! self is just a name. You can write it as symbol, strategy, or anything else if you want, but according to the convention, it is better to keep it as self in Python.
What are Magic Methods (Dunder Methods)?
There are some methods in Python that start and end with double underscores – such as __init__, __str__, __repr__, etc. These are called Magic Methods.
The power of Magic Methods:
- They do not require an explicit call to run.
- You can define the behavior of your custom objects.
- For example, if you want to add two trade objects (Addition), you can define the __add__ magic method.
Example of Magic Method – with Trade Objects
Class Trade:
def __init__(self, symbol, quantity, price):
self.symbol = symbol
self.quantity = quantity
self.price = price
def __repr__(self):
return f”Trade({self.symbol}, {self.quantity}, {self.price})”
def __add__(self, other):
if self.symbol == other.symbol:
total_qty = self.quantity + other.quantity
avg_price = (self.price + other.price) / 2
return Trade(self.symbol, total_qty, avg_price)
otherwise:
return “Symbols don’t match!”
How to use:
t1 = Trade(“BTC”, 1, 70000)
t2 = Trade(“BTC”, 2, 71000)
t3 = t1 + t2
print(t3)
# Output: Trade(BTC, 3, 70500.0)
The list of Magic Methods includes:
__init__ – Constructor
__str__ – readable string form of the object
__repr__ – dev-friendly representation of the object
__add__, __sub__, __mul__ – mathematical operator overloading
__len__, __getitem__, __setitem__ – Collection-like behaviour
Watch this Day 10 video tutorial
Day 10 : Object-Oriented Programming Part – 2