<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="gfn2html.xsl"?>
<gretl-functions>
<gretl-function-package name="ema_tools" minver="2018a">
<author email="christianlagunes2@outlook.com">Christian</author>
<version>1.0</version>
<date>2026-10-25</date>
<description>Optimal alpha for SES</description>
<tags>C22</tags>
<help>
ema_alpha_opt: Optimal alpha for SES

This function finds the optimal smoothing parameter alpha for Simple
Exponential Smoothing. It complements gretls native movavg()) function,
which already performs SES but requires alpha as input.

The optimal alpha is found by minimizing the sum of squared one-step
forecast errors (excluding the first observation).

Usage
scalar alpha = ema_alpha_opt (y)
series smooth = movavg (y,alpha)

Returns the optimal alpha in (0,1)

Note: Similar functionality for SES exists in the fcModels package
(autoSES function), which prints the optimal alpha. This package differs
by returning the optimal alpha as scalar for further use with movavg().
It also respects sub-sampled datasets
</help>
<gretl-function name="ema_alpha_opt" type="scalar" must-assign="1">
 <params count="1">
  <param name="y" type="series"/>
 </params>
<code>errorif(sum(missing(y)), &quot;found missings in input&quot;)
scalar best = 0.5
scalar min = $huge
loop i=1..99 --quiet
  scalar a = i / 100
  series tmp = movavg(y,a)
  scalar sse = sum( (y - tmp(-1))^2)
  if sse &lt; min
    min = sse
    best = a
  endif
endloop
return best
</code>
</gretl-function>
<sample-script>
include ema_tools.gfn
open australia.gdt --quiet

#Optimal alpha for PAU - interior solution
series dPAU = diff(PAU)
smpl dPAU --contiguous
scalar a = ema_alpha_opt(dPAU)
print a

#Smoothed with optimal alpha using native function
smpl full
series suav_opt = movavg(dPAU, a)

#Plot to compare
gnuplot dPAU suav_opt --with-lines --time-series --output=display
</sample-script>
</gretl-function-package>
</gretl-functions>

