Compute Time Series#
The compute_time_series()
function calculates the growth of a given pandas DataFrame of returns, creating a time series. This can be useful for investors and analysts to understand the growth of their investments over time, as well as for comparing the performance of different financial instruments.
To use the compute_time_series()
function, you need to provide a pandas DataFrame containing return data. Optionally, you can also provide a start_value, which is the initial value of the time series (default is 100).
After passing the DataFrame to the compute_time_series()
function, it will return a pandas DataFrame containing the growth time series for each column in the input DataFrame. This allows users to visualize and analyze the performance of different financial instruments over time.
Function
def compute_time_series(dataframe: pd.DataFrame, start_value: float = 100) -> pd.DataFrame:
"""
Compute the growth time series given a DataFrame of returns.
Parameters
----------
dataframe : pandas.DataFrame
DataFrame containing return data.
start_value : float, optional
Initial value of the time series. Default is 100.
Returns
-------
pandas.DataFrame
A pandas DataFrame containing the growth time series for each column in the input DataFrame.
"""
# Validate input
if not isinstance(dataframe, pd.DataFrame):
raise TypeError("Input 'dataframe' must be a pandas DataFrame.")
# Calculate growth time series
return (np.exp(np.log1p(dataframe).cumsum())) * start_value
Example#
import pandas as pd
import numpy as np
import yfinance as yf
import ds4finance as dsf
# Download historical data for SPY
spy = yf.download("SPY", start="2015-01-01", end="2020-12-31", progress=False)
# Calculate daily returns
returns = spy["Adj Close"].pct_change().dropna()
# Calculate growth time series
growth_time_series = dsf.compute_time_series(pd.DataFrame(returns))
# Rename column
growth_time_series.columns = ['SPY Growth']
# Display growth time series
growth_time_series.head()
SPY Growth | |
---|---|
Date | |
2015-01-05 | 98.194050 |
2015-01-06 | 97.269169 |
2015-01-07 | 98.481258 |
2015-01-08 | 100.228793 |
2015-01-09 | 99.425636 |
Notes:
The function calculates the growth time series based on the input DataFrame of returns.
Make sure the input is a pandas DataFrame containing return data.
The start_value parameter can be customized to set the initial value of the time series.