S
Suleyman Sade
Guest
From Cash to Stocks: Watch Your Portfolio in Action
This is part 5 of my โBuilding Stocksimpyโ series, where Iโm building a lightweight Python stock backtesting library from zero.
In the last post, I explained why I want Stocksimpy to stay simple: each class should have a clear purpose, instead of dumping everything in one giant backtester class.
This was why I had created
StockData
earlier to manage the stock price history. But only knowing the prices of stocks doesnโt get you farโโโI needed a way to track available cash, trades, and holdings. Thatโs where the Portfolio
comes in.Why a Portfolio Class?
Indicators are useless without an account keeping track of your tradesโโโso I built the
Portfolio
.Portfolio
is essentially the accountant, keeping track of all the money flow. Sure, you could track this with a data frame inside the backtesting loop. So why use Portfolio
? There is a principle in software development called:Donโt Repeat Yourself (DRY)
Coding consists of objects, functions, classes, and many more. Why repeat yourself again and again when you could just call the same function? This is the main reason why I wanted a centralized
Portfolio
class.And not only that, having a
Portfolio
class allowed me to separate cash flow and actually run the backtesting logic, so instead of trying to push everything together, I could separate different tasks in the code. Otherwise, I would be rewriting buy/sell logic over and over again, and imagine having to change a minor error in that codeโโโI am leaving the rest to your imagination.Three Core Responsibilities
What comes to your mind when I say Portfolioโโโin trading: total money, stocks, and other equities. That is exactly what
Portfolio
does, additionally, anything that is related to the flow and recording of that money/holdings. Storing cash and holdings
At its core, Portfolio keeps track of your available cash (
self.cash
) and all your holdings (self.holdings
). This may sound simple, but having a single place for this information prevents mistakes and makes the code cleaner.Buy and sell operations
I didnโt want the backtester loop to have direct access to the cash and holdings. So I decided the second responsibility should be buy/sell operations. Now buying/selling would require
Portfolio
knowing the current price of the stock, meaning it needs StockData
which was something I was against doing, as Portfolio
had to be used standalone. Solution? I just added
price
parameter to exec_trade()
so that this value could be provided by the backtesting loop or the user directly. And the direct access and alteration are done by exec_trade()
.Tracking history
Porfolio
may seem complete by now, but there is a 3rd critical responsibility: tracking history. User needs to be able to access the portfolio changes when the simulation buys/sells stock, and the total valuation. This was fairly easy to implement by _log_trade()
recording every trade in self.trade_log
.Here is an example run of how it works:
Code:
from portfolio import Portfolio
# Start out with $10,000
myportfolio = Portfolio(initial_cap = 10_000)
# Buy 10 NVDA stocks at $170 per stock
myportfolio.exec_trade(
symbol='NVDA',
trade_type='Buy',
price=170,
shares=10,
date=current_date
)
An interesting bug I encountered: Python wonโt let you increment a value for a key that doesnโt exist yet in a dictionary. The solution? Use
defaultdict(int)
from Pythonโs collections
module. This automatically initializes new keys to 0, solving the problem neatly.Future?
Portfolio
is designed to act independently, so it can be used in custom backtesting loops. It already handles multiple stocks without issue, although the first version of Backtester wonโt fully leverage them yet. Next up: Backtesting logic.
What else?
If there are any suggestions or improvements you want for
Stocksimpy.
Please let me know through either my socials or by directly commenting on them. I want this library to be useful to others, and anyone who is just starting out with quant finance.Thanks for readingโโโhope you enjoyed. Before you leave, please:
Star stocksimpy on Github
Follow me on Twitter / X
Iโm now on Bluesky
Or read more of my posts on Medium
Letโs connect on LinkedIn
Continue reading...