TradeViora AcademyLearn. Analyze. Practice. Trade Smarter.
Menu

FREE FINANCIAL EDUCATION

Python and Pine Script learning library

Runnable examples for data preparation, indicators, risk, options mathematics and execution-aware backtesting.

Run locally, without a paid service

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

Python examples

All 50 examples are executable teaching cases. They are not a live order-management system.

Compute consecutive percentage returns

Prices must be positive; a return is measured against the preceding price.

Download Python

Aggregate logarithmic returns

Log returns add over time; their exponential minus one is the compounded simple return.

Download Python

Build a compounded wealth path

A gain followed by the equal percentage loss leaves wealth below its start.

Download Python

Measure peak-to-trough percentage drawdown

Track the running peak, not only the initial investment.

Download Python

Count observations below a previous peak

The unit is observations, not calendar days. An unrecovered run is counted through the sample end.

Download Python

Annualize endpoint growth

CAGR ignores intermediate path and assumes no external cash flows.

Download Python

Annualize sample return dispersion

Square-root scaling assumes a suitable stable return process. It is not a forecast.

Download Python

Calculate an excess-return Sharpe estimate

Risk-free return and asset observations must use the same period; the sample deviation uses n-1.

Download Python

Measure downside deviation against a target

The denominator averages squared shortfalls across all observations, including zero shortfalls.

Download Python

Summarize a net trade distribution

Zero-profit trades remain in the denominator. Costs should already be included in supplied P&L.

Download Python

Compare gross winning and losing P&L

Profit factor is not a return percentage. With no losing trade the estimate is undefined, not proof of safety.

Download Python

Examine binary-bet Kelly sensitivity

Estimated probabilities are uncertain. A negative result rejects the assumed favorable bet; this is not a sizing recommendation.

Download Python

Round risk-limited units down to lots

This is planned stop risk. Gaps, liquidity, exposure caps and margin can require a smaller position.

Download Python

Implement a rolling arithmetic mean

None marks unavailable warm-up values; never backfill them with future observations.

Download Python

Implement an EMA with first-value seed

Different initialization conventions can disagree early in the sample.

Download Python

Implement Wilder smoothing with SMA seed

The first output occurs only after n inputs; subsequent values use weight 1/n.

Download Python

Include a price gap in true range

A narrow bar after a large gap can have substantial true range.

Download Python

Smooth a sequence of true ranges

Use the previous close for each bar and retain the chosen seed and period.

Download Python

Calculate RSI with an explicit flat-market convention

This implementation returns 50 if both smoothed gains and losses are zero.

Download Python

Build population-deviation bands

Bands describe past dispersion; prices are not guaranteed to remain within them.

Download Python

Calculate VWAP from actual trade prices

This is trade-weighted VWAP. Bar typical-price approximations may differ.

Download Python

Calculate a fixed-window volume-weighted mean

A rolling VWMA does not reset by session like a session VWAP.

Download Python

Accumulate close-direction volume

Unchanged closes add zero. OBV classifies entire bar volume, not actual aggressor order flow.

Download Python

Locate a close inside its range

A close at the midpoint gives zero multiplier; this is not a buyer-seller trade classification.

Download Python

Locate price in a rolling high-low window

A value near 100 does not by itself imply an imminent decline.

Download Python

Exclude current bar from a breakout channel

Using current high in the trigger channel can change or invalidate the intended rule.

Download Python

Compare endpoint momentum

The denominator is the earlier price, not the later price.

Download Python

Measure linear co-movement

Pair observations by timestamp before calculating. Constant series have undefined correlation.

Download Python

Estimate benchmark sensitivity

A beta of two describes sample sensitivity; it does not guarantee double the future return.

Download Python

Adjust a nominal return for inflation

Exact real return is a ratio of growth factors; subtraction is only an approximation.

Download Python

Calculate an interpolated return quantile

VaR is expressed here as loss; it is not maximum loss. Sparse tail samples are unstable.

Download Python

Average sample tail losses

This uses observations at or below the interpolated cutoff, so the selected tail mass can exceed 1-confidence.

Download Python

Resample the mean with a fixed seed

IID resampling ignores serial dependence. For time series, consider block resampling and regime changes.

Download Python

Generate rolling chronological train-test intervals

Intervals are zero-based and end-exclusive. Each test starts after its training segment.

Download Python

Remove training labels that overlap a test interval

If each outcome uses five future observations, training decision index plus five must be below the test start.

Download Python

Combine two call legs at expiry

Premiums are per underlying unit and both legs share the same expiry; fixed costs are charged once.

Download Python

Price a European option under constant volatility

Black-Scholes assumes a simplified diffusion, constant inputs and no early exercise.

Download Python

Check a European option parity identity

The relation requires consistent strike, expiry, underlying and carry assumptions.

Download Python

Invert an interior European option price

An out-of-bound observed premium has no admissible solution under the selected assumptions.

Download Python

Execute a closed-bar signal at the next open

No trade can use the current closing signal at an already elapsed opening price.

Download Python

Compare identical signals at two cost settings

The costlier simulation should not outperform the same execution path with zero fees and slippage.

Download Python

Measure open-position losses before exit

Closed-trade statistics can hide intratrade drawdown; a daily close path still misses intraday extremes.

Download Python

Reconcile a stock split in a position ledger

A split changes units and the per-share price basis; it does not itself create wealth. Cash distributions are separate.

Download Python

Separate investment returns from external cash flows

The portfolio is valued immediately before each external flow. Link subperiod returns; do not treat a contribution as profit.

Download Python

Solve a conventional annual money-weighted return

Only one initial outflow followed by non-negative annual inflows is supported. Irregular dates and multiple sign changes require different analysis.

Download Python

Join events using their actual availability time

A report period is not the time the information became available. Revised data must retain its own publication timestamp.

Download Python

Resample consecutive blocks of a return series

Overlapping moving blocks retain within-block adjacency. The block length remains a modeling choice and does not remove regime uncertainty.

Download Python

Combine covariance and portfolio weights

Sample covariance uses n-1 and contemporaneously paired returns. Diversification calculations are estimates, not stable future guarantees.

Download Python

Reconcile a partial sale using average-cost accounting

This is an educational accounting convention, not a tax-lot election. Sale fees reduce realized proceeds; acquisition fees increase basis.

Download Python

Translate an overseas asset return into home currency

The exchange rate is home-currency units per foreign-currency unit. Total return includes the interaction between asset and currency changes.

Download Python

Pine Script examples

These 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.