Compute consecutive percentage returns
Prices must be positive; a return is measured against the preceding price.
Download PythonFREE FINANCIAL EDUCATION
Runnable examples for data preparation, indicators, risk, options mathematics and execution-aware backtesting.
The Python examples use only the standard library and fixed synthetic inputs. Download the pack, keep tv_math.py beside the examples, and run an example with Python 3.10 or newer. Every Python file includes executable assertions and explains its conventions. No account, market feed or API key is needed.
python 01_simple-returns.py python run_all.py
Download all code examples · Open the browser research lab · Open the original SMA lab
All 50 examples are executable teaching cases. They are not a live order-management system.
Prices must be positive; a return is measured against the preceding price.
Download PythonLog returns add over time; their exponential minus one is the compounded simple return.
Download PythonA gain followed by the equal percentage loss leaves wealth below its start.
Download PythonTrack the running peak, not only the initial investment.
Download PythonThe unit is observations, not calendar days. An unrecovered run is counted through the sample end.
Download PythonCAGR ignores intermediate path and assumes no external cash flows.
Download PythonSquare-root scaling assumes a suitable stable return process. It is not a forecast.
Download PythonRisk-free return and asset observations must use the same period; the sample deviation uses n-1.
Download PythonThe denominator averages squared shortfalls across all observations, including zero shortfalls.
Download PythonZero-profit trades remain in the denominator. Costs should already be included in supplied P&L.
Download PythonProfit factor is not a return percentage. With no losing trade the estimate is undefined, not proof of safety.
Download PythonEstimated probabilities are uncertain. A negative result rejects the assumed favorable bet; this is not a sizing recommendation.
Download PythonThis is planned stop risk. Gaps, liquidity, exposure caps and margin can require a smaller position.
Download PythonNone marks unavailable warm-up values; never backfill them with future observations.
Download PythonDifferent initialization conventions can disagree early in the sample.
Download PythonThe first output occurs only after n inputs; subsequent values use weight 1/n.
Download PythonA narrow bar after a large gap can have substantial true range.
Download PythonUse the previous close for each bar and retain the chosen seed and period.
Download PythonThis implementation returns 50 if both smoothed gains and losses are zero.
Download PythonBands describe past dispersion; prices are not guaranteed to remain within them.
Download PythonThis is trade-weighted VWAP. Bar typical-price approximations may differ.
Download PythonA rolling VWMA does not reset by session like a session VWAP.
Download PythonUnchanged closes add zero. OBV classifies entire bar volume, not actual aggressor order flow.
Download PythonA close at the midpoint gives zero multiplier; this is not a buyer-seller trade classification.
Download PythonA value near 100 does not by itself imply an imminent decline.
Download PythonUsing current high in the trigger channel can change or invalidate the intended rule.
Download PythonThe denominator is the earlier price, not the later price.
Download PythonPair observations by timestamp before calculating. Constant series have undefined correlation.
Download PythonA beta of two describes sample sensitivity; it does not guarantee double the future return.
Download PythonExact real return is a ratio of growth factors; subtraction is only an approximation.
Download PythonVaR is expressed here as loss; it is not maximum loss. Sparse tail samples are unstable.
Download PythonThis uses observations at or below the interpolated cutoff, so the selected tail mass can exceed 1-confidence.
Download PythonIID resampling ignores serial dependence. For time series, consider block resampling and regime changes.
Download PythonIntervals are zero-based and end-exclusive. Each test starts after its training segment.
Download PythonIf each outcome uses five future observations, training decision index plus five must be below the test start.
Download PythonPremiums are per underlying unit and both legs share the same expiry; fixed costs are charged once.
Download PythonBlack-Scholes assumes a simplified diffusion, constant inputs and no early exercise.
Download PythonThe relation requires consistent strike, expiry, underlying and carry assumptions.
Download PythonAn out-of-bound observed premium has no admissible solution under the selected assumptions.
Download PythonNo trade can use the current closing signal at an already elapsed opening price.
Download PythonThe costlier simulation should not outperform the same execution path with zero fees and slippage.
Download PythonClosed-trade statistics can hide intratrade drawdown; a daily close path still misses intraday extremes.
Download PythonA split changes units and the per-share price basis; it does not itself create wealth. Cash distributions are separate.
Download PythonThe portfolio is valued immediately before each external flow. Link subperiod returns; do not treat a contribution as profit.
Download PythonOnly one initial outflow followed by non-negative annual inflows is supported. Irregular dates and multiple sign changes require different analysis.
Download PythonA report period is not the time the information became available. Revised data must retain its own publication timestamp.
Download PythonOverlapping moving blocks retain within-block adjacency. The block length remains a modeling choice and does not remove regime uncertainty.
Download PythonSample covariance uses n-1 and contemporaneously paired returns. Diversification calculations are estimates, not stable future guarantees.
Download PythonThis is an educational accounting convention, not a tax-lot election. Sale fees reduce realized proceeds; acquisition fees increase basis.
Download PythonThe exchange rate is home-currency units per foreign-currency unit. Total return includes the interaction between asset and currency changes.
Download PythonThese 12 original sources use documented version 6 constructs. Platform compilation is a remaining validation step; no compiler result is claimed. Strategy orders use the next available tick under the default broker emulator, with explicit illustrative costs. Real fills, session rules and broker charges can differ.
Reference: TradingView Pine strategy documentation. TradingView is a third-party platform; these files are independent educational examples.