Module 2 · Financial Arithmetic, Time Value, and Returns Lesson 16 of 120
Simple Return
A dividend can change the answer even when the price is known.
Transcript
20 sentences · select one to jump thereCheck your understanding
Could adding cash to an already total-return-adjusted series double count?
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 016 of 120
* Simple Return
* Module 02: Financial Arithmetic, Time Value, and Returns
*
* Scenario: A dividend can change the answer even when the price is known
* Rule: R = (P₁ − P₀ + cash)/P₀
*
* Try it: Could adding cash to an already total-return-adjusted series double count?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-arithmetic-time-value-and-returns/simple-return/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*/
export function lesson016() {
const start = 100, end = 108, cash = 2;
if (start <= 0) throw new Error("Positive base required");
const priceReturn = (end - start) / start;
const totalReturn = (end - start + cash) / start;
const result = {priceReturn, totalReturn};
return result;
}
export const checkedResult = {"priceReturn":0.08,"totalReturn":0.1};
// Run this file directly: npx tsx lessons/02-financial-arithmetic-time-value-and-returns/016-simple-return.ts
if (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, "/").split("/").pop()!)) {
console.log(JSON.stringify(lesson016(), null, 2));
}
Your output
Press Run to execute the code in your browser.
Expected output
{
"priceReturn": 0.08,
"totalReturn": 0.1
}"""
Fintech Math Bootcamp · Lesson 016 of 120
Simple Return
Module 02: Financial Arithmetic, Time Value, and Returns
Scenario: A dividend can change the answer even when the price is known
Rule: R = (P₁ − P₀ + cash)/P₀
Try it: Could adding cash to an already total-return-adjusted series double count?
Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-arithmetic-time-value-and-returns/simple-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 lesson016() -> dict:
start, end, cash = 100, 108, 2
if start <= 0:
raise ValueError("Positive base required")
price_return = (end - start) / start
total_return = (end - start + cash) / start
result = {"priceReturn": price_return, "totalReturn": total_return}
return result
if __name__ == "__main__":
print(json.dumps(lesson016(), indent=2))
Your output
Press Run to execute the code in your browser.
Expected output
{
"priceReturn": 0.08,
"totalReturn": 0.1
}/**
* Fintech Math Bootcamp · Lesson 016 of 120
* Simple Return
* Module 02: Financial Arithmetic, Time Value, and Returns
*
* Scenario: A dividend can change the answer even when the price is known
* Rule: R = (P1 − P0 + cash)/P0
*
* Try it: Could adding cash to an already total-return-adjusted series double count?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-arithmetic-time-value-and-returns/simple-return/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*
* Run it: javac Main.java && java Main
*/
public class Main {
static final class HoldingReturn {
final double priceReturn;
final double totalReturn;
HoldingReturn(double priceReturn, double totalReturn) {
this.priceReturn = priceReturn;
this.totalReturn = totalReturn;
}
}
static HoldingReturn lesson016() {
double start = 100, end = 108, cash = 2;
if (start <= 0) throw new IllegalArgumentException("Positive base required");
double priceReturn = (end - start) / start;
double totalReturn = (end - start + cash) / start;
HoldingReturn result = new HoldingReturn(priceReturn, totalReturn);
return result;
}
public static void main(String[] args) {
HoldingReturn result = lesson016();
System.out.println(object(
"priceReturn", num(result.priceReturn),
"totalReturn", num(result.totalReturn)));
}
// 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();
}
}
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
{
"priceReturn": 0.08,
"totalReturn": 0.1
}// Fintech Math Bootcamp · Lesson 016 of 120
// Simple Return
// Module 02: Financial Arithmetic, Time Value, and Returns
//
// Scenario: A dividend can change the answer even when the price is known
// Rule: R = (P₁ − P₀ + cash)/P₀
//
// Try it: Could adding cash to an already total-return-adjusted series double count?
//
// Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-arithmetic-time-value-and-returns/simple-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 HoldingReturn struct {
PriceReturn float64 `json:"priceReturn"`
TotalReturn float64 `json:"totalReturn"`
}
func lesson016() (HoldingReturn, error) {
start, end, cash := 100.0, 108.0, 2.0
if start <= 0 {
return HoldingReturn{}, errors.New("Positive base required")
}
priceReturn := (end - start) / start
totalReturn := (end - start + cash) / start
result := HoldingReturn{PriceReturn: priceReturn, TotalReturn: totalReturn}
return result, nil
}
func main() {
result, err := lesson016()
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
{
"priceReturn": 0.08,
"totalReturn": 0.1
}/**
* Fintech Math Bootcamp · Lesson 016 of 120
* Simple Return
* Module 02: Financial Arithmetic, Time Value, and Returns
*
* Scenario: A dividend can change the answer even when the price is known
* Rule: R = (P₁ − P₀ + cash)/P₀
*
* Try it: Could adding cash to an already total-return-adjusted series double count?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-arithmetic-time-value-and-returns/simple-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}";
}
struct HoldingReturn {
double priceReturn;
double totalReturn;
};
HoldingReturn lesson016() {
const double start = 100, end = 108, cash = 2;
if (start <= 0) throw std::invalid_argument("Positive base required");
const double priceReturn = (end - start) / start;
const double totalReturn = (end - start + cash) / start;
const HoldingReturn result{priceReturn, totalReturn};
return result;
}
int main() {
const HoldingReturn result = lesson016();
std::cout << object({
{"priceReturn", num(result.priceReturn)},
{"totalReturn", num(result.totalReturn)}
}) << "\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
{
"priceReturn": 0.08,
"totalReturn": 0.1
}//! Fintech Math Bootcamp · Lesson 016 of 120
//! Simple Return
//! Module 02: Financial Arithmetic, Time Value, and Returns
//!
//! Scenario: A dividend can change the answer even when the price is known
//! Rule: R = (P₁ − P₀ + cash)/P₀
//!
//! Try it: Could adding cash to an already total-return-adjusted series double count?
//!
//! Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-arithmetic-time-value-and-returns/simple-return/
//! Free course: https://courses.thefintechbuilder.com
//! Synthetic teaching example, not financial advice or a production library.
//!
//! Run it: rustc main.rs && ./main
struct HoldingReturn {
price_return: f64,
total_return: f64,
}
fn lesson016() -> Result<HoldingReturn, String> {
let (start, end, cash): (f64, f64, f64) = (100.0, 108.0, 2.0);
if start <= 0.0 {
return Err("Positive base required".to_string());
}
let price_return = (end - start) / start;
let total_return = (end - start + cash) / start;
let result = HoldingReturn { price_return, total_return };
Ok(result)
}
fn main() {
match lesson016() {
Ok(result) => println!("{}", object(&[
("priceReturn", num(result.price_return)),
("totalReturn", num(result.total_return)),
])),
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"))
}
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
{
"priceReturn": 0.08,
"totalReturn": 0.1
}/**
* Fintech Math Bootcamp · Lesson 016 of 120
* Simple Return
* Module 02: Financial Arithmetic, Time Value, and Returns
*
* Scenario: A dividend can change the answer even when the price is known
* Rule: R = (P₁ − P₀ + cash)/P₀
*
* Try it: Could adding cash to an already total-return-adjusted series double count?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-arithmetic-time-value-and-returns/simple-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(Lesson016(), jsonOptions));
static HoldingReturn Lesson016()
{
double start = 100, end = 108, cash = 2;
if (start <= 0) throw new ArgumentException("Positive base required");
var priceReturn = (end - start) / start;
var totalReturn = (end - start + cash) / start;
var result = new HoldingReturn(priceReturn, totalReturn);
return result;
}
record HoldingReturn(double PriceReturn, double TotalReturn);
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
{
"priceReturn": 0.08,
"totalReturn": 0.1
}Prefer your own machine? Every file is in the course repository · open it in Codespaces.
Lesson notes
The rule
R = (P₁ − P₀ + cash)/P₀