I have a pandas DF with a date index, price column, and dividend column. write me a function that computes the value of $x invested in the stock on a certain day, assuming dividend reinvestment is turned on
Assistant
Certainly! Here's a function that computes the value of an investment with dividend reinvestment over time.
python
import pandas as pd
def compute_investment_value(df, investment_amount, start_date):
"""
Computes the value of an investment over time with dividends reinvested.
Parameters:
- df: pandas DataFrame with a DateTime index and columns 'price' and 'dividend'.
- investment_amount: initial amount invested.
- start_date: date of the initial investment (must be in df's index).
Returns:
- Series representing the value of the investment over time.
"""
# Ensure required columns are present
required_columns = {'price', 'dividend'}
if not required_columns.issubset(df.columns):
raise ValueError(f"DataFrame must contain columns: {required_columns}")
# Ensure the start_date is in the DataFrame index
if start_date not in df.index:
raise ValueError(f"Start date {start_date} not found in DataFrame index.")
# Copy and filter the DataFrame from the start_date onwards
df = df.loc[df.index >= start_date].copy()
# Replace NaNs in 'dividend' with zeros
df['dividend'] = df['dividend'].fillna(0.0)
# Initialize shares and investment value columns
df['shares'] = 0.0
df['investment_value'] = 0.0
# Initial number of shares purchased on the start_date
initial_price = df.loc[start_date, 'price']
df.loc[start_date, 'shares'] = investment_amount / initial_price
df.loc[start_date, 'investment_value'] = investment_amount
# Iterate over subsequent dates to compute shares and investment value
for current_date in df.index[1:]:
previous_date = df.index[df.index.get_loc(current_date) - 1]
previous_shares = df.loc[previous_date, 'shares']
# Dividend received and reinvested
dividend_per_share = df.loc[current_date, 'dividend']
total_dividend = previous_shares * dividend_per_share
shares_purchased = total_dividend / df.loc[current_date, 'price']
# Update shares and investment value
df.loc[current_date, 'shares'] = previous_shares + shares_purchased
df.loc[current_date, 'investment_value'] = df.loc[current_date, 'shares'] * df.loc[current_date, 'price']
return df['investment_value']
# Example usage:
# Assuming 'df' is your DataFrame with 'price' and 'dividend' columns and a DateTime index
# investment_value_series = compute_investment_value(df, 1000, '2022-01-01')
This function:
Validates the Input: Checks if necessary columns are present and if the start date exists in the DataFrame.
Prepares the DataFrame: Filters it from the start date onwards and fills any missing dividends with zero.
Initializes the Investment: Calculates the initial number of shares based on the investment amount and starting price.
Iterates Over Dates: For each date, it calculates:
The dividend received based on the previous day's shares.
The number of shares purchased with the received dividends.
The total number of shares owned.
The current value of the investment.
Returns: A pandas Series representing the investment value over time.
Note: Replace '2022-01-01' in the example usage with your actual start date, and ensure that your DataFrame df is properly prepared with the correct date index and columns.