0
# Return Calculations
1
2
Convert between prices and returns using various methods, including simple returns, log returns, and price indexing with rebasing capabilities. Essential functions for time series transformations in financial analysis.
3
4
## Capabilities
5
6
### Price to Returns Conversion
7
8
Transform price series into return series using different calculation methods.
9
10
```python { .api }
11
def to_returns(prices):
12
"""
13
Calculate simple arithmetic returns from price series.
14
15
Parameters:
16
- prices (pd.Series or pd.DataFrame): Price series
17
18
Returns:
19
pd.Series or pd.DataFrame: Simple returns (percent change)
20
"""
21
22
def to_log_returns(prices):
23
"""
24
Calculate logarithmic returns from price series.
25
26
Parameters:
27
- prices (pd.Series or pd.DataFrame): Price series
28
29
Returns:
30
pd.Series or pd.DataFrame: Log returns
31
"""
32
```
33
34
### Returns to Price Index Conversion
35
36
Convert return series back to price index form for analysis and visualization.
37
38
```python { .api }
39
def to_price_index(returns, start=100):
40
"""
41
Convert returns to cumulative price index.
42
43
Parameters:
44
- returns (pd.Series or pd.DataFrame): Return series
45
- start (float): Starting value for price index (default: 100)
46
47
Returns:
48
pd.Series or pd.DataFrame: Cumulative price index
49
"""
50
```
51
52
### Price Rebasing
53
54
Standardize price series to common starting values for comparison.
55
56
```python { .api }
57
def rebase(prices, value=100):
58
"""
59
Rebase all price series to given initial value.
60
61
Parameters:
62
- prices (pd.Series or pd.DataFrame): Price series
63
- value (float): New starting value (default: 100)
64
65
Returns:
66
pd.Series or pd.DataFrame: Rebased prices
67
"""
68
```
69
70
### Performance Metrics from Returns
71
72
Calculate key performance metrics directly from return series.
73
74
```python { .api }
75
def calc_cagr(prices):
76
"""
77
Calculate compound annual growth rate.
78
79
Parameters:
80
- prices (pd.Series): Price series
81
82
Returns:
83
float: CAGR as decimal (e.g., 0.12 for 12%)
84
"""
85
86
def calc_total_return(prices):
87
"""
88
Calculate total return over the entire period.
89
90
Parameters:
91
- prices (pd.Series): Price series
92
93
Returns:
94
float: Total return as decimal
95
"""
96
```
97
98
## Usage Examples
99
100
### Basic Return Calculations
101
102
```python
103
import ffn
104
105
# Download price data
106
prices = ffn.get('AAPL', start='2020-01-01')['AAPL']
107
108
# Calculate simple returns
109
returns = ffn.to_returns(prices)
110
print(f"First 5 returns:\n{returns.head()}")
111
112
# Calculate log returns
113
log_returns = ffn.to_log_returns(prices)
114
print(f"Mean log return: {log_returns.mean():.4f}")
115
116
# Calculate CAGR
117
cagr = ffn.calc_cagr(prices)
118
print(f"CAGR: {cagr:.2%}")
119
```
120
121
### Price Index Construction
122
123
```python
124
import ffn
125
126
# Start with returns data
127
prices = ffn.get('AAPL,MSFT', start='2020-01-01')
128
returns = ffn.to_returns(prices).dropna()
129
130
# Convert back to price index starting at 100
131
price_index = ffn.to_price_index(returns, start=100)
132
print(f"Final values:\n{price_index.iloc[-1]}")
133
134
# Rebase original prices to 100
135
rebased_prices = ffn.rebase(prices, value=100)
136
print(f"All series start at: {rebased_prices.iloc[0]}")
137
```
138
139
### Method Chaining with Pandas Extensions
140
141
```python
142
import ffn
143
144
# FFN extends pandas automatically
145
prices = ffn.get('AAPL', start='2020-01-01')['AAPL']
146
147
# Method chaining for functional composition
148
result = (prices
149
.to_returns() # Convert to returns
150
.dropna() # Remove NaN values
151
.to_price_index(100) # Convert back to price index
152
.calc_cagr() # Calculate CAGR
153
)
154
155
print(f"CAGR via chaining: {result:.2%}")
156
157
# Multi-step transformation
158
analysis_ready = (prices
159
.rebase(100) # Rebase to 100
160
.to_returns() # Convert to returns
161
.dropna() # Clean data
162
)
163
164
print(f"Returns summary:\n{analysis_ready.describe()}")
165
```
166
167
### Portfolio Return Calculations
168
169
```python
170
import ffn
171
import pandas as pd
172
173
# Download multiple assets
174
prices = ffn.get('AAPL,MSFT,GOOGL', start='2020-01-01')
175
returns = ffn.to_returns(prices).dropna()
176
177
# Equal weight portfolio returns
178
equal_weights = pd.Series([1/3, 1/3, 1/3], index=returns.columns)
179
portfolio_returns = (returns * equal_weights).sum(axis=1)
180
181
# Convert portfolio returns to price index
182
portfolio_index = ffn.to_price_index(portfolio_returns, start=1000)
183
portfolio_cagr = ffn.calc_cagr(portfolio_index)
184
185
print(f"Portfolio CAGR: {portfolio_cagr:.2%}")
186
print(f"Final portfolio value: ${portfolio_index.iloc[-1]:.2f}")
187
```