Functions

<< Click to Display Table of Contents >>

Navigation:  Gekko functions >

Functions

Previous pageReturn to chapter overviewNext page

Gekko has a number of in-built functions, listed below. Note that all Gekko functions implement so-called UFCS so that a function like for instance f(x, y) can generally be written as x.f(y), and f(x) can generally be written as x.f().

 

Mathematical functions:

 

Function name

Description

Examples

abs(x)

Returns the absolute value of x (series, val or matrix).

Returns: series/value/matrix

%v1 = abs(%v2);

avg(x1, x2, ...)

Returns the average of x1, x2, ... etc. The input parameters may be series or value.

Returns: series/value

= avg(x1, x2, x3);
%= avg(%v1, %v2, %v3);

avgt(x)

avgt(<t1 t2>, x)

Returns the time-average of the observations of the timeseries x over the local/global time period (or over t1 to t2, if indicated)

Returns: series

= avgt(x);
= avgt(<2020 2025>, x);
= x.avgt(<2020 2025>);  //same as above

ceiling(x)

Returns the the smallest integer which is greater than or equal to x (series, val or matrix). See also int(), floor() and round().

Returns: series/value/matrix

PRT ceiling(-2.2);

dif(x) or diff(x)

Absolute time-difference of  series x: can also be used on left side of '='. Does not work on value.

Returns: series

= dif(x);
dif(y) = 100;

dify(x) or diffy(x)

Yearly difference. Same as dif(x), but will use 4 lags for quarterly data, and 12 lags for monthly data.

Returns: series

= dify(x);

dlog(x)

Logarithmic time-difference of series x: can also be used on left side of '='. Does not work on value.

Returns: series

= dlog(x);
dlog(y) = 0.02;

dlogy(x)

Yearly logarithmic time-difference. Same as dlog(x), but will use 4 lags for quarterly data, and 12 lags for monthly data.

Returns: series

= dlogy(x);

exp(x)

Returns the exponential value of x (series, value or matrix).

Returns: series/value

= exp(x);
%v1 = exp(%v2);

floor(x)

Returns the largest integer which is less than or equal to x (series, val or matrix). See also int(), ceiling() and round().

Returns: series/value/matrix

PRT floor(-2.2);

iif(in1, op, in2, out1, out2)

 

Conditional, works like an if statement. Think of it like IF in1 op in2 THEN out1 ELSE out2, where op is a string containing the operator ==, <>, <, <=, >=, >. The function can be used to avoid explicit time looping for timeseries. The op input must be a string, and the rest of the inputs must be of math type (there is another iif()-example here). You may alternatively use $-conditionals, see examples under SERIES. See also the replace() and isMiss() functions for series.

Returns: series/value

TIME 2010 2012;
in1 = 1, 2, 3;
in2 = 3, 2, 1;
= iif(in1, '<=', in2, 50, 100);
Result: y = 50, 50, 100.

int(x)

Returns the integer value of x (series, val or matrix), discarding the fractional part (after the .). See also floor(), ceiling() and round().

Returns: series/value/matrix

PRT int(-2.2);

isMiss(x)

If the value x is missing, the function returns 1, else 0.  The input parameter may be series or value.

Returns: series/value

PRT isMiss(1);
PRT isMiss(miss());
TIME 2020 2023;
xx = 1, m(), 3, m();
PRT <n> isMiss(xx), 1 - isMiss(xx);
//Note that for 2023, the function returns a
//missing value. The function only finds missing
//values between non-missing values.

lag(x, lag)

Lags series x a number of periods. Note the sign of the lag: lag(x, 2) = x[-2]. Can be used if x is an expression.

Returns: series

= lag(x, 2);  //same as x[-2]

log(x)

Returns the natural logarithmic value of x (series, value or matrix). Can also be used on the left side of '='.

Returns: series/value/matrix

= log(x);
%v1 = log(%v2);

log(y) = a * log(b);

max(x1, x2, ... )

Finds the largest of any  number of values. (max() can also be used with date arguments).

Returns: value.

[New in 3.1.6]

PRT max(2, 4, 1, 3);

min(x1, x2, ... )

Finds the smallest of any number of values. (min() can also be used with date arguments).

Returns: value.

[New in 3.1.6]

PRT min(2, 4, 1, 3);

movavg(x1, lags)

Moving average of series x1.

Returns: series

= movavg(x, 3);
= (+ x[-1] + x[-2])/3;  //same

movsum(x1, lags)

Moving sum of series x1, cf. movavg().

Returns: series

= movsum(x, 3);
= x + x[-1] + x[-2];  //same

pch(x)

Percentage growth in series x: can also be used on left side of '='. Does not work on value.

Returns: series

= pch(x);
pch(y) = 2;

pchy(x)

Yearly growth. Same as pch(x), but will use 4 lags for quarterly data, and 12 lags for monthly data.

Returns: series

= pchy(x);

pow(x, y)

The exponent must be a value or number, not a series. The function pow(x, y) is equal to x**y or x^y, that is, a in the y'th power. You may use power(x, y) as synonym.

Returns: series/value

= pow(x1, %x2);
%= pow(%x1, %x2);

rnorm(mean, var)

rnorm(mean, vcov)

Returns a random number from a normal distribution with mean and variance provided. If fed with a n x 1 matrix of averages, and a n x n covariance matrix, the function will return a n x 1 matrix of values. See also rseed() and runif().

Returns: value/matrix

%= rnorm(0, 1);
%= rnorm(-100, 25**2);
#= rnorm(#mean, #vcovar);

rseed(x)

Given value x, it sets a random seed for runif() and rnorm() functions. The function returns the seed as a value, but can be used without return value.

Returns: value

rseed(12345);
 

round(x, d)

Rounds x (series, val or matrix) to d decimal places. See also int(), floor() and ceiling().

Returns: series/value/matrix

%v1 = round(%v2, 3);

runif()

Returns a random number from a uniform distribution between 0 and 1. See also rseed() and rnorm().

Returns: value

%= runif();

seq(start, end)

