Code Quality & Collaboration: Building Finance Tools That Last
As a finance professional learning Python, you’ll soon want to move beyond writing scripts just for yourself. Whether you’re building financial models, automating reporting, or creating data analysis tools, there comes a point when your code needs to be shared with colleagues or even the wider finance community. This post will guide you through best practices for creating high-quality, shareable code.
Version Control: Git & GitHub for Financial Projects
Why Version Control Matters in Finance
Imagine you’ve built a Python script that calculates key financial ratios from quarterly reports. After sharing it with your team, you make changes that accidentally break the debt-to-equity calculation. Without version control, finding and fixing this error could be a nightmare. With Git, you can simply revert to the previous working version.
In finance, where accuracy is paramount and regulatory compliance often requires audit trails, version control is essential.
Getting Started with Git
First, download and install Git for your operating system.
Once installed, open a command prompt or terminal and set up your identity:
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
Creating Your First Finance Repository
Let’s walk through creating a repository for a simple financial calculator:
- Create a new directory for your project:
mkdir financial-ratio-calculator
cd financial-ratio-calculator
- Initialis a Git repository:
git init
You’ll see a message that an empty Git repository has been initialised.
- Create a simple Python file called
ratio_calculator.py
:
def calculate_current_ratio(current_assets, current_liabilities):
"""
Calculate the current ratio.
Args:
current_assets (float): Total current assets
current_liabilities (float): Total current liabilities
Returns:
float: Current ratio (current assets / current liabilities)
"""
if current_liabilities == 0:
raise ValueError("Current liabilities cannot be zero (division by zero)")
return current_assets / current_liabilities
def calculate_debt_to_equity(total_debt, shareholders_equity):
"""
Calculate the debt-to-equity ratio.
Args:
total_debt (float): Total debt
shareholders_equity (float): Total shareholders' equity
Returns:
float: Debt-to-equity ratio (total debt / shareholders' equity)
"""
if shareholders_equity == 0:
raise ValueError("Shareholders' equity cannot be zero (division by zero)")
return total_debt / shareholders_equity
# Add more financial ratios as needed
- Track the file with Git:
git add ratio_calculator.py
- Commit the changes:
git commit -m "Add basic financial ratio calculator functions"
Core Git Commands for Daily Use
git status
: Check which files have been modifiedgit diff
: See exactly what changed in your filesgit add <filename>
: Stage a file for commitgit commit -m "Your message"
: Commit staged changesgit log
: View commit history
Branching for New Features
Branching lets you work on new features without affecting your main code. This is perfect for when you’re adding new financial calculations to your toolkit.
# Create a branch for a new profitability ratio feature
git branch profitability-ratios
# Switch to that branch
git checkout profitability-ratios
Or do both at once:
git checkout -b profitability-ratios
Now add some code to your ratio_calculator.py file:
def calculate_roe(net_income, average_shareholders_equity):
"""
Calculate Return on Equity (ROE).
Args:
net_income (float): Net income for the period
average_shareholders_equity (float): Average shareholders' equity
Returns:
float: ROE ratio (net income / average shareholders' equity)
"""
if average_shareholders_equity == 0:
raise ValueError("Average shareholders' equity cannot be zero")
return net_income / average_shareholders_equity
Commit this new function:
git add ratio_calculator.py
git commit -m "Add ROE calculation function"
When you’re ready to merge this back into your main code:
git checkout main
git merge profitability-ratios
Collaborating with GitHub
GitHub extends Git’s functionality by hosting your repositories online, making collaboration easier.
- Create a GitHub account if you don’t have one
- Create a new repository on GitHub
- Connect your local repository to GitHub:
git remote add origin https://github.com/yourusername/financial-ratio-calculator.git
git push -u origin main
Now your code is on GitHub! You can share the link with colleagues, collaborate on improvements, and track issues.
Pull Requests: The Professional Way to Collaborate
When working with a team of financial analysts, direct changes to the main codebase can be risky. Pull requests (PRs) provide a mechanism for review and discussion before code is merged:
- Make your changes in a separate branch
- Push that branch to GitHub
- Open a PR to merge your branch into main
- Have teammates review your code
- Merge the PR once approved
This workflow is perfect for finance teams where code accuracy is critical; catching calculation errors before they make it into production reports!
Writing Clean, PEP 8 Compliant Code
What is PEP 8?
PEP 8 is Python’s style guide—a set of conventions for writing readable code. In finance, where you might be sharing models with auditors or other stakeholders, clean code is particularly important.
Key PEP 8 Rules for Finance Code
- Use 4 spaces for indentation (not tabs)
- Keep lines under 79 characters for better readability in documentation
- Use descriptive variable names that reflect financial concepts:
# Bad
def calc(a, b):
return a / b
# Good
def calculate_price_to_earnings_ratio(stock_price, earnings_per_share):
return stock_price / earnings_per_share
- Use whitespace appropriately:
# Bad
profit=revenue-expenses
tax_amount=profit*tax_rate
# Good
profit = revenue - expenses
tax_amount = profit * tax_rate
Using Linters: flake8
Linters automatically check your code for style issues. Let’s set up flake8:
- Install flake8:
pip install flake8
- Run flake8 on your code:
flake8 ratio_calculator.py
It will show any style violations that need fixing.
- For a real finance project, create a configuration file (
.flake8
) in your project root:
[flake8]
max-line-length = 88
exclude = .git,__pycache__,build,dist
per-file-ignores =
__init__.py: F401
Auto-formatting with black
Why spend time manually formatting code when tools can do it for you?
- Install black:
pip install black
- Format your code:
black ratio_calculator.py
Black will automatically reformat your code to follow a consistent style.
- For finance projects, you might want to create a
pyproject.toml
file to configure black:
[tool.black]
line-length = 88
target-version = ['py38']
include = '\.pyi?$'
exclude = '''
/(
\.git
| \.hg
| \.mypy_cache
| \.tox
| \.venv
| _build
| buck-out
| build
| dist
)/
'''
Organising Imports with isort
isort automatically organises your import statements by type and alphabetically.
- Install isort:
pip install isort
- Run isort on your file:
isort ratio_calculator.py
For finance projects where you might be importing various data analysis libraries, isort keeps your imports clean and consistent:
# Standard library imports
import datetime
import os
from decimal import Decimal
# Third-party imports
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
# Local application imports
from .financial_models import discounted_cash_flow
from .ratio_analysis import calculate_current_ratio
Writing Effective Documentation
Docstrings: Your Future Self Will Thank You
Documentation isn’t just for others, it’s useful for you six months from now when you can’t remember why you wrote that complex financial calculation a certain way.
Google Style Docstrings
def calculate_npv(cash_flows, discount_rate):
"""
Calculate Net Present Value of a series of cash flows.
Args:
cash_flows (list): List of cash flows, where the first element is the initial investment (negative)
discount_rate (float): Annual discount rate as a decimal (e.g., 0.1 for 10%)
Returns:
float: Net Present Value
Examples:
>>> calculate_npv([-1000, 200, 300, 400, 500], 0.1)
152.07
"""
npv = cash_flows[0] # Initial investment
for i, cf in enumerate(cash_flows[1:], 1):
npv += cf / (1 + discount_rate) ** i
return round(npv, 2)
NumPy Style Docstrings
def calculate_irr(cash_flows):
"""
Calculate Internal Rate of Return for a series of cash flows.
Parameters
----------
cash_flows : list or array-like
List of cash flows, where the first element is the initial investment (negative)
Returns
-------
float
The Internal Rate of Return as a decimal
Notes
-----
Uses Newton's method to find the rate that makes NPV = 0
Examples
--------
>>> calculate_irr([-1000, 300, 400, 500])
0.1548
"""
# IRR implementation...
Choose one style and be consistent across your project.
Generating Documentation with Sphinx
For larger finance projects, automatic documentation generation with Sphinx is invaluable:
- Install Sphinx:
pip install sphinx sphinx-rtd-theme
- Set up a docs directory:
mkdir docs
cd docs
sphinx-quickstart
- Configure
conf.py
to use a nice theme:
html_theme = 'sphinx_rtd_theme'
- Build your documentation:
sphinx-build -b html . _build
This creates HTML documentation you can share with your finance team.
Putting It All Together: A Finance Project Workflow
Let’s walk through a complete workflow for a hypothetical financial analysis tool:
Set up your environment:
- Create a virtual environment
- Install dependencies
- Set up Git
Create your project structure:
financial-analysis-toolkit/
├── .git/
├── .gitignore
├── .flake8
├── pyproject.toml
├── README.md
├── requirements.txt
├── setup.py
├── docs/
└── financial_toolkit/
├── __init__.py
├── ratio_analysis.py
├── valuation_models.py
├── risk_metrics.py
└── utilities.py
Write your code with documentation:
- Start with core functions
- Add comprehensive docstrings
- Make small, focused commits
Validate with linters and formatters:
- Run black to format code
- Run isort to organise imports
- Run flake8 to check for issues
Create tests (more on this in the next post)
Push to GitHub and collaborate:
- Share with colleagues
- Use pull requests for reviews
- Track issues and feature requests
Conclusion
As a finance professional using Python, the practices outlined in this post will help you create reliable, maintainable code that you can confidently share with colleagues or the wider finance community. Taking the time to learn these professional techniques now will save you countless hours in the future and elevate the quality of your financial analysis tools.
In the next post, we’ll look at testing and debugging your financial code, which are critical skills for ensuring your calculations are accurate and robust.
Further Resources
- Git Documentation
- GitHub Guides
- PEP 8 Style Guide
- Real Python’s Guide to Docstrings
- Sphinx Documentation
Questions for Practice:
- Try creating a Git repository for a simple financial calculator with at least three ratio calculations
- Format your code with black and check it with flake8
- Write Google-style docstrings for each function
- Push your repository to GitHub and create a README explaining what your calculator does