OOP in Python for traders means organising trading code into classes and objects: a Stock, a Portfolio, a Strategy, each holding its own data (attributes) and actions (methods). The four core ideas, inheritance, encapsulation, polymorphism and abstraction, let you reuse code, protect your data and swap strategies without rewriting your trading system.
Key Takeaways
- A class is a blueprint; an object is one instance, such as a single stock or position.
- Inheritance reuses code, encapsulation protects data, polymorphism lets different strategies share one interface, and abstraction hides complexity.
- Python dataclasses cut boilerplate for simple data holders such as orders and positions.
- Most backtesting and broker libraries (Backtrader, OpenAlgo, broker SDKs) are built around classes, so OOP makes them easier to use.
For traders and investors, having well-structured code can greatly improve the efficiency and manageability of trading applications. Object-Oriented Programming (OOP) in Python offers a systematic way to write code, making it simpler to manage and scale your trading systems. In this tutorial, we will explore key OOP concepts using stock market-related examples to demonstrate their practical applications.

Classes and Objects
Classes and objects are the foundation of OOP. A class is a blueprint for creating objects, which are instances of that class. Classes define the properties (attributes) and behaviors (methods) that the objects created from the class can have.
class Stock:
def __init__(self, symbol, price):
self.symbol = symbol
self.price = price
def display(self):
return f"Stock: {self.symbol}, Price: {self.price}"
# Creating objects
stock1 = Stock('AAPL', 150.00)
stock2 = Stock('GOOGL', 2800.00)
print(stock1.display())
print(stock2.display())
In this example, the Stock class has attributes for the stock symbol and price. The __init__ method is a special method called a constructor, which initializes these attributes when an object is created. The self parameter is a reference to the current instance of the class and is used to access variables and methods associated with that instance. The display method provides a simple way to print the stock information.
Attributes and Methods
- Attributes: These are variables that hold data about the object. For example, in the
Stockclass,symbolandpriceare attributes. They store the specific details of each stock instance.
class Stock:
def __init__(self, symbol, price):
self.symbol = symbol
self.price = price
Here, symbol and price are attributes of the Stock class. Each Stock object will have its own values for these attributes.
Methods: These are functions defined within a class that describe the behaviors of the objects. For example, the display method in the Stock class is used to show the stock’s information.
class Stock:
def __init__(self, symbol, price):
self.symbol = symbol
self.price = price
def display(self):
return f"Stock: {self.symbol}, Price: {self.price}"
- The
displaymethod is a behavior that allStockobjects can perform. It uses the object’s attributes to return a formatted string.
Inheritance
Inheritance allows us to create new classes that reuse, extend, or modify the behavior of existing classes. For example, let’s create a Watchlist class that inherits from the Stock class.
class Watchlist(Stock):
def __init__(self, symbol, price, watchlist_name):
super().__init__(symbol, price)
self.watchlist_name = watchlist_name
def display(self):
return f"Watchlist: {self.watchlist_name}, Stock: {self.symbol}, Price: {self.price}"
# Creating an object of Watchlist
watchlist_item = Watchlist('TSLA', 700.00, 'Tech Stocks')
print(watchlist_item.display())
The Watchlist class inherits from Stock and adds an additional attribute watchlist_name. The super().__init__(symbol, price) call invokes the constructor of the parent class (Stock), ensuring that the symbol and price attributes are initialized correctly.
Encapsulation
Encapsulation involves bundling the data (attributes) and methods that operate on the data into a single unit and restricting access to some of the object’s components. This helps to prevent accidental modification of data.
class Portfolio:
def __init__(self):
self.__stocks = []
def add_stock(self, stock):
self.__stocks.append(stock)
def remove_stock(self, stock):
self.__stocks.remove(stock)
def display(self):
for stock in self.__stocks:
print(stock.display())
# Creating a Portfolio object
portfolio = Portfolio()
portfolio.add_stock(stock1)
portfolio.add_stock(stock2)
portfolio.display()
In the Portfolio class, the __stocks attribute is private, indicated by the double underscores. This prevents direct access from outside the class, promoting encapsulation. Methods are provided to add, remove, and display stocks.
Strictly speaking, Python does not enforce private attributes. The double underscore triggers name mangling (the attribute becomes _Portfolio__stocks), which discourages accidental access rather than making it impossible. A single underscore, such as _stocks, is the usual convention for “internal, please don’t touch”.
Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables a function to use objects of various types through a single interface.
class TradingStrategy:
def execute(self, stock):
pass
class BuyStrategy(TradingStrategy):
def execute(self, stock):
return f"Buying {stock.symbol} at {stock.price}"
class SellStrategy(TradingStrategy):
def execute(self, stock):
return f"Selling {stock.symbol} at {stock.price}"
# Using polymorphism
strategy = BuyStrategy()
print(strategy.execute(stock1))
strategy = SellStrategy()
print(strategy.execute(stock2))
The TradingStrategy class defines an interface for executing a strategy. The BuyStrategy and SellStrategy classes inherit from TradingStrategy and implement the execute method. Polymorphism allows us to call the execute method on different strategy objects.
Abstraction
Abstraction simplifies complex systems by modeling classes appropriate to the problem domain and working at a high level of simplicity.
from abc import ABC, abstractmethod
class AbstractStock(ABC):
@abstractmethod
def display(self):
pass
class ConcreteStock(AbstractStock):
def __init__(self, symbol, price):
self.symbol = symbol
self.price = price
def display(self):
return f"Stock: {self.symbol}, Price: {self.price}"
# Creating an object of ConcreteStock
concrete_stock = ConcreteStock('AMZN', 3500.00)
print(concrete_stock.display())
In this example, AbstractStock is an abstract base class with an abstract method display. The ConcreteStock class inherits from AbstractStock and implements the display method. This abstraction hides the complex details and provides a simple interface for working with stock objects.
Dataclasses: Less Boilerplate for Trading Objects
Since Python 3.7, the dataclasses module generates __init__, __repr__ and comparison methods for you. It is ideal for simple objects such as orders, trades and positions:
from dataclasses import dataclass
@dataclass
class Position:
symbol: str
quantity: int
entry_price: float
def pnl(self, ltp: float) -> float:
"""Mark-to-market profit or loss at the last traded price."""
return (ltp - self.entry_price) * self.quantity
pos = Position("RELIANCE", 50, 1420.50)
print(pos)
print(pos.pnl(1450.00))
Output:
Position(symbol='RELIANCE', quantity=50, entry_price=1420.5)
1475.0
Putting It Together: A Strategy Class Example
Here is a small moving average crossover strategy written as a class. The object keeps its own price history, settings and position, so you can run several instances with different parameters side by side:
class SMACrossover:
"""A simple strategy object: keeps its own state and settings."""
def __init__(self, fast=10, slow=20):
if fast >= slow:
raise ValueError("fast period must be smaller than slow period")
self.fast = fast
self.slow = slow
self.prices = []
self.position = 0 # 1 = long, 0 = flat
def _sma(self, period):
return sum(self.prices[-period:]) / period
def on_price(self, price):
"""Feed one closing price; returns 'BUY', 'SELL' or None."""
self.prices.append(price)
if len(self.prices) < self.slow:
return None
fast_ma, slow_ma = self._sma(self.fast), self._sma(self.slow)
if fast_ma > slow_ma and self.position == 0:
self.position = 1
return "BUY"
if fast_ma < slow_ma and self.position == 1:
self.position = 0
return "SELL"
return None
strategy = SMACrossover(fast=3, slow=5)
closes = [100, 101, 102, 101, 103, 105, 107, 106, 104, 101, 99, 98]
for close in closes:
signal = strategy.on_price(close)
if signal:
print(close, signal)
Output:
103 BUY
101 SELL
This is the same pattern used by event-driven frameworks. See Introduction to Backtrader for a full backtesting framework built this way, and fetching broker historical data using OpenAlgo for broker data handled through Python objects.
Why Traders and Investors Should Learn OOP
Object-Oriented Programming (OOP) provides several benefits that are particularly valuable in the context of designing trading and investing applications:
- Modularity: By breaking down complex systems into smaller, manageable classes, traders can create more organized and modular code. This makes it easier to understand, maintain, and debug applications.
- Reusability: OOP promotes the reuse of code through inheritance and polymorphism. Traders can create a base class for common functionality and extend it for specific use cases, reducing redundancy.
- Scalability: OOP makes it easier to scale trading systems. As trading strategies and data analysis requirements evolve, new features can be added with minimal impact on existing code.
- Encapsulation: Encapsulation helps protect the data and functionality within objects, ensuring that they cannot be altered in unexpected ways. This is crucial for maintaining the integrity of trading algorithms and data.
- Abstraction: Abstraction allows traders to hide complex implementation details and expose only the necessary interfaces. This simplifies interaction with different components of the trading system.
- Efficiency: By using OOP principles, traders can develop efficient and robust applications that can handle large volumes of data and perform complex computations quickly.
By leveraging OOP principles, traders and investors can build robust, scalable, and maintainable trading applications that can adapt to changing market conditions and evolving strategies.
Common OOP Mistakes in Trading Code
- One giant class: a single class that fetches data, computes indicators, places orders and logs results is hard to test. Split responsibilities.
- Mutable default arguments:
def __init__(self, prices=[])shares one list across every object. UseNoneand create the list inside. - Deep inheritance chains: prefer composition (a
Portfoliothat holdsPositionobjects) over many layers of subclasses. - Hiding state changes: make methods that place orders or change positions clearly named, so a backtest and a live run behave the same way.
Using Object-Oriented Programming in Python offers numerous benefits for traders and investors. It provides a clear and manageable structure for your code, enhances reusability through inheritance, ensures data protection with encapsulation, allows flexibility with polymorphism, and simplifies complex systems through abstraction. By applying OOP principles, you can build robust and scalable trading applications that are easier to maintain and extend. The official Python classes tutorial is a good next read, and if you are starting out, try our free Python course for trading and investing.
Frequently Asked Questions
What are the four pillars of OOP in Python?
Inheritance, encapsulation, polymorphism and abstraction. Classes and objects are the building blocks that these four ideas are applied to.
Do I need OOP for algo trading in Python?
Not for simple scripts, but most backtesting frameworks and broker SDKs are built around classes. Knowing OOP makes it much easier to write strategies for them and to keep larger systems maintainable.
What is self in a Python class?
self is the reference to the current object. It lets a method read and change that object’s own attributes, such as self.price.
When should I use a dataclass instead of a normal class?
Use a dataclass when the class mainly stores data, such as an order, trade or position. Use a regular class when the object has significant behaviour or needs custom initialisation logic.
Learn by watching: free videos every week
Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