Returns a list of integer values or dates between start and end (both included). Start and end must be two values or two dates.

Returns: list

#= seq(1, 100);
#= seq(2001q1, 2005q4);

sqrt(x)

Returns the square root of x (series, value or matrix).

Returns: series/value/matrix

= sqrt(x);
%v1 = sqrt(%v2);

sum(x1, x2, ...)

sum(list, x)

Returns the sum of x1, x2, ... etc. The input parameters may be series or value.

If the first argument is a list name (or a list of list names), the sum function will sum the second argument over these lists.

Returns: series/value

= sum(x1, x2, x3);
%= sum(%v1, %v2, %v3);

 

= sum(#j, x[a, #j]);
= sum((#i, #j), x[#i, #j]);
= sum(#j, xa{#j});
= sum((#i, #j), x{#i}{#j});

 

To sum a simple list #j of series names, you may use this:

 

= sum({#j}); //shorter than sum(#j, {#j})

 

Note that for PRT/PLOT etc., you should use the more explicit PRT sum(#j, {#j}); because PRT/PLOT auto-unfolds 'uncontrolled' lists into columns/lines.

sumt(x)

sumt(<t1 t2>, x)

Returns the time-sum of the observations of the timeseries x over the local/global time period (or over t1 to t2, if indicated)

Returns: series

= sumt(x);
= sumt(<2020 2025>, x);
= x.sumt(<2020 2025>);  //same as above

 

 

Conversions

 

Function name

Description

Examples

date(x)

Tries to convert the scalar x to date type. See also under "date combining functions".

Returns: date

%= date(2000+15);
Result: %= 2015.

dates(x)

Tries to convert each element of the list x into a date.

Returns: list

#m1 = (2001, 2002, 2003);
#m2 = dates(#m1);  //or: #m1.dates()

data(x)

Converts a string x containing blank-separated numbers to a list of values.

Returns: list of values

#= data('1 2 3');
= data('1 2 3');

format(x, code)

Formats the value/date/string x by means of the formatting code. The formatting code is as follows for values:

 

'[width]:[format]'  //note: no blanks

 

The width specifies that the string will be at least [width] characters wide. The [format] follows the conventions shown here or here, so you may either use a pattern like 0.000 or 0.### (exactly three digits or at most three digits), or you may use a description like F3 (floating point, three digits). So, 12:0.000 or 12:F3 both a 12 characters wide field, and a number with three decimals.

 

If the [width] is positive, the number is right-aligned within the field, and if it is negative, it is left-aligned.

 

You may also format strings or dates: in that case only the [width] is used (positive or negative). In this way, table-like alignment is quite straightforward.

 

See also OPTION string interpolate format val = ... ; to set rules regarding {...} format in strings.

Returns a string.

%= 12.3456;

%= 2020q1;
%= 'abc';
 
tell;
tell '123456789012' + '|';
tell '------------' + '|';
tell format(%v, '0.000') + '|';
tell format(%v, '12:0.000') + '|';

tell format(%d, '12') + '|';
tell format(%s, '12') + '|';
tell format(%v, '-12:0.000') + '|';

tell format(%d, '-12') + '|';
tell format(%s, '-12') + '|';
tell '------------' + '|';
 
// 123456789012|
// ------------|
// 12.346|
//       12.346|

//       2020q1|
//          abc|
// 12.346      |

// 2020q1      |
// abc         |
// ------------|

string(x)

Tries to convert the scalar x to string type. See also under "string combining functions".

If x is a list of strings, the string() function returns a comma-separated list of strings.

Returns: string

%= string(12) + string(34);
Result: %= '1234'.

strings(x)

Tries to convert each element of the list x into a string.

Returns: list

#m1 = (1, 2, 3);
#m2 = strings(#m1); //or: #m1.strings()

val(x)

Tries to convert the scalar x to value type.

Returns: value

%= val('12' + '34');
Result: %= 1234.

vals(x)

Tries to convert each element of the list x into a value.

Returns: list

#m1 = ('1', '2', '3');
#m2 = vals(#m1);  //or: #m1.vals()

 

Date combining functions

 

Function name

Description

Examples

date(d, f, opt)

Converts the date d into a new date with frequency f (string), and option opt (string). The option can be 'start' or 'end'.

 

When converting from a higher frequency to a lower frequency, the result does not depend upon the option opt.

 

Returns: date

%= 2020q2;
PRT %d.date('m', 'start');  //2020m4
PRT %d.date('m', 'end');  //2020m6
PRT %d.date('a', 'start');  //2020
PRT %d.date('a', 'end');  //2020

date(y, f, sub)

date(y, 'm', m, 'd', d)

Constructs a new quarterly or monthly date from y (integer), frequency (string), and subperiod (integer). You may also construct a daily date with a similar syntax.

 

Note: you may also use date(x), where x can be a value or a string, and Gekko will try to convert the argument into a date.

 

Returns: date

%= date(2020, 'q', 2);  //2020q2
%= date(2020, 'm', 12, 'd', 24);  //2020m12d24

fromExcelDate(v)

Converts an Excel date (the val v, counting the number of days since January 1, 1900) to a date with daily frequency.

 

Returns: date with daily frequency

See examples regarding the toExcelDate() function.

getFreq(d)

Extracts the frequency of a date

Returns: string

%= 2020q2;
PRT %d.getfreq();  //'q'

getDay(d)

Extracts the day number from a date. Will fail if the date is not daily.

Returns: val

%= 2020m3d25;
PRT %d.getday(); //25

getMonth(d)

Extracts the month number from a date. More specific than getSubPer(), and will fail if the date is not monthly or daily.

Returns: val

%= 2020m2;
PRT %d.getmonth();  //2

getQuarter(d)

Extracts the quarter number from a date. More specific than getSubPer(), and will fail if the date is not quarterly.

Returns: val

%= 2020q2;
PRT %d.getquarter();  //2

getSubPer(d)

Extracts the sub-period from a date (1 if annual or undated, the quarter if quarterly, and the month if monthly or daily).

Returns: val

%= 2020q2;
PRT %d.getsubper();  //2

getYear(d)

Extracts the year from a date.

Returns: val

%= 2020q2;
PRT %d.getyear();  //2020

max(d1, d2, ... )

Finds the largest of any number of dates. (max() can also be used with value arguments).

Returns: date

[New in 3.1.6]

PRT max(2002q1, 2001q4);

min(d1, d2, ... )

Finds the smallest of any number of dates. (min() can also be used with value arguments).

Returns: date

[New in 3.1.6]

PRT min(2002q1, 2001q4);

toExcelDate(d)

Converts a daily date into an Excel date (counting the number of days since January 1, 1900). See also fromExcelDate(). Excel dates can be subtracted to obtain day spans. [New in 3.0.7]

 

Returns: val.

%v1 = toExcelDate(2019m11d12);
%v2 = toExcelDate(2019m12d3);
PRT %v1, %v2; //43781 and 43802
PRT %v2 - %v1; //21 days (span)
%= fromExcelDate(%v1 + 100);
PRT %d; //100 days from 2019m11d12

truncate(d1, d2)

Finds overlap between two different time periods. The period d1 to d2 is compared with the global time period (if no local period is indicated), or with the local time period (if such a period is indicated in the <...> fields). Use a local time period if you need to find the overlap between two arbitrary time windows.

 

Returns: a list of two elements, start and end date of the resulting period. If the two elements are both null, there is no overlap.

 

[New in 3.1.6]

TIME 2010 2020;
#= truncate(2000, 2030);  //(2010, 2020)
#= truncate(2000, 2015);  //(2010, 2015)
#= truncate(2000, 2005);  //(null, null)
TIME 1980 1990;
#= truncate(<2010 2020>, 2000, 2030);  //(2010, 2020)
#= truncate(<2010 2020>, 2000, 2015);  //(2010, 2015)
#= truncate(<2010 2020>, 2000, 2005);  //(null, null)

//

// The overlapping period (z) can be visualized as

// the overlap of these time windows/periods:     

//                                                

// period1    . x x x x x . . .                   

// period2    . . . y y y y y .                   

// truncate() . . . z z z . . .                   

 

 

 

String combining functions

 

Function name

Description

Examples

[x]-index

Index: returns the character at position x.

Returns: string

%= 'abcd';
PRT %s[2];  //'b'

[x1..x2]-index

Index: returns the range of characters from position x1 to x2 (both inclusive). You may omit x1 or x2.

Returns: string

%= 'abcd';
PRT %s[2..3];  //'bc'

concat(s1, s2)

Appends the two strings: same as s1 + s2.

Returns: string

%= concat('He', 'llo'); Result: 'Hello'.

endswith(s1, s2)

 

Returns 1 if the string s1 starts with the string s2, else 0. The comparison is case-insensitive.

Returns: val

%= endswith('abcde', 'cde');
Returns: 1

index(s1, s2)

Searches for the first occurrence of string s2 in string s1 and returns the position. It returns 0 if the string is not found. The search is case-insensitive

Returns: val

%= index('onetwothreetwo', 'two'); 

Returns: 4. 
%= index('oneTWO', 'two'); 

Returns: 4.

isAlpha(s)

Returns 1 if all the characters are letters (alphabet). [New in 3.0.5].

%= isAlpha('aBc');
Returns: 1

isLower(s)

Returns 1 if the string contains no uppercase characters. [New in 3.0.5].

%= isLower('abc12');
Returns: 1

isNumeric(s)

Returns 1 if all the characters are of numeric value. [New in 3.0.5].

%= isNumeric('123');
Returns: 1

isUpper(s)

Returns 1 if the string contains no lowercase characters. [New in 3.0.5].

%= isUpper('ABC12');
Returns: 1

length(s)

 

 

The length of the string (number of characters). You may use len() instead of  length().

Returns: val

%= %s.length();

lower(s)

The string in lower-case letters.

Returns: string

%= lower('aBcD'); 

Result: 'abcd'.

prefix(s1, s2)

If s1 is a string, it has the string s2 prefixed (prepended).

Returns: string

%s1 = %s2.prefix('a');

replace(s1, s2, s3)

replace(s1, s2, s3, max)

In the string s1, the function replaces all occurrences of s2 with s3. Replacement is case-insensitive.

 

If max > 0, the replacement is performed at most max times.

 

Returns: string

%= replace(%s1, %s2); 

//or: replace(%s, %s1, %s2)

split(s1, s2)

split(s1, s2, removeempty, strip)

Splits the string s1 by means of the delimiter s2. Empty elements are removed per default, and the resulting strings are stripped (blanks are removed from the start and end of the strings). The last two options are 1, 1 per default (set to 0 or 1), see examples. [New in 3.0.6]

%= 'a, b,c,,d, , e';
#m1 = %s.split(','); 
//--> ('a', 'b', 'c', 'd', 'e')
#m2 = %s.split(',', 1, 1); 
//--> ('a', 'b', 'c', 'd', 'e');
#m3 = %s.split(',', 0, 1);'); 
//--> ('a', 'b', 'c', '', 'd', '', 'e')
#m4 = %s.split(',', 1, 0);'); 
//--> ('a', ' b', 'c',  'd', ' ', ' e')
#m5 = %s.split(',', 0, 0);'); 
//--> ('a', ' b', 'c', '', 'd', ' ', ' e')

 

startswith(s1, s2)

Returns 1 if the string s1 starts with the string s2, else 0. The comparison is case-insensitive.

Returns: val

%= 'abcde';
%= s%.startswith('abc');
Returns: 1

strip(s)

Removes blank characters from the start and end of the string.

Returns: string

%s1 = %s2.strip();  //or: strip(%s1)

stripstart(s)

Removes blank characters from the start of the string.

Returns: string

%s1 = %s2.striptart();  //or: stripstart(%s1, %s2)

stripend(s)

Removes blank characters from the end of the string.

Returns: string

%s1 = %s2.stripend();  //or: stripend(%s1, %s2)

substring(s, start, length)

The piece of the string between character number start and length (these must be integer values).

 

You can alternatively use a 'slice', using []-notation, see example.

 

Returns: string

%= %s1.substring(3, 2);  

//or: substring(%s1, 3, 2)
%= %s1[.. 5];  

//a slice from pos 3 to 5 (both inclusive)

suffix(s1, s2)

If s1 is a string, it has the string s2 suffixed (appended)

Returns: string

%s1 = %s2.suffix('a');

upper(s)

The string with upper-case letters.

Returns: string

%= upper('aBcD'); Result: 'ABCD'.

 

 

 

List functions:

 

Note that some of the functions assume that the lists are lists of strings. This will be fixed regarding values and dates.

 

Function name

Description

Examples

[x]-index

Index: picks out a single element. In contrast to R, this does not return a 1-element list containing the variable. If you need that, use for instance #m[3..3].

Returns: var

#m[3];  //the third element

[x1..x2]-index

Index: picks out a range of elements. You may omit x1 or x2.

Returns: list

#m[3..5];  //the third to fifth elements

[x1, x2]-index

For a nested list of lists, #m[3, 5] will return the same element as #m[3][5], so this is just convenience to make a nested list accessible like a matrix. See more here.

Returns: variable

 

[New in 3.0.6].

#= ((1, 2), (3, 4));
PRT #m[2, 1], #m[2][1];  //same

[x1..y1, x2..y2]-index

[x1..y1, x2]-index

[x1, x2..y2]-index

For a nested list of lists, #m[2..3, 2..4] will select the given 'rows" and "columns", corresponding to selecting a submatrix from a matrix. Beware that in general, #m[2..3, 2..4] is completely different from #m[2..3][2..4].  See more here.

Returns: list

[New in 3.0.6].

//  1  2  3
//  4  5  6
//  7  8  9
// 10 11 12
#= ((1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12));
PRT #m[2, 2..3];
PRT #m[2][2..3]; //same as above
PRT #m[2..4, 2]; //matrix-like selection
PRT #m[2..4][2]; //different from above!
PRT #m[2..4, 2..3]; //matrix-like selection
PRT #m[2..4][2..3]; //different from above!

 

 

 

append(x1, x2)

append(x1, i, x2)

Adds variable x2 as it is at the end of list x1. Note that if x2 is a list of for instance 3 items, only 1 element is added (the list itself). If you need to add the 3 elements individually, use extend().

 

If used with i argument, x2 is inserted at index i, instead of at the end. See also extend().

 

To prepend, use append(x1, 1, x2).

 

Returns: list

#= #x1.append(#x2);  //or: append(#x1, #x2)
#= #x1.append(2, #x2);  //insert at position 2

contains(x1, x2)

Checks if the list of strings x1 contains the string x2. Returns 1 if true, 0 otherwise. You may alternatively use x2 in x1, see the last example. See also the count() and index() functions. The comparisons are case-insensitive.

Returns: val

%= #x1.contains(%s);
if(#x1.contains(%s) == 1); tell 'yes'; end;
if(%s in #x1); tell 'yes'; end;

count(x1, x2)

Counts the number of times the string x2 is present in the list of strings x1. See also the contains() and index() functions.

 

 

Note: to obtain the number of elements in a list, use the length() function. The comparisons are case-insensitive.

 

Returns: val

%= #x1.count(%s);  //or: count(#x1, %s)

data(x)

Accepts a string of blank-separated values x and turns them into a list of values. This is handy for long sequences of blank-separated numbers, instead of manually setting the commas.

Returns: list

#= data('1.0  2.0  1.5');

dates(x)

Tries to convert each element of the list x to a date.

Returns: list

#= dates(#x);

except(x1, x2)

The except() function subtracts x2 from x1. You may alternatively use the operator -. Only works for lists of strings. See also intersect() and union().

 

Was called difference() in Gekko 2.0. See also extend().

 

Returns: list

#= #x1.except(#x2);  //or: except(#x1, #x2)
#= #x1 - #x2;  //same
 
#-= #x1;  //subtract from itself

extend(x1, x2)

extend(x1, i, x2)

The arguments x1 and x2 must be lists. The function inserts the elements of list x2 one by one at the end of (or at position i in) the list x1.

 

For two lists x1 and x2, you may alternatively use the + operator. See also except() and append().

 

To pre-extend, use extend(x1, 1, x2).

 

Returns: list

#= #x1.extend(#x2);  //or: extend(#x1, #x2)
#= #x1 + #x2; //same as above
#= #x1.extend(2, #x2);  //insert at position 2
 
#+= #x1; //add to itself

flatten(x)

For at list x, the function returns a flattened version of the list. For instance, the list (1, (2, 3)) is transformed into a non-recursive list of non-list elements: (1, 2, 3).

 

Returns: list

 

#m1 = (1, (2, 3));
#m2 = #m1.flatten(); //or: flatten(#m1).

index(x1, x2)

Returns the index of the first occurrence of the string x2 in the list of strings x1. Returns 0 if x2 is not found in x1. See also the count() and contains() functions. The comparisons are case-insensitive.

Returns: val

%= #x1.index(%s);  //or: index(#x1, %s)

intersect(x1, x2)

The intersect() function finds the common elements of the two list of strings x1 and x2. You may alternatively use the operator &&. Only works for lists of strings. See also except() and union().

Returns: list

#= #x1.intersect(#x2);  //or: intersect(#x1, #x2)
#= #x1 && #x2;

length(x)

Returns the number of elements in the list x. You may use len() instead of length().

Returns: val

%= #x.length();  //or: length(#x).
%= #x.len(); //the same

list(x1, x2, ...)

Returns a list of the variables x1, x2, etc. The function is handy for lists with only 0 or 1 elements. See examples.

Returns: list

#= ();      //will fail
#= list();  //ok: empty list

#= (1, 2);  //easy
#= (1);     //will fail
#= (1,);    //is ok
#= list(1); //is ok

lower(x)

Returns string elements in the list as lower-case.

Returns: list

#= #x1.lower();  //or: lower(#x1)

pop(x1, i)

pop(x1)

Removes the element at position i in the list x1. Removes the last element if called with pop(x).

Returns: list

#= #x1.pop(2);  //or: pop(#x1, 2)
#= #x1.pop();  //last element
#= #x1.pop(1);  //first element

preextend(x1, x2)

Same as extend(x1, 1, x2), putting the elements of x2 in the first position of x1.

#= #x1.preextend(#x2);  //insert at position 1

prefix(x1, x2)

If x1 is a list of strings, each element has the string x2 prefixed (prepended)

Returns: list

#= #x1.prefix(%s);  //or: prefix(#x1, %s);

prepend(x1, x2)

Same as append(x1, 1, x2), putting x2 in the first position of x1.

#= #x1.prepend(#x2);  //insert at position 1

sort(x)

Returns a sorted list of strings, provided that x is a list of strings. Sorting is case-insensitive.

Returns: list

#= #x.sort();  //or: sort(#x)

remove(x1, x2)

Removes any string x2 from the list of strings x1. See also the except() function.

Returns: list

#= #x1.remove(%s);  //or: remove(#x1, %s);

replace(x1, x2, x3)

replaceinside(x1, x2, x3)

replaceinside(x1, x2, x3, max)

replace(): In the list of strings x1, if this string element is the same as x2, x3 is inserted instead.

 

replaceinside(): the string element has any occurences of x2 inside the string replaced with x3. The replacements may be limited via the max argument.

 

Returns: list

#= #x1.replace(%x2, %x3); //or: replace(#x1, %x2, %x3)
 
#= #x1.replaceinside(%x2, %x3); //or: replace(#x1, %x2, %x3, 'inside')

reverse(x)

To be done


split(x, s)

To be done


strings(x)

Tries to convert each element of the list x to a string

Returns: list

#= strings(#x);

suffix(x1, x2)

If x1 is a list of strings, each element has the string x2 suffixed (appended)

Returns: list

#= #x1.suffix(%s);  //or: suffix(#x1, %s);

t(x)

For a nested list of lists, the t() function returns the transpose, similar to transposing a matrix. [New in 3.0.6].

Returns: list (of lists)

#= ((1, 2), (3, 4));
#m, t(#m);

union(x1, x2)

The union() function adds the two lists (only adds unique elements in x2 that are not in x1), or you may use the operator ||. Alternatively, you may use + y, but that may introduce dublets. Only works for lists of strings. See also except() and intersect().

Returns: list

#= #x1.union(#x2);  //or: union(#x1, #x2)
#= #x1 || #x2;

unique(x1)

Retains only those elements of list x1 that are unique (list of strings only).

Returns: list

#= #x1.unique();  //or: unique(#x1)

upper(x)

Returns string elements in the list as upper-case.

Returns: list

#= #x1.upper();  //or: upper(#x1)

vals(x)

Tries to convert each element of the list x to a value

Returns: list

#= vals(#x);

 

 

 

 

Bank/name/frequency/index manipulations

 

Function name

Description

Examples

addBank(x, bank)

If x does not have a bankname, a bankname is added. The input x may be string or list.

Returns: string or list

%name = addBank('x!q', 'b2');
Result: 'b2:x!q'

addFreq(x, freq)

If x does not have a freq, a freq is added. The input x may be string or list.

Returns: string or list

%name = addFreq('x', 'q');
Result: 'x!q'

getBank(x)

Returns the bank part of x. The input x may be series, string or list.

Returns: string or list

%bank = getBank('b2:x!q');
Result: 'b2'

getFreq(x)

Returns the freq part of x. The input x may be series, string or list.

Returns: string or list

%bank = getFreq('b2:x!q');
Result: 'q'

getFullName(bank, name, freq)

Returns the full name corresponding to the input, where bank, name and freq are strings.

Returns: string

%name = getFullName('b2', 'x', 'q');
Result: 'b2:x!q'

getFullName(bank, name, freq, index)

Returns the full name corresponding to the input, where bank, name and freq are strings, and index is a list (of strings)

Returns: string

%name = getFullName('b2', 'x', 'q', ('a', 'b'));
Result: 'b2:x!q[a,b]'

getIndex(x)

Returns the index part of x. The input x may be string or list.

Returns: list

#index = getIndex('b2:x!q[a, b]');
Result: ('a', 'b')
If the input is a list, the output will be a list of lists.

getName(x)

Returns the name part of x. The input x may be series, string or list.

Returns: string or list

%name = getName('b2:x!q');
Result: 'x'

getNameAndFreq(x)

Returns the name part of x. The input x may be series, string or list.

Returns: string or list

%name = getNameAndFreq('b2:x!q');
Result: 'x!q'

removeBank(x)

Removes any bank in x. The input x may be string or list.

Returns: string or list

%name = removeBank('b2:x!q');
Result: 'x!q'

removeBank(x, bank)

Removes any banks in x with the indicated bankname. The input x may be string or list.

Returns: string or list

%name = removeBank('b2:x!q', 'b2');
Result: 'x!q'
%name = removeBank('b3:x!q', 'b2');
Result: 'b2:x!q'

removeFreq(x)

Removes any freq in x. The input x may be string or list.

Returns: string or list

%name = removeFreq('b2:x!q');
Result: 'b2:x'

removeFreq(x, freq)

Removes any freq in x with the indicated freqname. The input x may be string or list.

Returns: string or list

%name = removeFreq('b2:x!q', 'q');
Result: 'b2:x'
%name = removeFreq('b3:x!q', 'm');
Result: 'b2:x!q'

removeIndex(x)

Removes any index in x. The input x may be string or list.

Returns: string or list

%name = removeIndex('b2:x!q[a, b]');
Result: 'b2:x!q'

replaceBank(x, b1, b2)

Replaces any banks in x having name b1 with name b2. The input x may be string or list.

Returns: string or list

%name = replaceBank('b2:x!q', 'b2', 'b3');
Result: 'b3:x!q'
%name = replaceBank('b2:x!q', 'b3', 'b4');
Result: 'b2:x!q'

replaceFreq(x, f1, f2)

Replaces any freq in x having freq b1 with freq b2. The input x may be string or list.

Returns: string or list

%name = replaceFreq('b2:x!q', 'q', 'm');
Result: 'b3:x!m'
%name = replaceFreq('b2:x!q', 'm', 'a');
Result: 'b3:x!q'

setBank(x, bank)

The indicated bankname is set, even if it exists already. The input x may be string or list.

Returns: string or list

%name = setBank('b3:x!q', 'b2');
Result: 'b2:x!q'

setFreq(x, freq)

The indicated freq is set, even if it exists already. The input x may be string or list.

Returns: string or list

%name = setFreq('b2:x!q', 'm');
Result: 'b2:x1!m'

setName(x, name)

The indicated name is set. The input x may be string or list.

Returns: string or list

%name = setName('b2:x!q', 'y');
Result: 'b2:y!m'

setNamePrefix(x, p)

The name of x has prefix p added.The input x may be string or list.

Returns: string or list

%name = setNamePrefix('b2:x!q', 'a');
Result: 'b2:ax!m'

setNameSuffix(x, s)

The name of x has suffix s added.The input x may be string or list.

Returns: string or list

%name = setNameSuffix('b2:x!q', 'b');
Result: 'b2:xb!m'

 

 

Timeseries functions

 

Function name

Description

Examples

getdomains(x)

Returns a list of strings containing the domains for each dimension of the array-series x. Returns an empty list if there are no domains given.

Returns: list

#= getdomains(x); //or: #d = x.getdomains();

hpfilter(x, lambda)

hpfilter(<t1 t2>, lambda)

hpfilter(x, lambda, log)

hpfilter(<t1 t2> x, lambda, log)

Returns a HP-filtered version of series x. Lambda is normally 6.25 for annual, 1600 for quarterly, and 129600 for monthly series. An additional argument 0 or 1 may be added (1 if log-transforms are to be used inside the calculation). Time period may be indicated with t1-t2.

Returns: series

= hpfilter(x, 6.25);
= hpfilter(x, 6.25, 1);  //log-transforms
= hpfilter(<1970 2015>, x, 6.25);
= x.hpfilter(<1970 2015>, 6.25); //alternative syntax

laspchain(plist, qlist, t)

laspchain(<t1 t2>, plist, qlist, t)

Laspeyres chain index. Calculates a map containing two series p and q (price and quantity) from a list of prices  and a corresponding list of quantities, setting p = 1 in period t (t is a date). See also the bottom of the LIST help page. A period can be indicated in the <t1 t2> field.

Returns: map

#= p1, p2;  //prices
#= q1, q2;  //quantities
#= laspchain(#p, #x, 2000);  //#m is a map
PRT #m.p, #m.q;
 
Or in one command (only the quantity printed):
PRT laspchain(('p1', 'p2'), ('q1', 'q2'), 2000).q;
 
#= laspchain(<1980 2020>, #p, #x, 2000);  //with period

laspfixed(plist, qlist, t)

laspfixed(<t1 t2>, plist, qlist, t)

Laspeyres fixed-price index. As laspchain(), but with fixed prices.

Returns: map

//See example regarding laspchain()

percentile(x, %v)

Computes the %v percentile for the series x, for the global time period. Any missing values within that sample are ignored. Setting %v = 0.5 results in the median.

Returns: val

%= percentile(y, 0.25);
%= percentile(y, 0.50);

replace(x, v1, v2)

For the series x, the function replaces the value v1 with the value v2, over the given sample.

 

See also iif(), isMiss(), and the $-conditional.

 

Returns: series

 

TIME 2001 2003;
= (1, m(), 3);  //m() is missing value
//result is (1, 0, 3):
= x.replace(m(), 0);  //or: replace(x, m(), 0)
//the replacement is done for the sample:
<2000 2004> = x.replace(m(), 0);
//result is (0, 1, 0, 3, 0)

rotate(x, d)

Transforms the array-series x to a new array-series, where the time dimension and dimension number d swap places.

For instance, the array-series pop may contain subseries for each age group 0 to 100, that is, pop['0'], pop['1'], ... , pop[100']. These 101 subseries are all defined over a time period, say 2020-2050. Then profile = rotate(pop, 1) will be a new array-series containing subseries for each time period 2020 to 2050, that is, profile['2020'], profile['2021'], ... , profile['2050']. These 31 subseries are all defined over an undated time period 0 to 100, corresponding to the age dimension. Hence, PLOT <0u 100u> profile['2020']; will plot the age profile of the population in the year 2020.

Returns: series

//pop is a 1-dimensional array-series 
//with ages 0-100 in its dimension.
//note: 'u' indicates undated frequency
 
profile!= rotate(pop, 1);
#= ('2020', '2030', '2040', '2050');
plot <0u 100u> profile!u[#t];
 
 
 

series(freq, n)

Constructs a series or array-series of the given frequency and with the given dimensions (n). You can skip some of these options, see examples.

Returns: series

 

= series('q', 3);  //quarterly array-series, 3-dim
= series('q');  //quarterly normal series
= series(3);  //3-dim array-series with current frequency
= series();  //normal series with current frequency
 
= series(1);
y['a'] = 100;  //or: y[a] = ...
 

setdomains(x, d)

Sets a list of strings (d) containing the domains for each dimension.

Returns: nothing

#= ('#b', '#x');
setdomains(x, #d);  //or: x.setdomains(#d);

timeless(freq, v)

Constructs a timeless series of the given frequency, to value v. You can skip some of these options, see examples.

 

In many cases, you can just use a value scalar with the same functionality. But timeless series can be practical, for instance they can be used as array-series.

 

Returns: series

 

= timeless('q', 3);  //quarterly timeless series, with value = 3.
= timeless('q');  //quarterly timeless series, no value set.
= timeless(3);  //timeless series with current frequency, with value = 3.
= timeless();  //timeless series with current frequency, no value set.
 
= series(1);
y['a'] = timeless(100);  //or: y[a] = ...

 

 

Time, databank and timeseries info

 

Function name

Description

Examples

bankfilename(s)

bankfilename(s, p)

Return the filename of the s databank, where s is a string. Can include path.

Returns: string

%s1 = bankfilename('work');
%s1 = bankfilename('work', 'fullpath');  //with path

bankname(s)

Returns the name of the bank. Input can be the string 'first' or 'ref', or a val designating the number in the databank list.

Returns: string

%b1 = bankname('first');
%b0 = bankname('ref');
%b2 = bankname(2);

banktime(s)

Return the time stamp of the s databank, where s is a string.

Returns: string

%s1 = banktime('work');

currentDateTime()

Returns current date and time.

Returns: string

%= currentDateTime(); 
//Returns: '15-09-2014 12:34:58' (for instance).
TELL currentDateTime();

currentDate()

currentDate2()

Returns current date, either as a string, or as a date with daily frequency. [New in 3.1.1]

currentDate() returns: string

currentDate2() returns: date

%= currentDate(); 
//Returns: '15-09-2014' (for instance).
%= currentDate2(); 
//Returns: 2014m9d15 (for instance).

currentDay()

Returns the current day. [New in 3.0.5].

Returns: val

%= currentDay();

currentFolder()

Returns the current working folder (cf. OPTION folder working = ...). [New in 3.0.6].

Returns: string.

%= currentFolder();

currentFreq()

Returns the current frequency, for instance a, q, m, d or u.

Returns: string

%= currentFreq(); 
//Returns: 'a' (depending upon frequency setting, cf. option freq).

currentHour()

Returns the current hour. [New in 3.0.5].

Returns: val

%= currentHour();

currentMinute()

Returns the current minute. [New in 3.0.5].

Returns: val

%= currentMinute();

currentMonth()

Returns the current month. [New in 3.0.5].

Returns: val

%= currentMonth();

currentPerStart()

Returns the start of the global time period.

Returns: date

%= currentPerStart(); 
//Returns: 2012q1 (for instance).

currentPerEnd()

Returns the end of the global time period.

Returns: date

%= currentPerStart(); 
//Returns: 2015q4 (for instance).

currentSecond()

Returns the current second. [New in 3.0.5].

Returns: val

%= currentSecond();

currentTime()

Returns current time.

Returns: string

%= currentTime(); 
//Returns: '12:34:58' (for instance).

currentYear()

Returns the current year. [New in 3.0.5].

Returns: val

%v = currentYear(); 

exist(x)

Returns 1 if the variable x exists, else 0. The variable name must be a string. For timeseries, you do not have to add frequency to the name (for instance !q), if the series is of current frequency. The function respects the option databank search setting (that is, in sim-mode it will only look in the first-position databank, if a databank name is not provided).

 

Returns: val

%v = exist('gdp');
%v = exist('db2:gdp');

filteredperiods(d1, d2)

Returns the number of filtered periods between d1 and d2 (these are dates).

Returns: val

%v = filteredperiods(%d1, %d2);

fromSeries(x, type)

Accesses meta-information from the timeseries. Type can be

 

'name'

'bank'

'freq'

'label'

'source'

'units'

'stamp'

'dataStart' or 'dataEnd' (period with actual data)

'dataStartTruncate' or 'dataEndTruncate' (period with actual data, truncated with global or local time period). May return null/empty. [New in 3.1.6]

 

NOTE: The x argument must be a series (without quotes).

 

Returns: string or date

%= ref:gdp.fromSeries('label'); 
//Returns 'Gross domestic product' (for instance).
%= gdp.fromSeries('dataStart'); 
//Returns 1980q1 (for instance). Same logic regarding 'dataEnd' argument.
%= gdp.fromSeries('freq'); 
//Returns 'q' (for instance).
 
TIME 2011 2015;
= 1, 2, 3, 4, 5;
TIME 2013 2017;
PRT x.fromSeries('dataStartTruncate'); //2013
TIME 2011 2015;
PRT x.fromSeries(<2013 2017>, 'dataStartTruncate'); //2013

 

gekkoVersion()

Returns the Gekko version number (xx.yy.zz).

Returns: string

%= gekkoVersion(); 
//Returns: '3.0.1' (for instance).

getEndoExo()

Returns a list with names of those variables that start with 'endo_' or 'exo_'. This is used with GAMS models, when fixing equations.

Returns: list of strings.

#= getEndoExo();

isOpen(x)

Returns 1 if the databank with the name x (a string) is open, and 0 otherwise.

Returns: val

 

%= isopen('mybank');

time()

time(<t1 t2>)

Returns the current time period as a series where the dates are represented as values. Works with quarters and months, too. The function may for instance be practical for creating trend variables.

Returns: series

 

option freq q;
time 2010q1 2011q4;
p time();
p time(<2010q3 2011q3);  //truncated
//the first one prints 2010.125, 2010.375, 2010.625, 2010.875, ...

 

Matrix functions:

 

Function name

Description

Examples

avgc(x)

Average over cols.

Returns: matrix

#m2 = avgc(#m1);

avgr(x)

Average over rows

Returns: matrix

#m2 = avgr(#m1);

chol(x)

chol(x, type)

Cholesky decomposition of matrix x. Accepts type (string), either 'upper' or 'lower'.

Returns: matrix

#m2 = chol(#m1, 'upper');

cols(x)

Returns the number of colums of x

Returns: val

%= cols(#m);

det(x)

Determinant of a matrix.

Returns: val

%= det(#m);

diag(x)

Diagonal. If x is a n x n symmetric matrix, the method returns the diagonal as a n x 1 matrix. If x is a n x 1 column vector, the method returns a n x n matrix with this column vector on the diagonal (and zeroes elsewhere).

Returns: matrix

#m2 = diag(#m1);

divide(x1, x2)

Element by element division of the two matrices. If x2 is a row vector, each x1 column will be divided with the corresponding value from the row vector.  And if x2 is a column vector, each x1 row will be divided with the corresponding value from the column vector.

Returns: matrix

#= divide(#x1, #x2);

i(n)

Returns a n x n identity matrix.

Returns: matrix

#= i(10);

inv(x)

Inverse of matrix x

Returns: matrix

#m2 = inv(#m1);

maxc(x)

Max over cols

Returns: matrix

#m2 = maxc(#m1);

maxr(x)

Max over rows

Returns: matrix

#m2 = maxr(#m1);

minc(x)

Min over cols

Returns: matrix

#m2 = minc(#m1);

minr(x)

Min over rows

Returns: matrix

#m2 = minr(#m1);

m(r, c) or miss(r, c)

Returns a n x k matrix filled with missing values. Cf. also m() function for values.

Returns: matrix

#= m(5, 10);

multiply(x1, x2)

Element by element multiplication of the two matrices. If x2 is a row vector, each x1 column will be multiplied with the corresponding value from the row vector.  And if x2 is a column vector, each x1 row will be multiplied with the corresponding value from the column vector.

Returns: matrix

#= multiply(#x1, #x2);

ones(n, k)

Returns a n x k matrix filled with 1's

Returns: matrix

#= ones(5, 10);

pack(v1, v2, ...)

pack(<t1 t2>, v1, v2, ...)

Using period t1-t2, the timeseries v1, v2, ... are packed into a n x k matrix, where n is the number of observations and k is the number of variables. If the period is omitted, the global time period is used.

Returns: matrix

#= pack(<2020 2030>, x, y, z); Returns: a 11 x 3 matrix #m with the values.

rows(x)

Returns the number of rows of x.

Returns: val

%= rows(#m);

sumc(x)

Sum over cols

Returns: matrix

#m2 = sumc(#m1);

sumr(x)

Sum over rows

Returns: matrix

#m2 = sumr(#m1);

t(x)

Returns the transpose of a matrix.

Returns: matrix

#m2 = t(#m1);

trace(x)

Returns the trace of a matrix.

Returns: val

%= trace(#m);

unpack(m)

unpack(<t1 t2>, m)

The column matrix m (with only one column) is unpacked into a timeseries spanning the period t1-t2. If the period is omitted, the local/global time period is used.

The unpack() function is not strictly necessary: you may alternatively assign a nx1 matrix directly to a series (see example).

Returns: series

//This picks out the second column of #m (and all the rows).

= #m[.., 2].unpack(<2020 2030>);  
<2020 2030> = #m[.., 2].unpack();  //same
<2020 2030> = #m[.., 2]; //also works

zeros(n, k)

Returns a n x k matrix filled with 0's. Zeroes() can be used as alias.

Returns: matrix

#= zeros(5, 10);

 

 

 

Miscellaneous functions:

 

Function name

Description

Examples

m() or miss()

Returns a missing value. Useful in some series or matrix  expressions. Cf. also the m(r, c) function for matrices.

Returns: value

<2020 2020> = m();
#= [1, 2; m(), 4];

map()

Returns an empty map.

#= map();

null()

Returns a null variable. At the moment, null variables are mostly used to indicate empty "cells" in lists. You cannot perform calculations on null variables, but you can use the type() function to see the type of a given variable/cell (see example). [New in 3.0.6].

Returns: null variable

#= ((1, 2, 3), (4, null(), 6));
PRT #m;
PRT #m[2, 2].type(); //'null'

readFile(x)

Reads the file x (string) as a string.

See also writeFile().

Returns: string

%= readFile('rawdata.txt');

type(x)

Returns the type of a given variable x. The type is 'val', 'date', 'string', 'series', 'list', 'map', 'matrix' or 'null'. See examples. At the moment, null variables are mostly used to indicate empty "cells" in lists. [New in 3.0.6].

Returns: string

#= (1, 2021, 2021a, 'cat', null());
#m;
#m[1].type(); //'val'
#m[2].type(); //'val'
#m[3].type(); //'date'
#m[4].type(); //'string'
#m[5].type(); //'null'

writeFile(x, s)

Writes the string s to the file x (string). A newline can be indicated with '\n'.

See also readFile().

writeFile('rawdata.txt', '170 121 387);

 

 

Complete alphabetical list of in-built functions:

 

abs()

addbank()

addfreq()

append()

avg()

avgc()

avgr()

avgt()

bankfilename()

bankname()

chol()

cols()

concat()

contains()

count()

currentdate()

currentdatetime()

currentfreq()

currentperend()

currentperstart()

currenttime()

data()

date()

dates()

det()

diag()

dif()

diff()

diffy()

dify()

divide()

dlog()

dlogy()

endswith()

except()

exist()

exp()

extend()

filteredperiods()

flatten()

format()

fromseries()

gekkoversion()

getbank()

getdomains()

getendoexo()

getfreq()

getfullname()

getindex()

getmonth()

getname()

getnameandfreq()

getquarter()

getsubper()

getyear()

hpfilter()

i()

iif()

index()

intersect()

inv()

ismiss()

isopen()

lag()

laspchain()

laspfixed()

len()

length()

list()

log()

lower()

m()

map()

max()

maxc()

maxr()

min()

minc()

minr()

miss()

movavg()

movsum()

multiply()

null()

ones()

pack()

pch()

pchy()

percentile()

pop()

pow()

power()

preextend()

prefix()

prepend()

readfile()

remove()

removebank()

removefreq()

removeindex()

replace()

replacebank()

replacefreq()

replaceinside()

rnorm()

rotate()

round()

rows()

rseed()

runif()

seq()

series()

setbank()

setdomains()

setfreq()

setname()

setnameprefix()

setnamesuffix()

sort()

sqrt()

startswith()

string()

strings()

strip()

stripend()

stripstart()

substring()

suffix()

sum()

sumc()

sumr()

sumt()

t()

time()

timeless()

trace()

truncate()

type()

union()

unique()

unpack()

upper()

val()

vals()

writefile()

zeroes()

zeros()