Module 2 · Financial Arithmetic, Time Value, and Returns Lesson 18 of 120
Holding-Period and Cumulative Return
A two-period performance report with changing bases.
Transcript
22 sentences · select one to jump thereCheck your understanding
What gain is needed to recover from 96 to 100?
Code lab
Run it yourself
The lesson source in 7 languages. Edit it, run TypeScript and Python right here, and compare with the expected output.
/**
* Fintech Math Bootcamp · Lesson 018 of 120
* Holding-Period and Cumulative Return
* Module 02: Financial Arithmetic, Time Value, and Returns
*
* Scenario: A two-period performance report with changing bases
* Rule: cumulative = Π(1+Rₜ) − 1
*
* Try it: What gain is needed to recover from 96 to 100?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-arithmetic-time-value-and-returns/holding-period-return/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*/
export function lesson018() {
const returns = [0.20, -0.20];
let wealth = 100;
const path = [wealth];
for (const r of returns) {
if (!(1 + r > 0)) throw new Error("Growth factor must be positive");
wealth *= 1 + r; path.push(wealth);
}
const result = {path, cumulative: wealth / path[0] - 1};
return result;
}
export const checkedResult = {"path":[100,120,96],"cumulative":-0.040000000000000036};
// Run this file directly: npx tsx lessons/02-financial-arithmetic-time-value-and-returns/018-holding-period-and-cumulative-return.ts
if (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, "/").split("/").pop()!)) {
console.log(JSON.stringify(lesson018(), null, 2));
}
Your output
Press Run to execute the code in your browser.
Expected output
{
"path": [
100,
120,
96
],
"cumulative": -0.040000000000000036
}"""
Fintech Math Bootcamp · Lesson 018 of 120
Holding-Period and Cumulative Return
Module 02: Financial Arithmetic, Time Value, and Returns
Scenario: A two-period performance report with changing bases
Rule: cumulative = Π(1+Rₜ) − 1
Try it: What gain is needed to recover from 96 to 100?
Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-arithmetic-time-value-and-returns/holding-period-return/
Free course: https://courses.thefintechbuilder.com
Synthetic teaching example, not financial advice or a production library.
Run it: python main.py
"""
import json
def lesson018() -> dict:
returns = [0.20, -0.20]
wealth = 100
path = [wealth]
for r in returns:
if not 1 + r > 0:
raise ValueError("Growth factor must be positive")
wealth *= 1 + r
path.append(wealth)
result = {"path": path, "cumulative": wealth / path[0] - 1}
return result
if __name__ == "__main__":
print(json.dumps(lesson018(), indent=2))
Your output
Press Run to execute the code in your browser.
Expected output
{
"path": [
100,
120,
96
],
"cumulative": -0.040000000000000036
}/**
* Fintech Math Bootcamp · Lesson 018 of 120
* Holding-Period and Cumulative Return
* Module 02: Financial Arithmetic, Time Value, and Returns
*
* Scenario: A two-period performance report with changing bases
* Rule: cumulative = Π(1+Rₜ) − 1
*
* Try it: What gain is needed to recover from 96 to 100?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-arithmetic-time-value-and-returns/holding-period-return/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*
* Run it: javac Main.java && java Main
*/
import java.util.ArrayList;
import java.util.List;
public class Main {
static final class WealthPath {
final List<Double> path;
final double cumulative;
WealthPath(List<Double> path, double cumulative) {
this.path = path;
this.cumulative = cumulative;
}
}
static WealthPath lesson018() {
double[] returns = {0.20, -0.20};
double wealth = 100;
List<Double> path = new ArrayList<Double>();
path.add(wealth);
for (double r : returns) {
if (!(1 + r > 0)) throw new IllegalArgumentException("Growth factor must be positive");
wealth *= 1 + r;
path.add(wealth);
}
WealthPath result = new WealthPath(path, wealth / path.get(0) - 1);
return result;
}
public static void main(String[] args) {
WealthPath result = lesson018();
List<String> path = new ArrayList<String>();
for (double value : result.path) path.add(num(value));
System.out.println(object("path", array(path), "cumulative", num(result.cumulative)));
}
// Formats a double the way JSON.stringify does: whole numbers without ".0", null for NaN or infinity.
static String num(double x) {
if (Double.isNaN(x) || Double.isInfinite(x)) return "null";
if (x == Math.rint(x) && Math.abs(x) < 1e15) return String.valueOf((long) x);
return String.valueOf(x);
}
static String quote(String text) {
return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
}
// Indents an already formatted JSON value by one level.
static String nested(String json) {
return json.replace("\n", "\n ");
}
static String object(String... keysAndValues) {
if (keysAndValues.length == 0) return "{}";
StringBuilder out = new StringBuilder("{");
for (int i = 0; i < keysAndValues.length; i += 2) {
out.append(i == 0 ? "\n " : ",\n ")
.append(quote(keysAndValues[i])).append(": ").append(nested(keysAndValues[i + 1]));
}
return out.append("\n}").toString();
}
static String array(java.util.List<String> items) {
if (items.isEmpty()) return "[]";
StringBuilder out = new StringBuilder("[");
for (int i = 0; i < items.size(); i++) {
out.append(i == 0 ? "\n " : ",\n ").append(nested(items.get(i)));
}
return out.append("\n]").toString();
}
}
No browser runner for Java yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"path": [
100,
120,
96
],
"cumulative": -0.040000000000000036
}// Fintech Math Bootcamp · Lesson 018 of 120
// Holding-Period and Cumulative Return
// Module 02: Financial Arithmetic, Time Value, and Returns
//
// Scenario: A two-period performance report with changing bases
// Rule: cumulative = Π(1+Rₜ) − 1
//
// Try it: What gain is needed to recover from 96 to 100?
//
// Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-arithmetic-time-value-and-returns/holding-period-return/
// Free course: https://courses.thefintechbuilder.com
// Synthetic teaching example, not financial advice or a production library.
//
// Run it: go run main.go
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
)
type WealthPath struct {
Path []float64 `json:"path"`
Cumulative float64 `json:"cumulative"`
}
func lesson018() (WealthPath, error) {
returns := []float64{0.20, -0.20}
wealth := 100.0
path := []float64{wealth}
for _, r := range returns {
if !(1+r > 0) {
return WealthPath{}, errors.New("Growth factor must be positive")
}
wealth *= 1 + r
path = append(path, wealth)
}
result := WealthPath{Path: path, Cumulative: wealth/path[0] - 1}
return result, nil
}
func main() {
result, err := lesson018()
if err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
printJSON(result)
}
// printJSON prints a value as JSON indented with two spaces, like JSON.stringify(value, null, 2).
func printJSON(value any) {
out, err := json.MarshalIndent(value, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(out))
}
No browser runner for Go yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"path": [
100,
120,
96
],
"cumulative": -0.040000000000000036
}/**
* Fintech Math Bootcamp · Lesson 018 of 120
* Holding-Period and Cumulative Return
* Module 02: Financial Arithmetic, Time Value, and Returns
*
* Scenario: A two-period performance report with changing bases
* Rule: cumulative = Π(1+Rₜ) − 1
*
* Try it: What gain is needed to recover from 96 to 100?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-arithmetic-time-value-and-returns/holding-period-return/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*
* Run it: g++ -std=c++17 -o main main.cpp && ./main
*/
#include <charconv>
#include <cmath>
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
// Formats a double the way JSON.stringify does: shortest round-trip form, null for NaN or infinity.
std::string num(double x) {
if (!std::isfinite(x)) return "null";
char buffer[32];
auto [end, error] = std::to_chars(buffer, buffer + sizeof buffer, x);
(void)error;
return std::string(buffer, end);
}
std::string quote(const std::string& text) {
std::string out = "\"";
for (char c : text) {
if (c == '"' || c == '\\') out += '\\';
out += c;
}
return out + "\"";
}
// Indents an already formatted JSON value by one level.
std::string nested(const std::string& json) {
std::string out;
for (char c : json) {
out += c;
if (c == '\n') out += " ";
}
return out;
}
std::string object(const std::vector<std::pair<std::string, std::string>>& fields) {
if (fields.empty()) return "{}";
std::string out = "{";
for (std::size_t i = 0; i < fields.size(); ++i) {
out += i == 0 ? "\n " : ",\n ";
out += quote(fields[i].first) + ": " + nested(fields[i].second);
}
return out + "\n}";
}
std::string array(const std::vector<std::string>& items) {
if (items.empty()) return "[]";
std::string out = "[";
for (std::size_t i = 0; i < items.size(); ++i) {
out += i == 0 ? "\n " : ",\n ";
out += nested(items[i]);
}
return out + "\n]";
}
std::string numbers(const std::vector<double>& values) {
std::vector<std::string> items;
for (double value : values) items.push_back(num(value));
return array(items);
}
struct WealthPath {
std::vector<double> path;
double cumulative;
};
WealthPath lesson018() {
const std::vector<double> returns{0.20, -0.20};
double wealth = 100;
std::vector<double> path{wealth};
for (double r : returns) {
if (!(1 + r > 0)) throw std::invalid_argument("Growth factor must be positive");
wealth *= 1 + r;
path.push_back(wealth);
}
const WealthPath result{path, wealth / path[0] - 1};
return result;
}
int main() {
const WealthPath result = lesson018();
std::cout << object({{"path", numbers(result.path)}, {"cumulative", num(result.cumulative)}}) << "\n";
}
No browser runner for C++ yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"path": [
100,
120,
96
],
"cumulative": -0.040000000000000036
}//! Fintech Math Bootcamp · Lesson 018 of 120
//! Holding-Period and Cumulative Return
//! Module 02: Financial Arithmetic, Time Value, and Returns
//!
//! Scenario: A two-period performance report with changing bases
//! Rule: cumulative = Π(1+Rₜ) − 1
//!
//! Try it: What gain is needed to recover from 96 to 100?
//!
//! Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-arithmetic-time-value-and-returns/holding-period-return/
//! Free course: https://courses.thefintechbuilder.com
//! Synthetic teaching example, not financial advice or a production library.
//!
//! Run it: rustc main.rs && ./main
struct WealthPath {
path: Vec<f64>,
cumulative: f64,
}
fn lesson018() -> Result<WealthPath, String> {
let returns = [0.20, -0.20];
let mut wealth: f64 = 100.0;
let mut path = vec![wealth];
for &r in returns.iter() {
if !(1.0 + r > 0.0) {
return Err("Growth factor must be positive".to_string());
}
wealth *= 1.0 + r;
path.push(wealth);
}
let cumulative = wealth / path[0] - 1.0;
let result = WealthPath { path, cumulative };
Ok(result)
}
fn main() {
match lesson018() {
Ok(result) => println!("{}", object(&[
("path", numbers(&result.path)),
("cumulative", num(result.cumulative)),
])),
Err(message) => {
eprintln!("Error: {}", message);
std::process::exit(1);
}
}
}
/// Formats a number the way JSON.stringify does: shortest round-trip form, null for NaN or infinity.
fn num(x: f64) -> String {
if x.is_finite() {
format!("{}", x)
} else {
"null".to_string()
}
}
fn quote(text: &str) -> String {
format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
}
/// Indents an already formatted JSON value by one level.
fn nested(json: &str) -> String {
json.replace('\n', "\n ")
}
fn object(fields: &[(&str, String)]) -> String {
if fields.is_empty() {
return "{}".to_string();
}
let lines: Vec<String> = fields
.iter()
.map(|(key, value)| format!(" {}: {}", quote(key), nested(value)))
.collect();
format!("{{\n{}\n}}", lines.join(",\n"))
}
fn array(items: &[String]) -> String {
if items.is_empty() {
return "[]".to_string();
}
let lines: Vec<String> = items.iter().map(|item| format!(" {}", nested(item))).collect();
format!("[\n{}\n]", lines.join(",\n"))
}
fn numbers(values: &[f64]) -> String {
let items: Vec<String> = values.iter().map(|&value| num(value)).collect();
array(&items)
}
No browser runner for Rust yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"path": [
100,
120,
96
],
"cumulative": -0.040000000000000036
}/**
* Fintech Math Bootcamp · Lesson 018 of 120
* Holding-Period and Cumulative Return
* Module 02: Financial Arithmetic, Time Value, and Returns
*
* Scenario: A two-period performance report with changing bases
* Rule: cumulative = Π(1+Rₜ) − 1
*
* Try it: What gain is needed to recover from 96 to 100?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-arithmetic-time-value-and-returns/holding-period-return/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*
* Run it: dotnet run (inside a console project that holds this Program.cs)
*/
using System.Text.Json;
var jsonOptions = new JsonSerializerOptions { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
Console.WriteLine(JsonSerializer.Serialize(Lesson018(), jsonOptions));
static WealthPath Lesson018()
{
double[] returns = { 0.20, -0.20 };
double wealth = 100;
var path = new List<double> { wealth };
foreach (var r in returns)
{
if (!(1 + r > 0)) throw new ArgumentException("Growth factor must be positive");
wealth *= 1 + r;
path.Add(wealth);
}
var result = new WealthPath(path, wealth / path[0] - 1);
return result;
}
record WealthPath(List<double> Path, double Cumulative);
No browser runner for C# yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"path": [
100,
120,
96
],
"cumulative": -0.040000000000000036
}Prefer your own machine? Every file is in the course repository · open it in Codespaces.
Lesson notes
The rule
cumulative = Π(1+Rₜ) − 1