Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vectorized computation of cumulative_returns #127

Merged
merged 2 commits into from
Aug 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion finquant/returns.py
PietropaoloFrisoni marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ def cumulative_returns(data, dividend=0):
:Output:
:ret: a ``pandas.DataFrame`` of cumulative Returns of given stock prices.
"""
return data.dropna(axis=0, how="any").apply(lambda x: (x - x[0] + dividend) / x[0])
data = data.dropna(axis=0, how="any")
return ((data - data.iloc[0] + dividend) / data.iloc[0]).astype(np.float64)


def daily_returns(data):
Expand Down
2 changes: 2 additions & 0 deletions tests/test_returns.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ def test_cumulative_returns():
d = {"1": l1, "2": l2}
df = pd.DataFrame(d)
ret = cumulative_returns(df)
assert isinstance(ret, pd.DataFrame) and not ret.empty
assert all(abs(ret["1"].values - orig[0]) <= 1e-15)
assert all(abs(ret["2"].values - orig[1]) <= 1e-15)
# with dividend of 0.2
Expand All @@ -28,6 +29,7 @@ def test_cumulative_returns():
[0.005, -0.02, -0.045, -0.07, -0.095, -0.12, -0.145, -0.17, -0.195, -0.22],
]
ret = cumulative_returns(df, 0.2)
assert isinstance(ret, pd.DataFrame) and not ret.empty
assert all(abs(ret["1"].values - orig[0]) <= 1e-15)
assert all(abs(ret["2"].values - orig[1]) <= 1e-15)

Expand Down