-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwq_operators_cleaned.json.bak
More file actions
308 lines (308 loc) · 62.6 KB
/
Copy pathwq_operators_cleaned.json.bak
File metadata and controls
308 lines (308 loc) · 62.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
[
{
"operator_syntax": "abs(x)",
"level": "base",
"summary": "Returns the absolute value of a number, removing any negative sign.",
"detailed_explanation": "The absolute value is often used to ensure that only the size of a value is considered, not its direction.\n\nExamples:\n\nabs(close - open)\n\nThis expression will output the absolute difference of the daily price change"
},
{
"operator_syntax": "add(x, y, filter = false), x + y",
"level": "base",
"summary": "Adds two or more inputs element wise. Set filter=true to treat NaNs as 0 before summing.",
"detailed_explanation": "The add operator performs element-wise addition on two or more inputs. If the optional filter parameter is set to true, any NaN values in the inputs are treated as zero before the addition.\n\nExample calculations\n\nSuppose you have two vectors:\n\nx = [1, NaN, 3]\ny = [4, 5, NaN]\nadd(x, y) returns [1+4, NaN+5, 3+NaN] = [5, NaN, NaN]\nadd(x, y, filter=true) returns [1+4, 0+5, 3+0] = [5, 5, 3]\n\nTips\n\nUse filter=true to treat NaNs as zeros. This can improve coverage and performance without the need to backfill the data."
},
{
"operator_syntax": "densify(x)",
"level": "base",
"summary": "Converts a grouping field of many buckets into lesser number of only available buckets so as to make working with grouping fields computationally efficient",
"detailed_explanation": "This operator converts a grouping field with many buckets into a lesser number of only the available buckets, making working with grouping fields computationally efficient. The example below will clarify the implementation.\n\nExample:\n\nSay a grouping field is provided as an integer (e.g., industry: tech -> 0, airspace -> 1, ...) and for a certain date, we have instruments with grouping field values among {0, 1, 2, 99}. Instead of creating 100 buckets and keeping 96 of them empty, it is better to just create 4 buckets with values {0, 1, 2, 3}. So, if the number of unique values in x is n, densify maps those values between 0 and (n-1). The order of magnitude need not be preserved.\n\ndivide(x, y), x / y\nbase\nx / y\ninverse(x)\nbase\n1 / x"
},
{
"operator_syntax": "log(x)",
"level": "base",
"summary": "Calculates the natural logarithm of the input value. Commonly used to transform data that has positive values.",
"detailed_explanation": "The log(x) operator computes the natural logarithm (base e) of the input x. This transformation is widely used in finance to normalize data, reduce skewness, or convert multiplicative relationships into additive ones. The input x should be positive, as the logarithm is undefined for zero or negative values.\n\nIf x = 10, then log(10) ≈ 2.3026\nIf x = 1, then log(1) = 0\nIf x = 0.5, then log(0.5) ≈ -0.6931"
},
{
"operator_syntax": "max(x, y, ..)",
"level": "base",
"summary": "Maximum value of all inputs. At least 2 inputs are required",
"detailed_explanation": "Example:\n\n1\nmax (close, vwap)\nOpen example alpha in Simulate\nSimulation Settings\nRegion\tUniverse\tLanguage\tDecay\tDelay\tTruncation\tNeutralization\tPasteurization\tNaN Handling\tUnit Handling\tMax Trade\tMax Position\nUSA\tTOP3000\tFast Expression\t2\t1\t0.01\tIndustry\tOn\tOff\tVerify\tOFF\tOFF"
},
{
"operator_syntax": "min(x, y ..)",
"level": "base",
"summary": "Minimum value of all inputs. At least 2 inputs are required",
"detailed_explanation": "Example:\n\n1\nmin(close, vwap)\nOpen example alpha in Simulate\nSimulation Settings\nRegion\tUniverse\tLanguage\tDecay\tDelay\tTruncation\tNeutralization\tPasteurization\tNaN Handling\tUnit Handling\tMax Trade\tMax Position\nUSA\tTOP3000\tFast Expression\t3\t1\t0.01\tIndustry\tOn\tOff\tVerify\tOFF\tOFF"
},
{
"operator_syntax": "multiply(x ,y, ... , filter=false), x * y",
"level": "base",
"summary": "Multiplies two or more inputs element wise. Set filter=true to treat NaNs as 0 before multiplication",
"detailed_explanation": "Computes the product of all inputs. You can pass any number of scalars or series: multiply(a, b, c) = a × b × c. When filter=true, NaNs are replaced with 1 before the product; when false, any NaN propagates to the result.\n\nExample calculations:\n\nmultiply(2, 3) = 6\nmultiply(2, 3, 4) = 24\nmultiply(5, NaN, filter=false) = NaN\n\nmultiply(5, NaN, filter=true) = 5 × 1 = 5\n\nAlpha Examples:\n\n1\nmultiply(rank(-returns), rank(volume/adv20), filter=true)\nOpen example alpha in Simulate\nSimulation Settings\nRegion\tUniverse\tLanguage\tDecay\tDelay\tTruncation\tNeutralization\tPasteurization\tNaN Handling\tUnit Handling\tMax Trade\tMax Position\nUSA\tTOP3000\tFast Expression\t3\t1\t0.01\tIndustry\tOn\tOff\tVerify\tOFF\tOFF"
},
{
"operator_syntax": "power(x, y)",
"level": "base",
"summary": "x ^ y",
"detailed_explanation": "1\npower (returns, volume/adv20); power (returns, volume/adv20, precise=true)\nOpen example alpha in Simulate\nSimulation Settings\nRegion\tUniverse\tLanguage\tDecay\tDelay\tTruncation\tNeutralization\tPasteurization\tNaN Handling\tUnit Handling\tMax Trade\tMax Position\nUSA\tTOP3000\tFast Expression\t3\t1\t0.01\tIndustry\tOn\tOff\tVerify\tOFF\tOFF\n\npower (x, y) operator can be used to implement popular mathematical functions. For example, sigmoid(close) can be implemented using power(x) as:\n\n1\n1/(1+ power(2.7182, -close)\nOpen example alpha in Simulate\nSimulation Settings\nRegion\tUniverse\tLanguage\tDecay\tDelay\tTruncation\tNeutralization\tPasteurization\tNaN Handling\tUnit Handling\tMax Trade\tMax Position\nUSA\tTOP3000\tFast Expression\t1\t1\t1\tMarket\tOn\tOff\tVerify\tOFF\tOFF\nreverse(x)\nbase\n - x"
},
{
"operator_syntax": "sign(x)",
"level": "base",
"summary": "Returns the sign of a number: +1 for positive, -1 for negative, and 0 for zero. If the input is NaN, returns NaN. Input: Value of 7 instruments at day t: (2, -3, 5, 6, 3, NaN, -10) Output: (1, -1, 1, 1, 1, NaN, -1)",
"detailed_explanation": "The sign(x) operator determines whether a value is positive, negative, or zero. It is commonly used to quickly identify the direction of a value. If the input is not a number (NaN), the result will also be NaN.\n\nExample calculations\n\nsign(5) returns 1\nsign(-3.2) returns -1\nsign(0) returns 0\nsign(NaN) returns NaN\n\nExamples\n\nsign(close - open)\n\nThis expression returns:\n1 if the closing price is higher than the opening price,\n-1 if the closing price is lower,\n\n0 if they are equal.\n\nsigned_power(x, y)\nbase\nx raised to the power of y such that final result preserves sign of x\nShow more"
},
{
"operator_syntax": "sqrt(x)",
"level": "base",
"summary": "Returns the non negative square root of x. Equivalent to power(x, 0.5); for signed roots use signed_power(x, 0.5).",
"detailed_explanation": "sqrt(x) = power(x, 0.5) for x ≥ 0. It reduces skew and compresses large positive values while keeping order. It returns NaN for x < 0. If you need a root‑like transform that keeps the sign for negative inputs, use signed_power(x, 0.5), which computes sign(x)*sqrt(abs(x)).\n\nExample calculations\n\nsqrt(9) = 3\nsqrt(0.25) = 0.5\nsqrt(0) = 0\n\nsqrt(-4) = NaN (use signed_power(-4, 0.5) = -2 for a sign‑preserving root)"
},
{
"operator_syntax": "subtract(x, y, filter=false), x - y",
"level": "base",
"summary": "Subtracts inputs left to right: x ? y ? … Supports two or more inputs. Set filter=true to treat NaNs as 0 before subtraction.",
"detailed_explanation": "Performs element‑wise subtraction on scalars or series. You can pass more than two inputs; evaluation is left‑to‑right: subtract(a, b, c) = ((a − b) − c). When filter=true, any NaN in the inputs is replaced with 0 before subtraction; when false, NaNs propagate.\n\nExample calculations for the calculation walkthrough\n\nsubtract(10, 3) = 7\nsubtract(10, 3, 2) = 5 (left‑to‑right: (10−3)−2)\nsubtract(NaN, 5, filter=true) = 0 − 5 = −5\n\nsubtract(NaN, 5, filter=false) = NaN\n\nLogical\nOperator\nDescription\nand(input1, input2)\nbase\nReturns 1 ('true') if both inputs are 1 ('true'). Otherwise, returns 0 ('false')."
},
{
"operator_syntax": "if_else(input1, input2, input 3)",
"level": "base",
"summary": "The if_else operator returns one of two values based on a condition. If the condition is true, it returns the first value; if false, it returns the second value.",
"detailed_explanation": "if_else(event_condition, Alpha_expression_1, Alpha_expression_2)\n\nThe if_else operator lets you choose between two expressions depending on whether a condition is met. This is useful for creating Alphas that react to market events, data thresholds, or other logical rules.\n\nExamples\n\nEvent = volume > adv20;\n\nif_else(Event, 2 * ts_delta(close, 3), ts_delta(close, 3))\n\nWhen volume spikes above its 20‑day average, your position change doubles; otherwise it stays normal.\n\nAlpha Example\n\n1\n2\n3\n4\nEvent = volume > adv20;\nalpha_1 = 2 * (-ts_delta(close, 3));\nalpha_2 = (-ts_delta(close, 3));\nif_else(event, alpha_1, alpha_2)\nOpen example alpha in Simulate\nSimulation Settings\nRegion\tUniverse\tLanguage\tDecay\tDelay\tTruncation\tNeutralization\tPasteurization\tNaN Handling\tUnit Handling\tMax Trade\tMax Position\nUSA\tTOP3000\tFast Expression\t3\t1\t0.01\tIndustry\tOn\tOff\tVerify\tOFF\tOFF\ninput1 < input2\nbase\nReturns 1 ('true') if input1 is a smaller than input2. Otherwise, returns 0 ('false').\ninput1 <= input2\nbase\nReturns 1 ('true') if input1 is a smaller or the same as input2. Otherwise, returns 0 ('false').\ninput1 == input2\nbase\nReturns 1 ('true') if input1 and input2 are the same. Otherwise, returns 0 ('false').\ninput1 > input2\nbase\nReturns 1 ('true') if input1 is a larger than input2. Otherwise, returns 0 ('false').\ninput1 >= input2\nbase\nReturns 1 ('true') if input1 is a larger or the same as input2. Otherwise, returns 0 ('false').\ninput1!= input2\nbase\nReturns 1 ('true') if input1 and input2 are different numbers. Otherwise, returns 0 ('false')."
},
{
"operator_syntax": "is_nan(input)",
"level": "base",
"summary": "If (input == NaN) return 1 else return 0",
"detailed_explanation": "is_nan(x) operator can be used to identify NaN values and replace them to a default value using if_else statement. For example:\n\n1\nif_else(is_nan(rank(sales)), 0.5, rank(sales))\nOpen example alpha in Simulate\nSimulation Settings\nRegion\tUniverse\tLanguage\tDecay\tDelay\tTruncation\tNeutralization\tPasteurization\tNaN Handling\tUnit Handling\tMax Trade\tMax Position\nUSA\tTOP3000\tFast Expression\t1\t1\t1\tMarket\tOn\tOff\tVerify\tOFF\tOFF\n\nIn this example, in case sales value is NaN for any instrument, then the expression will replace it with the mean value of rank, that is 0.5.\n\nnot(x)\nbase\nReturns the logical negation of x. Returns 0 when x is 1 (‘true’) and 1 when x is 0 (‘false’).\nor(input1, input2)\nbase\nReturns 1 if either input is true (either input1 or input2 has a value of 1), otherwise it returns 0.\nTime Series\nOperator\nDescription"
},
{
"operator_syntax": "days_from_last_change(x)",
"level": "base",
"summary": "Calculates the number of days since the last change in the value of a given variable.",
"detailed_explanation": "The days_from_last_change(x) operator returns how many days have passed since the last time the value of x changed. This is useful for tracking the “age” of the current value. Can be used as a trade_when condition.\n\nExample calculations\n\nDate\tX\n2024-06-01\t10\n2024-06-02\t10\n2024-06-03\t12\n2024-06-04\t12\n2024-06-05\t12\n2024-06-06\t15\nOn 2024-06-05: days_from_last_change(x) = 2\nOn 2024-06-06: days_from_last_change(x) = 0\n\nExamples\n\nLast_earnings_date = days_from_last_change(ern2_earnrelease_d1_calendar_prev);\n\nalpha = rank(operating_income/cap);\n\ntrade_when(Last_earnings_date == 0, alpha, -1)"
},
{
"operator_syntax": "hump(x, hump = 0.01)",
"level": "base",
"summary": "Limits amount and magnitude of changes in input (thus reducing turnover)",
"detailed_explanation": "hump(x, hump = 0.01)\n\nThis operator limits the frequency and magnitude of changes in the Alpha (thus reducing turnover). If today's values show only a minor change (not exceeding the Threshold) from yesterday's value, the output of the hump operator stays the same as yesterday. If the change is bigger than the limit, the output is yesterday's value plus the limit in the direction of the change.\n\nThis operator may help reduce turnover and drawdown.\n\nInput: Value of 1 instrument in past 2 days where first element is the latest: (2, 5), hump: 0.1, assuming limit: 1.5\n\nOutput: 3.5 (from 5-1.5 instead of 2 as abs(2 - 5) greater than limit)\n\nFlowchart of the Hump operator:\n\n1\nhump(-ts_delta(close, 5), hump = 0.00001)\nOpen example alpha in Simulate\nSimulation Settings\nRegion\tUniverse\tLanguage\tDecay\tDelay\tTruncation\tNeutralization\tPasteurization\tNaN Handling\tUnit Handling\tMax Trade\tMax Position\nUSA\tTOP3000\tFast Expression\t3\t1\t0.01\tMarket\tOn\tOff\tVerify\tOFF\tOFF"
},
{
"operator_syntax": "kth_element(x, d, k, ignore=“NaN”)",
"level": "base",
"summary": "Returns the K-th value from a time series by looking back over a specified number of (‘d’) days, with the option to ignore certain values. Commonly used for backfilling missing data.",
"detailed_explanation": "The kth_element(x, d, k) operator retrieves the k-th value from the input series x by searching through the last d days. You can specify which values to ignore (e.g., “NaN”, “0”) using the ignore parameter. This operator is especially useful for filling in missing data points (backfilling), where setting k=1 returns the most recent valid value.\n\nExample Calculations\n\nSuppose your input series for a stock's sales/assets ratio over 5 days is: [0.5, NaN, NaN, 0.7, 0]\n\nUsing kth_element(sales/assets, 5, k=“1”, ignore=“NaN 0”):\n\nDate\tInput Value\tLookback Window (up to 5 days)\tOutput\n2024-06-01\t0.5\t[0.5]\t0.5\n2024-06-02\tNaN\t[0.5, NaN]\t0.5\n2024-06-03\tNaN\t[0.5, NaN, NaN]\t0.5\n2024-06-04\t0.7\t[0.5, NaN, NaN, 0.7]\t0.7\n2024-06-05\t0\t[0.5, NaN, NaN, 0.7, 0]\t0.7\nIf you have a time series with missing values (NaNs) and want to fill each missing value with the most recent non-NaN value, set k=1 and ignore=“NaN”.\nIf you want the second most recent non-zero, non-NaN value, set k=2 and ignore=“NaN 0”.\n\nWhile you can achieve the same result with ts_backfill, there are cases where you would prefer the kth_element operator, for example:\n\nExpression 1: kth_element(dividend,63,k=1,ignore=“NaN 0”)\n\nExpression 2: ts_backfill(to_nan(sales/assets, value=0), 63)\n\nBoth expressions produce the same result. But using the kth_element operator is more efficient here, as it eliminates the need for an additional operator.\n\n1\nkth_element(sales/assets,252,k=\"1\",ignore=\"NAN 0\")\nOpen example alpha in Simulate\nSimulation Settings\nRegion\tUniverse\tLanguage\tDecay\tDelay\tTruncation\tNeutralization\tPasteurization\tNaN Handling\tUnit Handling\tMax Trade\tMax Position\nUSA\tTOP3000\tFast Expression\t3\t1\t0.01\tIndustry\tOn\tOff\tVerify\tOFF\tOFF"
},
{
"operator_syntax": "last_diff_value(x, d)",
"level": "base",
"summary": "Returns the most recent value of x from the past d days that is different from the current value of x.",
"detailed_explanation": "The last_diff_value(x, d) operator helps you find the last value of a variable x within the previous d days that is not equal to its current value. This is useful for detecting when a value has changed and what the previous value was.\n\nExamples\n\nlast_diff_value(eps, 63)\n\nReturns the most recent eps (earnings per share) in the last 60 days (~quarter) that differs from today’s eps; if no change within 63 days, returns NaN."
},
{
"operator_syntax": "ts_arg_max(x, d)",
"level": "base",
"summary": "Returns the number of days since the maximum value occurred in the last d days of a time series. If today's value is the maximum, returns 0; if it was yesterday, returns 1, and so on.",
"detailed_explanation": "The ts_arg_max(x, d) operator finds the relative index (number of days ago) of the maximum value in the time series x over the past d days.\n\nExample calculations\n\nSuppose you have the following values for the past 6 days (with the first element being today):\n\nx = [6, 2, 8, 5, 9, 4]; d = 6\n\nThe maximum value is 9.\n9 occurred 4 days before today.\nSo, ts_arg_max(x, 6) returns 4.\n\nIf today's value is the maximum, the operator returns 0.\n\nExamples\n\nts_arg_max(close, 10)\n\nThis expression returns how many days ago the highest closing price occurred in the last 10 days."
},
{
"operator_syntax": "ts_arg_min(x, d)",
"level": "base",
"summary": "Returns the number of days since the minimum value occurred in a time series over the past d days. If today's value is the minimum, returns 0; if it was yesterday, returns 1, and so on.",
"detailed_explanation": "The ts_arg_min(x, d) operator finds how many days ago the minimum value appeared in the last d days of the time series x.\n\nExample calculations\n\nSuppose you have the following values for the past 6 days (with the first element being today):\n\ndata = [6, 2, 8, 5, 9, 4]\n\nThe minimum value is 2. It occurred 1 day before today. So, ts_arg_min(data, 6) returns 1.\n\nExamples\n\nts_arg_min(close, 10)\n\nThis expression returns the number of days since the lowest closing price in the last 10 days."
},
{
"operator_syntax": "ts_av_diff(x, d)",
"level": "base",
"summary": "Calculates the difference between a value and its mean over a specified period, ignoring NaN values in the mean calculation. In short, it returns x – ts_mean(x, d) with NaNs ignored.",
"detailed_explanation": "The ts_av_diff(x, d) operator returns the difference between the current value x and the mean of x over the past d periods, excluding any NaN values from the mean calculation.\n\nExample calculations\n\nSuppose d = 6 and the values for the past 6 days are [6, 2, 8, 5, 9, NaN].\n\nThe mean is calculated as (6 + 2 + 8 + 5 + 9) / 5 = 6 (NaN is ignored).\n\nToday's value is in the first index which is 6. Hence, 6 - 6 = 0.\n\nExamples\n\nts_av_diff(close, 20)\n\nOutputs today’s deviation from the 20‑day mean of close, ignoring NaNs in the mean; positive when above average, negative when below."
},
{
"operator_syntax": "ts_backfill(x,lookback = d, k=1)",
"level": "base",
"summary": "Replaces missing (NaN) values in a time series with the most recent valid value from a specified lookback window, improving data coverage and reducing risk from missing data.",
"detailed_explanation": "This helps maintain data integrity, increases coverage, and can reduce drawdown risk in your Alpha. You can also specify which recent value to use with the k parameter (e.g., the 2nd most recent non-NaN value).\n\nThe ts_backfill function takes x (input data or expression), lookback = d (number of days to look back), and an optional k (kth most recent valid value, default is 1).\n\nExample calculations\n\nSuppose you have a time series for a stock's daily volume over 5 days:\n\nDay\tVolumn\n2024-06-01\t100\n2024-06-02\tNaN\n2024-06-03\t120\n2024-06-04\tNaN\n2024-06-05\tNaN\n\nUsing ts_backfill(volume, 3) on Day 5:\n\nLooks back up to 3 days for the most recent non-NaN value.\n\nFinds 120 on Day 3, so Day 5's value becomes 120.\n\nUsing ts_backfill(volume, 3, k=2) on Day 5:\n\nLooks for the 2nd most recent non-NaN value within 3 days.\n\nFinds 100 on Day 1, so Day 5's value becomes 100.\n\nExamples\n\nts_backfill(fnd6_newqv1300_xrdq, 252)\n\nEach NaN is replaced with the most recent non‑NaN value found within the last 252 trading days; if none exists within the window, the output stays NaN\n\nTip: Avoid setting the lookback period too long, as this may introduce outdated values and reduce signal quality."
},
{
"operator_syntax": "ts_corr(x, y, d)",
"level": "base",
"summary": "Calculates the Pearson correlation between two variables, x and y, over the past d days, showing how closely they move together.",
"detailed_explanation": "This coefficient measures the strength and direction of the linear relationship between the two variables. The value ranges from -1 (perfect negative correlation) to 1 (perfect positive correlation), with 0 indicating no linear relationship. This operator is most effective when the data is normally distributed, and the relationship is linear.\n\n𝐶\n𝑜\n𝑟\n𝑟\n𝑒\n𝑙\n𝑎\n𝑡\n𝑖\n𝑜\n𝑛\n(\n𝑥\n,\n𝑦\n)\n=\n∑\n𝑖\n=\n𝑡\n−\n𝑑\n+\n1\n𝑡\n(\n𝑥\n𝑖\n−\n𝑥\n¯\n)\n(\n𝑦\n𝑖\n−\n𝑦\n¯\n)\n∑\n𝑖\n=\n𝑡\n−\n𝑑\n+\n1\n𝑡\n(\n𝑥\n𝑖\n−\n𝑥\n¯\n)\n2\n(\n𝑦\n𝑖\n−\n𝑦\n¯\n)\n2\n\nExamples\n\nInput: Value of 1 instrument in past 7 days: (2, 3, 5, 6, 3, 8, 10), and another instrument value in past 7 days: (100, 190, 150, 180, 210, 220, 240), d = 7, where first element is the latest\n\nOutput: 0.6891 (Pearson correlation coefficient formula)\n\nAlpha Example\n\nts_corr(vwap, close, 20)\n\nThis expression calculates the 20-day rolling Pearson correlation between vwap and close.\n1\nts_corr(vwap, close, 20)\nOpen example alpha in Simulate\nSimulation Settings\nRegion\tUniverse\tLanguage\tDecay\tDelay\tTruncation\tNeutralization\tPasteurization\tNaN Handling\tUnit Handling\tMax Trade\tMax Position\nUSA\tTOP3000\tFast Expression\t3\t1\t0.01\tIndustry\tOn\tOff\tVerify\tOFF\tOFF"
},
{
"operator_syntax": "ts_count_nans(x ,d)",
"level": "base",
"summary": "Counts the number of missing (NaN) values in a data series over a specified number of days.",
"detailed_explanation": "Example calculations\n\nSuppose you have a data series for a stock's daily volume over 5 days, first element is the latest:\n[100, NaN, 200, NaN, 300]\n\nUsing ts_count_nans(volume, 5) on the last day will return 2, since there are two NaN values in the last 5 days.\n\nIf your data for the last 10 days is:\n[NaN, 50, 60, NaN, NaN, 80, 90, 100, NaN, 110]\n\nts_count_nans(x, 10) will return 4 (four NaNs in the last 10 days)."
},
{
"operator_syntax": "ts_covariance(y, x, d)",
"level": "base",
"summary": "Calculates the covariance between two time-series variables, y and x, over the past d days. Useful for measuring how two variables move together within a specified historical window.",
"detailed_explanation": "Covariance quantifies the direction and strength of the linear relationship between two variables. A positive covariance means the variables tend to move in the same direction, while a negative value means they move in opposite directions. The magnitude reflects the strength of this relationship, but it is sensitive to the scale of the variables.\n\nExample calculations\n\nSuppose you have two time-series:\n\ny = [2, 4, 6, 8, 10]\nx = [1, 3, 5, 7, 9]\nd = 5 (using all 5 days)\n\nThe covariance is calculated as:\n\nCompute the mean of y and x:\nmean_y = (2+4+6+8+10)/5 = 6\nmean_x = (1+3+5+7+9)/5 = 5\nFor each day, calculate (y_i - mean_y) * (x_i - mean_x):\n(2-6)*(1-5) = 16\n(4-6)*(3-5) = 4\n(6-6)*(5-5) = 0\n(8-6)*(7-5) = 4\n(10-6)*(9-5) = 16\nSum these values: 16 + 4 + 0 + 4 + 16 = 40\nDivide by the number of days: 40 / 5 = 8\n\nSo, ts_covariance(y, x, 5) returns 8."
},
{
"operator_syntax": "ts_decay_linear(x, d, dense = false)",
"level": "base",
"summary": "Applies a linear decay to time-series data over a set number of days, smoothing the data by averaging recent values and reducing the impact of older or missing data.",
"detailed_explanation": "Linear decay means more recent values have a higher weight, and older values have less influence. By default, it operates in sparse mode (dense = false), treating missing (NaN) values as zero. In dense mode, NaNs are not replaced.\n\nThis operator is useful for:\n\nReducing turnover by smoothing out sharp changes in your Alpha.\nLimiting the effect of outliers and noise in your data.\nMaking your strategy more stable across days.\n\nExample calculations\n\nSuppose you have a time series:\nx = [2, 4, 6, 8, 10] and you want to apply ts_decay_linear(x, 3).\n\nFor the most recent value (10), the calculation uses the last 3 values: 6, 8, 10.\nThe weights are linear: 1 (oldest), 2, 3 (most recent).\nCalculation:\n(6*1 + 8*2 + 10*3) / (1+2+3) = (6 + 16 + 30) / 6 = 52 / 6 ≈ 8.67\n\nSo, the output for the last day is about 8.67, showing that recent values have more influence.\n\nTip: To get the most out of the ts_decay_linear operator, use it in intermediate stages of your alphas, such as in the following example:\n\nSignal = ts_rank(ts_decay_linear(close, 5), 252);\n\nAlpha = rank(Signal);\n\nOtherwise, if you need decay at the end (using it on alpha variable in this case), adjust the decay setting directly in the simulation settings instead of using the operator."
},
{
"operator_syntax": "ts_delay(x, d)",
"level": "base",
"summary": "Returns the value of a variable x from d days ago. Use this operator to access historical data points by specifying the desired time lag in days.",
"detailed_explanation": "This is useful for referencing past data in time series analysis, such as comparing current values to previous values or constructing lagged features for modeling.\n\nExample calculations\n\nFor a time series:\n\nSuppose you have the following daily closing prices for a stock:\n\nDay\tclose\n2024-06-01\t100\n2024-06-02\t102\n2024-06-03\t101\n2024-06-04\t105\n2024-06-05\t107\n\nts_delay(close, 3) and today is day 2024-06-05, returns 101 (the value from Day 3).\n\nExamples\n\nts_delay(close, 5)\n\nReturns the closing price from five trading days ago; use it to form lags for deltas and returns."
},
{
"operator_syntax": "ts_delta(x, d)",
"level": "base",
"summary": "Calculates the difference between a value and its delayed version over a specified period. Useful for measuring changes or momentum in time-series data.",
"detailed_explanation": "The ts_delta(x, d) operator computes the difference between the current value of x and its value d periods ago. This is a simple way to measure how much a variable has changed over a given time window, making it useful for detecting trends, momentum, or reversals in time-series data.\n\nExample calculations\n\nSuppose you have a time series of daily closing prices for a stock:\n\nDay\tPrice\n2024-06-01\t100\n2024-06-02\t102\n2024-06-03\t105\n2024-06-04\t103\n2024-06-05\t108\n\nIf you want to calculate the 3-day delta for Day 5:\n\nts_delta(price, 3) on Day 5 = price on Day 5 - price on Day 3 = 108 - 105 = 3\n\nExamples\n\nts_delta(close, 5)\n\nWhat to expect: Today’s close minus the close five days ago; positive for 5‑day up moves, negative for down moves."
},
{
"operator_syntax": "ts_mean(x, d)",
"level": "base",
"summary": "Calculates the simple average (mean) value of a variable x over the past d days.",
"detailed_explanation": "The ts_mean(x, d) operator computes the simple average of the values of x for the most recent d days. This is useful for smoothing out short-term fluctuations and identifying longer-term trends in time-series data.\n\nExample calculations\n\nSuppose you have the following values for x over the last 5 days:\n\nDay\tValue of x\n2024-06-01\t6\n2024-06-02\t2\n2024-06-03\t8\n2024-06-04\t5\n2024-06-05\t9\n\nIf you use ts_mean(x, 5), the calculation is:\n\n(6 + 2 + 8 + 5 + 9) / 5 = 30 / 5 = 6\n\nSo, ts_mean(x, 5) returns 6.\n\nExamples\n\nts_mean(returns, 21)\n\nWhat to expect: Computes the 1‑month average daily return; smooths day‑to‑day noise."
},
{
"operator_syntax": "ts_product(x, d)",
"level": "base",
"summary": "Returns the product of the values of x over the past d days. Useful for calculating geometric means and compounding returns or growth rates.",
"detailed_explanation": "The ts_product(x, d) operator computes the product of the values of x for the last d days. This is especially useful in financial analysis for calculating geometric means, which are often preferred over arithmetic means for averaging rates of return or growth rates. For example, the geometric mean of daily returns over a period can be derived using ts_product.\n\nExample calculations\n\nIf you have daily returns for a stock over 5 days:\n\nReturns: [1.01, 0.99, 1.02, 1.00, 1.03]\n\nts_product(returns, 5) will calculate:\n\n1.01 × 0.99 × 1.02 × 1.00 × 1.03 = 1.0501\n\nExamples\n\npower(ts_product(returns, 10), 1/10)\n\nCalculate the geometric mean of daily returns for the past 10 days:\n1\npower(ts_product(returns, 10), 1/10)\nOpen example alpha in Simulate\nSimulation Settings\nRegion\tUniverse\tLanguage\tDecay\tDelay\tTruncation\tNeutralization\tPasteurization\tNaN Handling\tUnit Handling\tMax Trade\tMax Position\nUSA\tTOP3000\tFast Expression\t1\t1\t1\tMarket\tOn\tOff\tVerify\tOFF\tOFF"
},
{
"operator_syntax": "ts_quantile(x,d, driver=\"gaussian\" )",
"level": "base",
"summary": "Calculates the ts_rank of the input and transforms it using the inverse cumulative distribution function (quantile function) of a specified probability distribution (default: Gaussian/normal). This helps to normalize or reshape the distribution of your data over a rolling window.",
"detailed_explanation": "The ts_quantile(x, d, driver=“gaussian”) operator first computes the time-series rank of the input x over the past d days for each instrument. It then applies the inverse cumulative distribution function (quantile function) of the chosen distribution (driver) to these ranks. Supported distributions are ”gaussian” (default), ”uniform”, and ”cauchy”.\n\nExample 1\n\nInput: Value of 1 instrument in past 7 days where first element is the latest: (8, 10, 4, 6, 5, 3, 2), d: 7, driver: ’gaussian’ Output: quantile = 0.82 from SD = 2.82, mean = 5.43, zscore = 0.911\n\n- ts_quantile(anl14_mean_div_fy1/cap, 252, driver=“gaussian”)\n\nThe past‑252‑day history is mapped to a Gaussian‑like shape while preserving time‑series order, often making the series more symmetric and comparable over time."
},
{
"operator_syntax": "ts_rank(x, d, constant = 0)",
"level": "base",
"summary": "Ranks the value of a variable for each instrument over a specified number of past days, returning the rank of the current value (optionally adjusted by a constant). Useful for normalizing time-series data and highlighting relative performance over time.",
"detailed_explanation": "The ts_rank operator evaluates how the current value of a variable compares to its values over a defined lookback period (d days) for each instrument. It returns a normalized rank (between 0 and 1) of the current value within that window, optionally shifted by a constant. This is helpful for identifying trends, momentum, or reversals in time-series data.\n\nExample calculations\n\nSuppose you have the following closing prices for a stock over 5 days:\n[10, 12, 11, 15, 13]\n\nTo calculate ts_rank(close, 5) for the last day:\nRank the last value (13) among [10, 12, 11, 15, 13]\nSorted: [10, 11, 12, 13, 15]\n13 is the 4th value out of 5 (0-based index: 3)\nNormalized rank: 3 / (5 - 1) = 0.75\n\nIf you use a constant, e.g., ts_rank(close, 5, 0.1), the result would be 0.75 + 0.1 = 0.85.\n\nExamples\n\nts_rank(pretax_income, 252)\n\nThis ranks a company's current pretax income within its own historical range from the past year.\n\nrank(ts_rank(cap/income, 252))\n\nThis formula first normalizes each stock's P/E ratio by ranking it against its own one-year history (ts_rank). Then, it performs a cross-sectional rank on those historical percentiles, allowing us to identify which stocks are most expensive or inexpensive relative to their own past valuation, rather than comparing their absolute P/E ratios."
},
{
"operator_syntax": "ts_regression(y, x, d, lag = 0, rettype = 0)",
"level": "base",
"summary": "Returns various parameters related to regression function",
"detailed_explanation": "ts_regression(y, x, d, lag = 0, rettype = 0)\n\nGiven a set of two variables’ values (X: the independent variable, Y: the dependent variable) over a course of d days, an approximating linear function can be defined, such that sum of squared errors on this set assumes minimal value:\n\nBeta and Alpha in second line are OLS Linear Regression coefficients.\n\nts_regression operator returns various parameters related to said regression. This is governed by “rettype” keyword argument, which has a default value of 0. Other “rettype” argument values correspond to:\n\n0\nError Term\n1\ny-intercept (α)\n2\nslope (β)\n3\ny-estimate\n4\nSum of Squares of Error (SSE)\n5\nSum of Squares of Total (SST)\n6\nR-Square\n7\nMean Square Error (MSE)\n8\nStandard Error of β\n9\nStandard Error of α\n\nHere, \"di\" is current day index, “n”(may differ from d) is a number of valid (x, y) tuples used for calculation. All summations are over day index, using only valid tuples.\n\n“lag” keyword argument may be optionally specified (default value is zero) to calculate lagged regression parameters instead:\n\nExample:\n\nts_regression(est_netprofit, est_netdebt, 252, lag = 0, rettype = 2)\nTaking the data from the past 252 trading days (1 year), return the β coefficient from the equation when estimating the est_netprofit using the est_netdebt\n1\nts_regression(ts_mean(volume, 2), ts_returns(close, 2), 252)\nOpen example alpha in Simulate\nSimulation Settings\nRegion\tUniverse\tLanguage\tDecay\tDelay\tTruncation\tNeutralization\tPasteurization\tNaN Handling\tUnit Handling\tMax Trade\tMax Position\nUSA\tTOP3000\tFast Expression\t3\t1\t5\tMarket\tOn\tOff\tVerify\tOFF\tOFF"
},
{
"operator_syntax": "ts_scale(x, d, constant = 0)",
"level": "base",
"summary": "Scales a time series to a 0–1 range based on its minimum and maximum values over a specified period, with an optional constant shift.",
"detailed_explanation": "The ts_scale(x, d, constant = 0) operator normalizes a time series by scaling each value between 0 and 1, using the minimum and maximum values from the last d days. You can also add a constant to shift the scaled result. This is similar to the scale_down operator but works specifically on time series data.\n\nThe formula is:\n\nts_scale(x, d, constant) = (x - ts_min(x, d)) / (ts_max(x, d) - ts_min(x, d)) + constant\n\nExample calculations\n\nSuppose d = 6 and the values for the last 6 days are data = [6, 2, 8, 5, 9, 4] (with the first element being today’s value):\n\nts_min(x, d) = 2\nts_max(x, d) = 9\n\nIf you use ts_scale(x, d, constant = 1) for today's value (6):\n\nts_scale(data, 6, 1) = 1 + (6 - 2) / (9 - 2) = 1 + 4 / 7 ≈ 1.57\n\nExamples\n\nts_scale(close, 252, constant=0)\n\nScales today’s close to [0,1] within its 1‑year range; 0 at the 1‑year low, 1 at the 1‑year high.\n\nTip: When performing regression calculations where the Y variable represents a proportion or percentage, you can apply ts_scale to your X variable if needed. However, keep in mind that this scaling method is highly sensitive to outliers in the time series data, as extreme values can disproportionately affect the minimum and maximum used for normalization.ts_std_dev(x, d)."
},
{
"operator_syntax": "ts_std_dev(x, d)",
"level": "base",
"summary": "Calculates the standard deviation of a data series x over the past d days, measuring how much the values deviate from their mean during that period.",
"detailed_explanation": "The ts_std_dev(x, d) operator returns the standard deviation of the input series x for the last d days. Standard deviation is a key statistical measure that quantifies the amount of variation or dispersion in a dataset. In the context of time series, it helps you understand how volatile or stable a variable (such as returns or prices) has been over a specified window.\n\nA low standard deviation means values are close to the mean, while a high standard deviation indicates values are more spread out.\n\nExample calculations\n\nSuppose you have daily returns for a stock over the last 5 days:\nx = [0.01, 0.02, -0.01, 0.00, 0.03]\n\nTo calculate the 5-day standard deviation:\n\nCompute the mean:\n(0.01 + 0.02 + -0.01 + 0.00 + 0.03) / 5 = 0.01\nCompute squared deviations:\n\n(0.01 - 0.01)² = 0\n\n(0.02 - 0.01)² = 0.0001\n\n(-0.01 - 0.01)² = 0.0004\n\n(0.00 - 0.01)² = 0.0001\n\n(0.03 - 0.01)² = 0.0004\n\nAverage the squared deviations:\n(0 + 0.0001 + 0.0004 + 0.0001 + 0.0004) / 5 = 0.0002\nTake the square root:\nsqrt(0.0002) ≈ 0.0141\n\nSo, ts_std_dev(x, 5) would return approximately 0.0141.\n\nExamples\n\nts_std_dev(returns, 21)\n\nCalculates the 21‑day rolling standard deviation of daily returns; a proxy for one‑month stock volatility."
},
{
"operator_syntax": "ts_step(1)",
"level": "base",
"summary": "Returns a counter of days, incrementing by one each day.",
"detailed_explanation": "ts_step(1) is most commonly used as an x variable in functions like ts_regression, where it serves as a day counter. It helps represent time intervals in the regression analysis.\n\nExamples\n\nts_regression(returns, ts_step(1), 60, rettype=0)\n\nts_step(1) acts as the independent variable (x), counting days backward in the simulation. This allows the function to regress the returns over a 60-day window."
},
{
"operator_syntax": "ts_sum(x, d)",
"level": "base",
"summary": "Returns the sum of the values of x over the past d days.",
"detailed_explanation": "ts_sum(x, d) computes the sum of the values of x for the last d days. It is commonly used to aggregate daily data (e.g., returns, volume) over a window, or to accumulate fundamental data points into a trailing total.\n\nExamples\n\nts_sum(returns, 21)\n\nWhat to expect: Sums daily returns over the past 21 trading days (~1 month). Useful for creating multi-day return factors.\n\nts_sum(volume, 5)\n\nWhat to expect: Sums daily volume over the past 5 trading days (1 week) as a measure of weekly liquidity.\n\nTips\n\nts_sum(x, d) is similar to ts_mean(x, d) * d but preserves the magnitude rather than averaging. It pairs naturally with ts_backfill when accumulating fundamental data with missing values."
},
{
"operator_syntax": "ts_zscore(x, d)",
"level": "base",
"summary": "Calculates the Z-score of a time series, showing how far today's value is from the recent average, measured in standard deviations. Useful for standardizing and comparing values over time.",
"detailed_explanation": "The ts_zscore(x, d) operator computes the Z-score for each value in a time series. This tells you how many standard deviations today's value is from the mean of the past d days. It helps to normalize data, making it easier to compare values across different time periods or instruments, and can reduce the impact of outliers.\n\nExample calculations\n\nSuppose you have a time series of daily closing prices for a stock over 5 days: [10, 12, 11, 13, 15]. To calculate the Z-score for the last value (15) with a window of 5 days:\n\nMean of last 5 days: (10 + 12 + 11 + 13 + 15) / 5 = 12.2\nStandard deviation of last 5 days: ≈ 1.92\nZ-score for 15: (15 - 12.2) / 1.92 ≈ 1.46\n\nThis means today's value (15) is about 1.46 standard deviations above the recent average.\n\nExamples\n\nts_zscore(returns, 63)\n\nWhat to expect: Standardizes returns by subtracting the 63‑day mean and dividing by the 63‑day std; values are in “sigma” units.\n\nTips\n\nts_zscore can be useful to standardize different fields before using them in an Alpha.\nCombining ts_zscore with cross-sectional operators like rank or quantile can produce stronger signals compared to using either method alone, as it incorporates both standardized scaling and relative comparison.\nCross Sectional\nOperator\nDescription"
},
{
"operator_syntax": "normalize(x, useStd = false, limit = 0.0)",
"level": "base",
"summary": "Centers a daily cross section by subtracting the market mean; optionally divide by the cross sectional standard deviation and clamp the result to [?limit, +limit]. NaNs are ignored in mean/std.",
"detailed_explanation": "normalize(x, useStd = false, limit = 0.0)\n\nnormalize(x, useStd=false, limit=0.0) operates cross‑sectionally for each date:\n\nCompute the mean of all valid (non‑NaN) x values across instruments.\nSubtract that mean from each instrument’s value.\nIf useStd=true, compute the cross‑sectional standard deviation (std) of the mean‑centered values and divide each by std.\nIf limit ≠ 0.0, clamp each result to the range [−limit, +limit] (applied after optional std scaling).\n\nMean and standard deviation are computed each day on the same set of valid (non‑NaN) instruments; NaNs are excluded from the calculations and remain NaN in the output.\n\nThe limit parameter applies a symmetric cap to the final values; with useStd=true, this is equivalent to capping Z‑scores at ±limit.\n\nExample calculations for the calculation walkthrough Given a single day with four instruments:\n\nx = [3, 5, 6, 2]\n\nValid set = all four\n\nMean = (3 + 5 + 6 + 2) / 4 = 4\n\nMean‑centered = [−1, 1, 2, −2]\n\n1.normalize(x, useStd=false, limit=0.0)\n\nOutput = [−1, 1, 2, −2]\n\n2.normalize(x, useStd=true, limit=0.0)\n\nCross‑sectional std of mean‑centered: std ≈ 1.82\nDivide: [−1/1.82, 1/1.82, 2/1.82, −2/1.82] ≈ [−0.55, 0.55, 1.10, −1.10]\n\n3.normalize(x, useStd=true, limit=1.0)\n\nFrom step (2): [−0.55, 0.55, 1.10, −1.10]\nClamp to [−1, 1] → [−0.55, 0.55, 1.00, −1.00]\n\n4.normalize(x, useStd=false, limit=1.5)\n\nFrom step (1): [−1, 1, 2, −2]\nClamp to [−1.5, 1.5] → [−1, 1, 1.5, −1.5]\n\nExamples\n\nnormalize(rank(returns), useStd=true, limit=3)\n\nHere The normalize function act like a zscore operator, it computes cross‑sectional Z‑scores on ranked daily returns and caps them at ±3."
},
{
"operator_syntax": "quantile(x, driver = gaussian, sigma = 1.0)",
"level": "base",
"summary": "Ranks and shifts a vector of Alpha values, then applies a chosen statistical distribution (gaussian, cauchy, or uniform) to reduce outliers. The sigma parameter controls the scale of the output.",
"detailed_explanation": "quantile(x, driver = gaussian, sigma = 1.0)\n\nThe quantile(x, driver = gaussian, sigma = 1.0) operator is a cross-sectional tool that transforms a raw Alpha vector by ranking, shifting, and mapping its values to a specified distribution. This process can help reduce the impact of outliers and can improve the stability and performance of your Alpha.\n\nExample calculations\n\nStep 1: Rank the input Alpha vector. Each value is assigned a rank between 0 and 1.\nStep 2: Shift the ranked values so that, for N instruments, each value is within [1/N, 1-1/N]:\nAlpha_value = 1/N + Alpha_value * (1 - 2/N)\nStep 3: Apply the chosen distribution:\nIf driver = gaussian, map the shifted values to a normal distribution.\nIf driver = cauchy, map to a Cauchy distribution.\nIf driver = uniform, subtract the mean from each value.\nStep 4: The sigma parameter scales the final values (only affects scale, not ranking).\n\nExample Calculations\n\nSuppose you have 5 stocks with Alpha values: [0.2, 0.5, -0.1, 0.8, 0.3].\n\n1.Rank: [0.25, 0.75, 0.0, 1.0, 0.5]\n\n2.Shift (N=5):\n\nEach value: 1/5 + value * (1 - 2/5) = 0.2 + value * 0.6\n\nResult: [0.35, 0.65, 0.2, 0.8, 0.5]\n\n3.Apply gaussian distribution (here we choose in the expression driver = gaussian):\n\nThese shifted values are mapped to the corresponding quantiles of a normal distribution (mean 0, std sigma).\n\n4.Final output:\n\nThe output vector is now distributed according to the chosen distribution, with reduced outliers.\n\nExamples\n\nquantile(implied_volatility_call_60 - implied_volatility_put_60, driver=cauchy)\n\nToday’s cross‑section is rank‑mapped to a Cauchy distribution; ranks are preserved while the output becomes heavy‑tailed and less sensitive to extreme raw scales.\n1\nquantile(close, driver = gaussian, sigma = 0.5 )\nOpen example alpha in Simulate\nSimulation Settings\nRegion\tUniverse\tLanguage\tDecay\tDelay\tTruncation\tNeutralization\tPasteurization\tNaN Handling\tUnit Handling\tMax Trade\tMax Position\nUSA\tTOP3000\tFast Expression\t3\t1\t0.01\tMarket\tOn\tOff\tVerify\tOFF\tOFF"
},
{
"operator_syntax": "rank(x, rate=2)",
"level": "base",
"summary": "Ranks the values of the input x among all instruments, returning numbers evenly spaced between 0.0 and 1.0. Useful for normalizing data and reducing the impact of outliers.",
"detailed_explanation": "The rank(x) operator assigns a rank to each value in the input x across all instruments for a given date, mapping the lowest value to 0.0 and the highest to 1.0, with all other values evenly distributed in between. This helps normalize data, limit extreme values, and can improve the stability of your Alpha by reducing outliers and drawdown. The optional rate parameter controls the precision of sorting (default is 2; set to 0 for exact sorting).\n\nExample calculations\n\nSuppose you have the following values for five stocks on a given day:\n\nx = (4, 3, 6, 10, 2)\n\nApplying rank(x):\n\nThe lowest value (2) gets 0.0\nThe next lowest (3) gets 0.25\nThen 4 gets 0.5\n6 gets 0.75\nThe highest (10) gets 1.0\n\nSo, rank(x) returns: (0.5, 0.25, 0.75, 1, 0)\n\nExamples\n\nrank(ts_returns(close, 5))\n\nWhat to expect: Maps each stock’s 5‑day return to [0,1] across the universe for the day; 0 for the worst, 1 for the best, uniformly spaced in between.\n\nTip: A good robustness check is to evaluate how your Alpha performs after applying rank() at the end. If the performance doesn’t fall off dramatically, it is a good sign."
},
{
"operator_syntax": "scale(x, scale=1, longscale=1, shortscale=1)",
"level": "base",
"summary": "Scales the input so that the sum of absolute values across all instruments equals a specified book size. Allows separate scaling for long and short positions using optional parameters.",
"detailed_explanation": "The scale(x, scale=1, longscale=1, shortscale=1) operator adjusts the input values so that their total absolute value matches a target book size. By default, it scales so that the sum of absolute values is 1, but you can set a different scale. You can also use longscale and shortscale to apply different scaling to long and short positions, respectively. This operator is useful for normalizing your alpha signals and reducing the impact of outliers.\n\nExample calculations\n\nIf you have an input vector x = [2, -3, 5] and use scale(x), the operator will scale these values so that abs(2) + abs(-3) + abs(5) = 10 becomes 1. Each value is divided by 10, so the output is [0.2, -0.3, 0.5].\nUsing scale(x, scale=4), the sum of absolute values will be 4. The output will be [0.8, -1.2, 2.0].\nIf you want to scale long and short positions differently, e.g., scale(x, longscale=2, shortscale=3), positive values will be scaled so their sum is 2, and negative values so their sum is 3.\n\nExamples\n\nscale(returns, scale=4)\n\nThe vector is rescaled so that the sum of absolute values across instruments equals 4; relative signs and cross‑sectional order are preserved.\nwinsorize(x, std=4)\nbase\nWinsorize limits values in a data to within a specified number of standard deviations from the mean, reducing the impact of extreme outliers.\nShow more"
},
{
"operator_syntax": "zscore(x)",
"level": "base",
"summary": "Z-score is a numerical measurement that describes a value's relationship to the mean of a group of values. Z-score is measured in terms of standard deviations from the mean",
"detailed_explanation": "zscore(x)\n\nZ-score is a statistical tool that indicates how many standard deviations a data point lies from the average of a group of values. Essentially, it measures how unusual a data point is in relation to the mean, making it a handy tool for understanding deviation and comparison.\n\nThe formula to calculate a Z-score is:\n\n𝑍\n-\n𝑠\n𝑐\n𝑜\n𝑟\n𝑒\n=\n𝑥\n−\n𝑚\n𝑒\n𝑎\n𝑛\n(\n𝑥\n)\n𝑠\n𝑡\n𝑑\n(\n𝑥\n)\n\nWhere:\n\nx is an individual data point\nmean(x) is the average of the data set\nstd(x) is the standard deviation of the data set\n\nBy this definition, the mean of the Z-scores in a distribution is always 0, and the standard deviation is always 1.\n\nA Z-score tells you how many standard deviations a particular data point is from the mean. If the Z-score is positive, the data point is above the mean, and if it's negative, it's below the mean.\n\nZ-scores may be especially useful for normalizing and comparing different data fields for different stocks or different data fields. They allow researchers to calculate the probability of a score occurring within a standard normal distribution and compare two scores that are from different samples (which may have different means and standard deviations).\n\nThis operator may help reduce outliers.\n\nInput: Value of 5 instruments at day t: (100, 0, 50, 60, 25)\n\nOutput: (1.57, -1.39, 0.09, 0.39, -0.65) from SD: 33.7, mean: 47\n\n1\nzscore(close)\nOpen example alpha in Simulate\nSimulation Settings\nRegion\tUniverse\tLanguage\tDecay\tDelay\tTruncation\tNeutralization\tPasteurization\tNaN Handling\tUnit Handling\tMax Trade\tMax Position\nUSA\tTOP3000\tFast Expression\t3\t1\t0.03\tMarket\tOn\tOff\tVerify\tOFF\tOFF\nVector\nOperator\nDescription"
},
{
"operator_syntax": "vec_avg(x)",
"level": "base",
"summary": "Calculates the mean (average) of all elements in a vector field for each instrument and date, converting vector data to a single matrix value.",
"detailed_explanation": "The vec_avg(x) operator takes a vector field x and computes the arithmetic mean of its elements for each instrument and date. This is useful for summarizing vector data (such as multiple sentiment scores or short interest values in a day) into a single representative value that can be used in further calculations or as input to other operators.\n\nExample calculations\n\nDate\tX (vector datafield)\tvec_avg(X)\n2024-06-01\t[10, 20, 30]\t(10+20+30)/3 = 20\n2024-06-02\t[13, 5, 15]\t(13+5+15)/3 = 11\n2024-06-03\t[3, 12, 8, 20, 7]\t(3+12+8+20+7)/5 = 10\n\nExamples\n\nvec_avg(shrt3_bar)\n\nGet the average short interest for the current day for each stock\n\nTip: When unsure how to use a vector field, vec_avg() is a simple and effective way to summarize the data."
},
{
"operator_syntax": "vec_sum(x)",
"level": "base",
"summary": "Calculates the sum of all values in a vector field.",
"detailed_explanation": "The vec_sum(x) operator adds up every value in the vector field x and returns the total. This is useful for aggregating data points stored as vectors, such as total daily sentiment volume or total trades for a stock.\n\nExample calculations\n\nDate\tX (vector datafield)\tvec_avg(X)\n2024-06-01\t[10, 20, 30]\t10+20+30 = 60\n2024-06-02\t[13, 5, 15]\t13+5+15 = 33\n2024-06-03\t[3, 12, 8, 20, 7]\t3+12+8+20+7 = 50\n\nExamples\n\nvec_sum(scl12_alltype_buzzvec)\n\nSums all entries of the intraday “buzz” vector to get a daily total volume of mentions for each instrument.\nTransformational\nOperator\nDescription"
},
{
"operator_syntax": "trade_when(x, y, z)",
"level": "base",
"summary": "The trade_when operator changes Alpha values only when a specific condition is met, keeps previous values otherwise, and can close positions by assigning NaN under an exit condition. It is useful for reducing turnover and controlling when trades are executed.",
"detailed_explanation": "The trade_when(x, y, z) operator lets you:\n\nChange Alpha values only when a trigger condition (x) is true.\nHold (retain) previous Alpha values when the trigger is false.\nClose Alpha positions (set to NaN) when an exit condition (z) is true.\n\nThis operator is especially helpful for event-driven Alphas and for reducing turnover by only trading when certain events occur.\n\nExample calculations\n\nIf z (exit condition) is true, Alpha = NaN (no trade).\nIf z is false and x (trigger condition) is true, Alpha = y (new value).\nIf both z and x are false, Alpha = previous Alpha (hold position).\n\nExamples\n\ntrade_when(volume >= ts_mean(volume, 5), rank(-returns), -1)\n\nIf today's volume is higher than the 5-day average, Alpha = rank(-returns).\nIf not, Alpha holds its previous value.\nThe exit condition is always false (-1), so positions are not closed by this rule.\nGroup\nOperator\nDescription"
},
{
"operator_syntax": "group_backfill(x, group, d, std = 4.0)",
"level": "base",
"summary": "Fills missing (NaN) values for instruments within the same group by calculating a winsorized mean of all non-NaN values over the past d days. The winsorized mean is computed by trimming extreme values based on a specified standard deviation multiplier (std, default 4.0).",
"detailed_explanation": "The group_backfill operator is used to handle missing data (NaN values) for instruments that belong to the same group. When a value is missing for a specific instrument and date, the operator:\n\nLooks at all instruments in the same group.\nCollects all non-NaN values for the past d days.\nComputes the simple average after trimming (winsorizing) values that are further than std times the standard deviation from the mean.\nUses this winsorized mean to fill the missing value.\n\nThis approach helps maintain data coverage and reduces the impact of outliers, making it especially useful for fundamental or low-frequency datasets where missing values are common.\n\nExample calculations\n\nSuppose you have three instruments (i1, i2, i3) in the same group, and their values for the past 4 days are:\n\nx[i1] = [4, 2, 5, 5]\nx[i2] = [7, NaN, 2, 9]\nx[i3] = [NaN, -4, 2, NaN]\n\nThe first element is the most recent. If you want to backfill x’s recent value.\n\nGather all non-NaN values: [4, 2, 5, 5, 7, 2, 9, -4, 2]\nCalculate mean = 3.56, standard deviation = 3.71\nWinsorization range: 3.56 ± 4 × 3.71 (no values are outside this range, so no trimming)\nThe backfilled value for x[i3][0] is 3.56\n\nSo, group_backfill(x, group, 4 std=4.0) would output: [4, 7, 3.56]\n\nExamples\n\ngroup_backfill(fnd94_rt_gross_mgn_q, subindustry, 21)\n\nThis fills missing values for each industry group using the winsorized mean over the last 21 days. The data field fnd94_rt_gross_mgn_q represent gross margin, it is recommended for the data field that is being backfilled is in the same scale for all stocks.\n\nTip : If you are having trouble simulating because it takes too long to simulate. Try using the densify() operator on your group variable before passing it to the group operators. This removes empty groups and improves performance."
},
{
"operator_syntax": "group_mean(x, weight, group)",
"level": "base",
"summary": "Calculates the harmonic mean of a data field within each specified group.",
"detailed_explanation": "The group_mean(x, weight, group) operator computes the harmonic mean of the values of x for each group defined by group, optionally using a weight parameter. This is especially helpful for financial ratios, where the harmonic mean provides a more accurate average than the arithmetic mean.\n\nExample calculations\n\nSuppose you want to calculate the harmonic mean of the P/E ratio (pe_ratio) for each industry:\n\nIf you have three stocks in an industry with P/E ratios of 10, 15, and 20:\nHarmonic mean = 3 / (1/10 + 1/15 + 1/20) ≈ 13.85\nAll stocks in that industry will be assigned the value 13.85.\n\nExamples\n\ngroup_mean(close/eps, 1, industry)\n\nThis assigns the harmonic mean of P/E ratio within each industry group to all stocks in that group.\n\nTip : If you are having trouble simulating because it takes too long to simulate. Try using the densify() operator on your group variable before passing it to the group operators. This removes empty groups and improves performance.\n\n1\n1 /(group_mean(eps/close,1, industry))\nOpen example alpha in Simulate\nSimulation Settings\nRegion\tUniverse\tLanguage\tDecay\tDelay\tTruncation\tNeutralization\tPasteurization\tNaN Handling\tUnit Handling\tMax Trade\tMax Position\nUSA\tTOP3000\tFast Expression\t1\t1\t1\tMarket\tOn\tOff\tVerify\tOFF\tOFF"
},
{
"operator_syntax": "group_neutralize(x, group)",
"level": "base",
"summary": "Neutralizes Alpha values within each specified group by subtracting the group mean from each value. Groups can be industry, sector, country, or any custom grouping.",
"detailed_explanation": "The group_neutralize(x, group) operator adjusts Alpha values so that, within each group, the mean is zero. This is done by subtracting the mean of the group from each value in that group. This helps remove group-level effects and can reduce unwanted correlations in your Alpha.\n\nExample calculations\n\nSuppose you have 10 instruments with values:\n[3, 2, 6, 5, 8, 9, 1, 4, 8, 0]\n\nFirst 5 instruments belong to group A, last 5 to group B.\nMean of group A: (3+2+6+5+8)/5 = 4.8\nMean of group B: (9+1+4+8+0)/5 = 4.4\nSubtract group means:\nGroup A: [3-4.8, 2-4.8, 6-4.8, 5-4.8, 8-4.8] = [-1.8, -2.8, 1.2, 0.2, 3.2]\nGroup B: [9-4.4, 1-4.4, 4-4.4, 8-4.4, 0-4.4] = [4.6, -3.4, -0.4, 3.6, -4.4]\n\nExamples\n\nalpha1 = group_neutralize(ts_returns(close, 5), industry);\n\nSimply neutralize the signal within industry\n\ncustom_group = bucket(rank(cap), range=“0,1,0.2”);\n\nalpha2 = group_neutralize(ts_returns(close, 5), custom_group);\n\nThis divides stocks into 5 buckets by market cap and neutralizes within each bucket.\n\ngroup = densify(group_cartesian_product(industry, country));\n\nalpha3 = group_neutralize(ts_returns(close, 5), group);\n\nThis creates a unique group for each industry-country pair and neutralizes within those.\n\nTip: If you are having trouble simulating because it takes too long to simulate. Try using the densify() operator on your group variable before passing it to the group operators. This removes empty groups and improves performance."
},
{
"operator_syntax": "group_rank(x, group)",
"level": "base",
"summary": "Ranks each element within its group based on the input field, assigning a value between 0.0 and 1.0. This helps compare items within the same group, such as stocks in the same industry.",
"detailed_explanation": "The group_rank(x, group) operator assigns a rank to each element within its specified group, based on the values of x. The ranking is normalized to a range between 0.0 (lowest) and 1.0 (highest) within each group. This operator is useful for comparing items within similar categories (e.g., subindustries), focusing on intra-group differences.\n\nExample calculations\n\nSuppose you have five stocks in the “Tech” group with the following momentum values:\n\nStock\tMomentum\tgroup_rank(mom, “Tech”)\nA\t10\t0.0\nB\t20\t0.25\nC\t30\t0.5\nD\t40\t0.75\nE\t50\t1.0\n\nEach stock is ranked within the “Tech” group, with the lowest value assigned 0.0 and the highest 1.0.\n\nExamples\n\ngroup_rank(close, subindustry)\n\nRanks each stock's closing price within its subindustry group.\n\ngroup_rank(ts_rank(eps, 252), industry)\n\nFirst, computes the 252-day time-series rank of EPS for each stock, then ranks these values within each industry group.\n\nTip: If you are having trouble simulating because it takes too long to simulate. Try using the densify() operator on your group variable before passing it to the group operators. This removes empty groups and improves performance."
},
{
"operator_syntax": "group_scale(x, group)",
"level": "base",
"summary": "Normalizes values within each group to a range between 0 and 1, making data comparable across different groups.",
"detailed_explanation": "The group_scale(x, group) operator rescales the values of x within each specified group so that the minimum value in the group becomes 0 and the maximum becomes 1. This is done using the formula:\n\ngroup_scale(x, group) = (x - groupmin) / (groupmax - groupmin)\n\nThis normalization is useful for standardizing data within groups, allowing for fair comparisons and consistent data representation across different segments (such as industries, sectors, or custom buckets).\n\nExample calculations\n\nSuppose you have the following values for x in a group:\n\nGroup A: [10, 20, 30]\nGroup B: [5, 15, 25]\n\nFor Group A:\n\ngroupmin = 10, groupmax = 30\nScaled values:\n(10-10)/(30-10) = 0\n(20-10)/(30-10) = 0.5\n(30-10)/(30-10) = 1\n\nFor Group B:\n\ngroupmin = 5, groupmax = 25\nScaled values:\n(5-5)/(25-5) = 0\n(15-5)/(25-5) = 0.5\n(25-5)/(25-5) = 1\n\nExamples\n\ngroup_scale(return_equity, industry)\n\nThis will scale the return_equity within each industry group so that the lowest return_equity in each industry is 0 and the highest is 1. Making it comparable across industries with varying levels of capital intensity or profitability."
},
{
"operator_syntax": "group_zscore(x, group)",
"level": "base",
"summary": "Calculates the Z-score of each value within its group, showing how far each value is from the group mean in terms of standard deviations. Useful for comparing values relative to their group.",
"detailed_explanation": "The group_zscore(x, group) operator computes the Z-score for each value of x within the specified group. This means it measures how many standard deviations a value is from the mean of its group, allowing you to compare values on a normalized scale within each group. This is especially helpful when you want to standardize data for cross-sectional analysis within categories like industry, sector, or custom groupings.\n\nThe formula is:\n\ngroup_zscore(x, group) = (x - mean(x in group)) / stddev(x in group)\n\nThis operator is commonly used to normalize data within groups, making it easier to compare instruments that belong to the same group but may have different scales or distributions.\n\nExample calculations\n\nSuppose you have three stocks in a group with the following values for x:\n\nStock A: 10\nStock B: 20\nStock C: 30\n\nMean of group = (10 + 20 + 30) / 3 = 20\nStandard deviation of group ≈ 8.16\n\nStock A Z-score: (10 - 20) / 8.16 ≈ -1.22\nStock B Z-score: (20 - 20) / 8.16 = 0\nStock C Z-score: (30 - 20) / 8.16 ≈ 1.22\n\nExamples\n\nasset_group = bucket(rank(operating_income/assets), range=“0.1, 1, 0.1”)\n\nalpha = group_zscore(cap/income, densify(asset_group))\n\nThis creates groups based on ranks of operating_income/assets, and then computes the Z-score of P/E within each group."
}
]