ApasScript.

Finance

sma

Simple moving average over a window of bars; the bars before the window fills are NaN (a gap in a plot). From gtfinance, checked against TA-Lib.

ema

Exponential moving average with the usual 2/(n + 1) smoothing.

wma

Weighted moving average, the newest bar weighted most.

hma

Hull moving average, a fast smooth average.

dema

Double exponential moving average.

tema

Triple exponential moving average.

roc

Rate of change, the percentage change over the period.

trix

TRIX, the one-bar rate of change of a triple-smoothed average, in percent.

rsi

Relative strength index (Wilder), 0 to 100; the period is 14 when left out.

macd

MACD: a record with the lists line, signal and histogram (12, 26, 9 by default).

bollinger

Bollinger bands: a record with the lists middle, upper and lower (period 20, 2 standard deviations by default).

atr

Average true range (Wilder) from highs, lows and closes; the period is 14 by default.

adx

Average directional index, the trend's strength 0 to 100.

cci

Commodity channel index.

williamsR

Williams %R, -100 to 0.

mfi

Money flow index, a volume-weighted RSI, 0 to 100.

cmf

Chaikin money flow, -1 to 1.

stochastic

Stochastic oscillator: a record with the lists k and d (14 and 3 by default).

vwap

Volume-weighted average price, cumulative from the first bar.

obv

On-balance volume from closes and volumes.

adl

Accumulation/distribution line.

donchian

Donchian channel: a record with the lists upper, middle and lower (period 20 by default).

keltner

Keltner channel: a record with the lists upper, middle and lower (period 20, ATR multiplier 2 by default).

parabolicSar

Parabolic SAR stop levels (acceleration 0.02, maximum 0.2 by default).

ichimoku

Ichimoku cloud: a record with the lists tenkan, kijun, senkouA, senkouB and chikou (9, 26, 52 by default).

pivotPoints

Pivot points: with one high, low and close a record of numbers pivot, r1, r2, r3, s1, s2, s3; with lists a record of lists, row by row; pivotPoints(times, highs, lows, closes[, kind]) gives each bar the previous session's levels (sessions read from the times' days), the first session null, so plot() draws the day's pivots on an intraday chart. The kind is "classic" (or "standard"), "fibonacci" or "camarilla".

fibLevels

Fibonacci levels of a move from low to high: a record with retracement (23.6, 38.2, 50, 61.8, 78.6 percent) and extension (127.2, 161.8 percent) lists; up = false mirrors them for a down move.

parkinson

Parkinson volatility estimate per bar from highs and lows.

garmanKlass

Garman-Klass volatility estimate per bar from opens, highs, lows and closes.

moveZScore

How many standard deviations a move is against a history of at least 30 earlier moves.

xirr

