mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-07 05:27:43 +00:00
50 lines
1.7 KiB
Plaintext
50 lines
1.7 KiB
Plaintext
// Licensed under the Apache License, Version 2.0
|
|
// © mihakralj
|
|
//@version=6
|
|
indicator("Fibonacci Weighted Moving Average (FWMA)", "FWMA", overlay=true)
|
|
|
|
//@function Calculates FWMA using Fibonacci sequence as weights with adaptive warmup
|
|
//@param source Series to calculate FWMA from
|
|
//@param period Lookback period - FIR window size (number of Fibonacci weights)
|
|
//@returns FWMA value, calculates from first bar using available data
|
|
//@optimized Precomputes Fibonacci weights when period changes; O(period) per bar
|
|
fwma(series float source, simple int period) =>
|
|
if period <= 0
|
|
runtime.error("Period must be greater than 0")
|
|
int p = math.min(bar_index + 1, period)
|
|
var array<float> weights = array.new_float(1, 1.0)
|
|
var int last_p = 1
|
|
if last_p != p
|
|
weights := array.new_float(p, 0.0)
|
|
// Generate Fibonacci sequence: F(1)=1, F(2)=1, F(3)=2, ...
|
|
float prev2 = 0.0
|
|
float prev1 = 1.0
|
|
for i = 0 to p - 1
|
|
float fib = (i == 0) ? 1.0 : (i == 1) ? 1.0 : prev1 + prev2
|
|
// Reverse: index 0 = most recent bar gets F(p), last index gets F(1)
|
|
array.set(weights, p - 1 - i, fib)
|
|
prev2 := prev1
|
|
prev1 := fib
|
|
last_p := p
|
|
float sum = 0.0
|
|
float weight_sum = 0.0
|
|
for i = 0 to p - 1
|
|
float price = source[i]
|
|
if not na(price)
|
|
float w = array.get(weights, i)
|
|
sum += price * w
|
|
weight_sum += w
|
|
nz(sum / weight_sum, source)
|
|
|
|
// ---------- Main loop ----------
|
|
|
|
// Inputs
|
|
i_period = input.int(10, "Period", minval=1)
|
|
i_source = input.source(close, "Source")
|
|
|
|
// Calculation
|
|
fwma_value = fwma(i_source, i_period)
|
|
|
|
// Plot
|
|
plot(fwma_value, "FWMA", color=color.yellow, linewidth=2)
|