Week 4: Functions in Python
Learn how to create reusable functions for financial calculations and analysis. Functions are essential for organizing code and building complex financial models.
Learning Objectives:
- ✓ Understand the concept of functions in programming
- ✓ Learn how to define and call functions in Python
- ✓ Understand function parameters and return values
- ✓ Create reusable financial calculation functions
2. Function Parameters and Arguments
Understanding how to pass data to functions and handle different types of parameters.
def calculate_roi(initial_investment, final_value):
return (final_value - initial_investment) / initial_investment * 100
Read more about Function Parameters
3. Return Values
Learn how functions can return calculated values for use in your program.
def calculate_monthly_payment(principal, rate, years):
r = rate / 12 / 100 # Monthly rate
n = years * 12 # Total months
return principal * (r * (1 + r)**n) / ((1 + r)**n - 1)
Exercises:
- Create a function library for financial calculations:
- Present Value (PV)
- Future Value (FV)
- Net Present Value (NPV)
- Internal Rate of Return (IRR)
- Write a function that calculates stock metrics:
- Daily returns
- Volatility
- Sharpe ratio
- Create a bond pricing function that:
- Takes face value, coupon rate, years to maturity, and market rate
- Returns the current bond price
- Write a portfolio analysis function that:
- Takes a list of stock prices and weights
- Calculates portfolio return and risk
- Returns a summary dictionary
- Create a loan amortization function that generates a payment schedule
- Write a function to calculate various risk metrics (Beta, Standard Deviation, etc.)
💡 ChatGPT Learning Tips
Use these prompts to enhance your learning:
- "Show me how to write a function that calculates the Present Value (PV) with detailed explanation"
- "What are the best practices for organizing financial functions in Python?"
- "Help me understand how to handle errors in financial calculation functions"
- "Explain how to write a function that calculates portfolio statistics with multiple return values"