The yearly rate (actual days over 365, as Excel's XIRR) at which dated cash flows net to zero: money paid in is negative, money received positive. Cash flows are taken to the paisa. An error says so when no rate exists (all flows one sign). From gtfinance, checked against an independent implementation.

sipXirr

A monthly SIP over a NAV series. Each instalment falls on the day of the month (the month's last day when it is shorter) and buys at the first NAV on or after it; the final value is the units times the last NAV on or before the end date. Returns a record: xirr, invested, units, value, instalments, valuationDate. Past returns only; not a forecast or advice.

rolling

Rolling returns over a NAV series. For every NAV date, the window ends at the last NAV on or before date + windowDays (windows ending more than toleranceDays short of that, or past the last NAV, are left out; when none fits the lists are empty and summary.count is 0). Returns a record: startDate, endDate, absolute and annualised lists (annualised, (end/start)^(365/days used) - 1, only for windows of 365 days or more, else NaN) and summary: count, min, max, mean, median, p10, p90, shareNegative of the annualised returns (the absolute ones for a shorter window). Past returns only; not a forecast or advice.

drawdown

How far a NAV series is below its running peak, 1 - NAV/peak at each date, and the worst fall: a record with series, max, peakDate, troughDate, recoveryDate (NaN when the NAV never got back to the peak), underwaterDays (peak to recovery, or to the last date) and current. Past returns only; not a forecast or advice.

valueHoldings

Values a set of holdings: each one's value (units times price), cost (units times cost per unit), gain as a fraction of its cost (NaN when the cost is 0) and weight of the total value, as lists, and a total record with value, cost, gain and gainPct. The price is an AMFI NAV or a last traded price. Arithmetic on what is held; not advice.

pointReturn

The return between two NAVs some days apart: a record with absolute (end over start, less 1) and annualised ((end/start)^(365/days) - 1, NaN for spans under 365 days). Past returns only; not a forecast.

lumpVsSip

The same money two ways on past NAVs: the SIP of sipXirr (xirr, invested, units, value, instalments, valuationDate) and its total put in at once at the first NAV on or after the start date and valued on the same day (lumpUnits, lumpValue, lumpXirr, lumpDate). A look back, not a forecast or advice.

swpOnSeries

A systematic withdrawal plan on past NAVs: the corpus buys at the first NAV on or after the start date; on the day of each month after it the withdrawal is sold at the first NAV on or after that day, the last units when fewer remain. A record with xirr (of the corpus out, the withdrawals in and the value left; NaN when none solves), withdrawn, withdrawals, unitsLeft, valueLeft, depletedDate (NaN when the plan outlasts the series) and valuationDate. Past data only; not a forecast or advice.

sipForTarget

The monthly instalment, paid at each month end, whose value after the months is the target if money grew at the yearly rate given (an effective rate; the monthly rate is (1 + r)^(1/12) - 1). Arithmetic at an assumed rate, not a forecast or advice.

riskStats

Risk measures of a NAV series from the simple returns between its dates: a record with returns (their count), periodsPerYear (returns x 365 over the days spanned), meanAnnual, volAnnual (sample standard deviation, annualised), downsideAnnual (deviation below the risk-free rate), sharpe and sortino (NaN when the deviation is 0). The risk-free rate is an effective yearly rate, 0.06 for 6 percent. About the past only; not advice.

relativeStats

A scheme against a reference series (another scheme, an index fund or an ETF) on their common dates: a record with common (the dates shared), periodsPerYear, beta, correlation, rSquared, alphaAnnual (Jensen's alpha, yearly), trackingError, informationRatio, upCapture and downCapture (NaN where a denominator is 0 or no such period exists). About the past only; not advice.

terEffect

What an expense ratio takes: an amount grown for the years at an assumed yearly gross return, at the gross return less expense ratio A and less expense ratio B (a direct and a regular plan, say): a record with grossValue, valueA, valueB, dragA, dragB (each against the gross value) and aMinusB. Arithmetic at assumed rates; not a forecast or advice.

capitalGains

The capital gain on one sale against dated lots, first in first out: a lot is long term when held more than the holding days; a short-term loss is set off against a long-term gain but not the other way; the exemption comes off the long-term gain; tax = rate x taxable gain. A record with proceeds, costSold, stcg, ltcg, taxableStcg, taxableLtcg, tax and lotsTouched. No surcharge, cess or indexation; the rules are inputs, as the law and the kind of fund change them. Arithmetic on the rules given, not tax advice.

percentileRank

Where a value stands among peer values: a record with percentile (the share below, ties counting half), rank (1 for the highest) and of (the count). Position only; it says nothing about why or what comes next.

policyReturn

The return a policy gives: the XIRR (ACT/365) of the premiums paid (money out) and the benefits received (maturity, survival, surrender or death benefit, money in), merged by date. A record with xirr (NaN when no rate solves the flows), premiums, benefits, net (benefits less premiums) and multiple (benefits over premiums). Arithmetic on the amounts given; nothing here says what to buy.

premiumSchedule

The premium dates for the years at 1, 2, 4 or 12 payments a year from the first date: a list of day numbers, each on the first date's day of the month, clamped to the month's length (31 Jan, 28 Feb, 31 Mar). Premiums fall at the start of each period.

coverNeed

Cover against stated needs: the present value of a yearly need in today's money over the years, at the real rate (1 + return)/(1 + inflation) - 1 as an ordinary annuity, plus liabilities and goals due; against the cover held and the assets set aside. A record with realRate, annuityFactor, incomeValue, need, available, gap (need less available, or 0), surplus (available less need, or 0) and availableToNeed. Arithmetic on the numbers given, not a recommendation of an amount of cover.

expectedRange

The expected range of a session from the log-linear model of gtfinance (quant-rust indicator I1): a record with median, mean, p10 and p90, all in percent of the open. The six coefficients and sigma come from fitRangeModel (or the stored range_model row); r1 is yesterday's high-low range in percent of its open, m5 and m20 its 5- and 20-day means, vixOpen the India VIX at the open, gap the opening gap in percent. A forecast of a range, never of direction.

rangeUsed

The range so far today, high less low in percent of the open, as a fraction of the expected range: 1 means the session has done what was expected.

rangeFeatures

The inputs of expectedRange for session i (0-based, 20 or more) of a daily series, as the fit script builds them: a record with r1, m5, m20, vixOpen and gap.

fitRangeModel

Refits the expected-range model on a daily series (R277, R280): a row for every session from the 21st, its target the session's own high-low range in percent of the open, or with "move" its absolute open-to-close move, so the same expectedRange then forecasts a move. A record with coef (six numbers), sigma, rSquared and sessions. Needs 32 sessions or more; a fit on the past, not a promise about the future.

impliedMinusRealised

Implied less realised volatility in volatility points: the implied figure is annualised percent (the India VIX), the realised one a per-bar estimator from parkinson or garmanKlass (a fraction), scaled by the square root of the bars in a year (75 x 252 for 5-minute bars). Positive when options are priced above what the market has done.

todZScore

How unusual today's move to a minute of the session is (quant-rust indicator I3): from intraday bars with the minute of the session of each (0 at the first bar; a smaller minute than the bar before opens a new session), each session's move is its close at the last bar on or before the minute over its first bar's open, less 1, in percent. Today is the last session; its move is divided by the population standard deviation of the same move on the look-back sessions before it (at least 30). A record with zscore, move, sd and sessions.

oiWalls

The strikes of the largest call and put open interest of a chain (resistance and support as traders read them, which is only what the chain shows): a record with callWall, callWallOi, putWall, putWallOi, callDistance and putDistance (percent of the spot, positive when the call wall is above and the put wall below) and pcr (put OI over call OI).

oiShift

The change in open interest from one snapshot of a chain to the next, by band: a record with callAbove and callBelow (strikes above the spot, and at or below it), putAbove and putBelow, callTotal, putTotal, pcrBefore and pcrAfter. Calls added above the spot and puts added below it are the usual writing pattern.

buildup

Price change against open-interest change, as the futures market reads them: "long buildup" (both up), "short buildup" (price down, OI up), "short covering" (price up, OI down), "long unwinding" (both down), "flat" when either is zero.

gex

Gamma exposure of a chain: for each strike the Black-Scholes gamma times the open interest times the lot times spot squared times 0.01, calls positive and puts negative (dealers taken long the calls and short the puts), so the figure is the dealers' hedging flow in money for a one percent move. A record with perStrike, total, call, put and flip (the first strike at which the running sum from the lowest strike turns non-negative; NaN when none). A model's estimate on stated assumptions.

ivSkew

The mean implied volatility of the puts below the spot less that of the calls above it, both within a band of the spot: a record with putIv, callIv, skew, puts and calls (the strikes counted; NaN parts when a side has none). The change of skew between two snapshots is the difference of two such figures.

resampleBars

Bars gathered into a longer interval from the bars given, as the chart server's own resampling does: resampleBars(times, opens, highs, lows, closes, volumes, rule[, openMinute]) returns a record of lists times, open, high, low, close, volume. The rule is a count of minutes (buckets counted from the session open, 09:15 for the NSE, so 15 gives 09:15, 09:30, ...; a bucket never crosses a day; a bar before the open is dropped; each bar is stamped at its bucket's start), or "day", "week" (Monday to Sunday) or "month", each stamped at its first bar's time. The open is the first bar's, the high the highest, the low the lowest, the close the last bar's, the volume the sum (give [] for none). The times are dateTimeDays values (or date() days for daily bars) in order; a last bucket still filling is given as it stands. Checked against quant-rust's chartdb on a year of Nifty 5-minute bars.

percentChange

Each value's change from the first value in percent, 100 (x / x0 - 1): two symbols rebased for a compare chart (the chart's own percent scale is yScale(g, "percent")). A null in the list (an indicator's warm-up) stays null.

spread

The spread a - b bar by bar, for a pair or a price against its average; a null on either side stays null.

ratio

The ratio a / b bar by bar (a relative-strength line); a null on either side, or a zero divisor, gives null, a gap in the plot.

supertrend

Supertrend: a record with the lists line, direction (+1 up, -1 down), up and down (the line split by direction, each for a plot() in its colour), upper and lower (the bands in force); hl2 +- multiplier * ATR(period), period 10 and multiplier 3 by default, null through the ATR's warm-up.

anchoredVwap

Anchored VWAP: the volume-weighted average of the typical price (H+L+C)/3 from the first bar at or after the anchor time on, null before it; the times in the bars' unit (dateTimeDays).

sessionVwapBands

Session VWAP with sigma bands: a record with the lists vwap, sd (the volume-weighted standard deviation of the typical price this session) and upper1, lower1, upper2, lower2 (one pair a sigma; [1, 2] unless given), the accumulators reset where the times' day changes.

volumeProfile

Volume profile: the volume traded at each price row between the lowest low and the highest high (each bar's volume spread over the rows its range covers), a record with the lists price (the row's middle), low, high and volume, and the numbers poc (the point of control, the heaviest row's middle), vaHigh and vaLow (the value area holding the share of the volume, 0.7 unless given), total and step; 24 rows unless given. showVolumeProfile(g, volumes) draws it at the right of a chart.

strategyPayoff

What an option position pays (R316): legs as a list of {"kind": "call" or "put", "side": "buy" or "sell", "strike", "premium", "qty"} (premium 0 and qty 1 unless given; qty is the lots times the lot size; an "iv" of a leg's own, a fraction a year, overrides the position's), spots a list of prices to work the profit at or the spot alone (then 121 prices about the strikes). A record: spots, expiry (the profit at each spot at expiry), today (the Black-Scholes profit now at iv, days to expiry and the rate; the expiry profit when iv and days are left out), breakevens (every spot where the expiry profit crosses zero, exact), maxProfit and maxLoss (the loss as a size; the word "unlimited" when so), netPremium (positive a debit, negative a credit) and netKind ("debit", "credit" or "even"), spot (the one given, else the middle of the list) with value, delta, gamma, theta (a day) and vega of the whole position there, and legs as read. showPayoff(g, record) draws it.

strategy

The legs of a named option strategy about the at-the-money strike (the spot rounded to the strike step), premiums 0 until priceLegs or the chain fills them: "long-straddle", "short-straddle" (a call and a put at the money), "long-strangle", "short-strangle" (the put width strikes below, the call width above), "bull-call-spread", "bear-call-spread", "bull-put-spread", "bear-put-spread" (at the money and width strikes away), "iron-condor" (the short put and call width strikes away, the long ones another width out), "butterfly" (calls at width below, at the money twice, width above), "iron-butterfly" (a short straddle with the wings width strikes away). A list of leg records for strategyPayoff.

priceLegs

Each leg's premium set to its Black-Scholes value (no dividend) at the spot, the implied volatility (a leg's own iv when it has one), the days to expiry and the rate: the legs back with their premiums, for strategyPayoff when no chain gives them.

tradeCharges

The charges of one order leg on an Indian broker (R317), an estimate from one rate table (Dhan's brokerage, STT or CTT, the exchange's transaction charge, the SEBI fee, stamp duty, GST, the DP charge of a delivery sell) kept with the date it was last checked: a record with value (price x qty x multiplier), brokerage, tax (STT or CTT: on the sell leg; delivery shares both legs), exchange, sebi, stamp (the buy leg), gst (on the brokerage, exchange and SEBI charges, never on the taxes), total, and note (the rates' standing in words). The kinds: "equity" (intraday or delivery), "index-futures", "index-options", "stock-futures", "stock-options", "commodity-futures", "commodity-options", or the exchange's FUTIDX, OPTIDX, FUTSTK, OPTSTK, FUTCOM, OPTFUT.

roundTripCost

An entry and its exit after charges: a record with entry and exit (each the record tradeCharges gives), gross (the points times the quantity and multiplier, a buy gaining when the exit is higher), charges (both legs), net, perUnit (the charges a point a unit, the break-even move) and note.