# Cumulative (Aggregation) Expressions

Canonical page: https://www.adaptabletools.com/docs/adaptable-ql-expression-cumulative

- AdapTableQL performs cumulative aggregations with a `CUMULATIVE` clause on an Aggregation Function (`SUM{[PnL], CUMULATIVE([TradeDate])}`)

Cumulative Expressions, as the name suggests, perform **cumulative** Aggregations.

- This is particularly useful when calculating Running Totals
- AG Grid has no running totals: its formulas can only reach another row by its fixed row number

Cumulative Expressions are actually a special case of [Aggregation Expression](https://www.adaptabletools.com/docs/adaptable-ql-expression-aggregation/index.md) but where the _Aggregation Operation_ is applied to each row in the set cumulatively.

- **Run values in one line**: running PnL, running Notional, highest PnL so far - `SUM{[PnL], CUMULATIVE([TradeDate])}`
- **Per group too**: add `GROUP_BY` and each Book, Desk or Currency gets its own running total
- **Order comes from data**: running value follows `TradeDate` (or any date / number Column), whatever the Grid sort
- **Always live**: edit or add a trade and every running value after it updates 
- **Filter what counts**: add `WHERE` to keep a running total of just Buy trades, or just Open positions

## Aggregation Operations

There are 5 Aggregation Operations available when using Cumulative Aggregations:

- `SUM`
- `MIN`
- `MAX`
- `AVG`
- `COUNT`

## Using `CUMULATIVE` to set Order

The Aggregation Operation is applied in a **specific order**.

That order is specified by the `CUMULATIVE` clause, which takes the name of an [Adaptable Column](https://www.adaptabletools.com/docs/dev-guide-columns-adaptable-column/index.md) as its first parameter.

The `CUMULATIVE` clause only works with Columns of type `date` or `number`

```ts [[2, 2, "SUM"], [1, 2, "PnL"], [2, 2, "CUMULATIVE"], [1, 2, "TradeDate"]]
// Derive cumulative sum of all PnL columns according to TradeDate order
 SUM{[PnL], CUMULATIVE([TradeDate])};
```

```ts [[2, 2, "MAX"], [1, 2, "PnL"], [2, 2, "CUMULATIVE"], [1, 2, "TradeDate"]]
 // Calculate cumulative maximum value of all PnL columns according to TradeDate order
 MAX{[PnL], CUMULATIVE([TradeDate])};
```

- There is no need physically to sort the Grid using the column specified by `CUMULATIVE`
- It *ignores* the current Grid Sort and uses the order in the given Column

### Sort Direction

By default the Aggregation accumulates in **ascending** order (smallest or earliest first).

To accumulate in the opposite direction, pass `'DESC'` as an optional second parameter to `CUMULATIVE` (`'ASC'` is the default and can be omitted).

```ts [[2, 2, "SUM"], [1, 2, "PnL"], [2, 2, "CUMULATIVE"], [1, 2, "TradeDate"], [4, 2, "'DESC'"]]
// Running total of PnL from the most recent trade backwards
 SUM{[PnL], CUMULATIVE([TradeDate], 'DESC')};
```

Rows with a blank value in the `CUMULATIVE` Column are always placed **last** - in both ascending and descending order

### Filtering Rows

A `WHERE` clause restricts which rows are accumulated - see [WHERE Clause](https://www.adaptabletools.com/docs/adaptable-ql-expression-aggregation/index.md#where-clause) for full details:

```ts [[2, 2, "SUM"], [1, 2, "PnL"], [5, 2, "WHERE"], [1, 2, "Side"], [4, 2, "Buy"], [2, 2, "CUMULATIVE"], [1, 2, "TradeDate"]]
// Running total of PnL for Buy trades only
 SUM{[PnL] WHERE [Side] = 'Buy', CUMULATIVE([TradeDate])};
```

Rows excluded by `WHERE` return a blank value

### Running Weighted Average

`AVG` with a `WEIGHT` clause can also be cumulative - e.g. a running VWAP (Volume-Weighted Average Price):

```ts [[2, 2, "AVG"], [1, 2, "Price"], [2, 2, "WEIGHT"], [1, 2, "Quantity"], [2, 2, "CUMULATIVE"], [1, 2, "TradeTime"]]
// Running VWAP - average Price weighted by Quantity, in TradeTime order
 AVG{[Price], WEIGHT([Quantity]), CUMULATIVE([TradeTime])};
```

**Example: AdapTableQL: Cumulative Aggregation**

Using Cumulative Scalar Aggregation Expressions

- This demo contains 2 [Calculated Columns](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md) that use Cumulative Aggregation Scalar Expressions:
  - `Cumul Stars` - displays the cumulative sum of stars count of all repos in the grid, aggregated over the `Created` date
  - `Max Technical Debt` - shows the cumulative maxima of open issues of all repos in the grid, aggregated over the `GitHub Stars` count

### Expand to see the Aggregated Cumulative Scalar Expressions

The 2 Calculated Columns are defined as follows:

```
CalculatedColumn: {
  CalculatedColumns: [
    {
      ColumnId: 'cumul-stars-count',
      FriendlyName: 'Cumul Stars',
      Expression: 'SUM{[github_stars], CUMULATIVE([created_at])}',
      CalculatedColumnSettings: {
        DataType: 'number'
      },
    },
    {
      ColumnId: 'max-tech-debt-over-stars',
      FriendlyName: 'Maxi Technical Debt',
      Expression: 'MAX{[open_issues_count], CUMULATIVE([github_stars])}',
      CalculatedColumnSettings: {
        DataType: 'number'
      },
    },
  ]
}
```

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Aggregated Scalar Cumulative Expressions',
  initialState: {
    Dashboard: {
      ModuleButtons: ['CalculatedColumn'],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['CellSummary'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'name',
            'created_at',
            'language',
            'github_stars',
            'open_issues_count',
            'cumul-stars-count',
            'max-tech-debt-over-stars',
          ],
          ColumnSorts: [{ColumnId: 'created_at', SortOrder: 'Asc'}],
          AutoSizeColumns: true,
        },
      ],
    },
    CalculatedColumn: {
      CalculatedColumns: [
        {
          ColumnId: 'cumul-stars-count',
          FriendlyName: 'Cumul Stars',
          Expression: 'SUM{[github_stars], CUMULATIVE([created_at])}',
          CalculatedColumnSettings: {
            DataType: 'number',
            Resizable: true,
            Width: 200,
          },
        },
        {
          ColumnId: 'max-tech-debt-over-stars',
          FriendlyName: 'Max Technical Debt',
          Expression: 'MAX{[open_issues_count], CUMULATIVE([github_stars])}',
          CalculatedColumnSettings: {
            DataType: 'number',
            Resizable: true,
            Width: 200,
          },
        },
      ],
    },
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'formatColumn-created_at',
          Scope: {
            ColumnIds: ['created_at'],
          },
          DisplayFormat: {
            Formatter: 'DateFormatter',
            Options: {
              Pattern: 'yyyy/MM/dd',
            },
          },
        },
        {
          Name: 'formatColumn-number',
          Scope: {
            DataTypes: ['number'],
          },
          DisplayFormat: {
            Formatter: 'NumberFormatter',
            Options: {
              IntegerSeparator: ',',
            },
          },
        },
      ],
    },
  },
};
```

## Grouped Cumulative Aggregation

Like with Standard Scalar Aggregations, Cumulative Aggregations can be grouped.

Again this is accomplished by using the `GROUP_BY` clause.

`GROUP_BY` is a clause on the Aggregation Function (e.g. `SUM`), together with `CUMULATIVE`

```ts [[2, 2, "SUM"], [1, 2, "PnL"], [2, 2, "GROUP_BY"], [1, 2, "currency"], [2, 2, "CUMULATIVE"], [1, 2, "TradeDate"]]
// Cumulative sum of all PnL columns ordering by TradeDate, grouping by Currency
 SUM{[PnL], GROUP_BY([currency]), CUMULATIVE([TradeDate])};
```

Similar to Standard Scalar Aggregations, there is no limit on the number of Columns which can be grouped.

```ts [[2, 2, "SUM"], [1, 2, "PnL"], [2, 2, "GROUP_BY"], [1, 2, "currency"], [1, 2, "country"], [2, 2, "CUMULATIVE"], [1, 2, "TradeDate"]]
// Cumulative sum of all PnL columns ordering by TradeDate, grouping by Currency and Country
 SUM{[PnL], GROUP_BY([currency], [country]), CUMULATIVE([TradeDate])};
```

**Example: AdapTableQL: Cumulative Aggregations Grouped**

Using Cumulative Scalar Aggregations with Grouping

- This demo contains 2 [Calculated Columns](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md) that use Cumulative Aggregation Scalar Expressions, one with grouping:
  - `Cumul Stars` - displays the cumulative sum of stars count of **all repos** in the grid, aggregated over the `Created` date (same as in demo above)
  - `Cumul Lang Stars` - displays the cumulative sum of stars count in the grid, but grouped by `Language`, and aggregated over the `Created` date

### Expand to see the Aggregated Cumulative Scalar Expressions

The 2 Calculated Columns are defined as follows:

```
CalculatedColumn: {
  CalculatedColumns: [
    {
      ColumnId: 'cumul-stars-count',
      FriendlyName: 'Cumul Stars',
      Expression: 'SUM{[github_stars], CUMULATIVE([created_at])}',
      CalculatedColumnSettings: {
        DataType: 'number'
      },
    },
    {
      ColumnId: 'cumul-language-stars-count',
      FriendlyName: 'Cumul Lang Stars',
      Expression: 'SUM{[github_stars], GROUP_BY([language]), CUMULATIVE([created_at])}',
      CalculatedColumnSettings: {
        DataType: 'number'
      },
    },
  ]
}
```

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Aggregated Scalar Cumulative Expressions Grouped',
  initialState: {
    Dashboard: {
      ModuleButtons: ['CalculatedColumn'],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['CellSummary'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'name',
            'created_at',
            'language',
            'github_stars',
            'open_issues_count',
            'cumul-stars-count',
            'cumul-language-stars-count',
          ],
          ColumnSorts: [
            {ColumnId: 'language', SortOrder: 'Asc'},
            {ColumnId: 'created_at', SortOrder: 'Asc'},
          ],
          AutoSizeColumns: true,
        },
      ],
    },
    CalculatedColumn: {
      CalculatedColumns: [
        {
          ColumnId: 'cumul-stars-count',
          FriendlyName: 'Cumul Stars',
          Expression: 'SUM{[github_stars], CUMULATIVE([created_at])}',
          CalculatedColumnSettings: {
            DataType: 'number',
            Resizable: true,
            Width: 200,
          },
        },
        {
          ColumnId: 'cumul-language-stars-count',
          FriendlyName: 'Cumul Lang Stars',
          Expression: 'SUM{[github_stars], GROUP_BY([language]), CUMULATIVE([created_at])}',
          CalculatedColumnSettings: {
            DataType: 'number',
            Resizable: true,
            Width: 200,
          },
        },
      ],
    },
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'formatColumn-created_at',
          Scope: {
            ColumnIds: ['created_at'],
          },
          DisplayFormat: {
            Formatter: 'DateFormatter',
            Options: {
              Pattern: 'yyyy/MM/dd',
            },
          },
        },
        {
          Name: 'formatColumn-number',
          Scope: {
            DataTypes: ['number'],
          },
          DisplayFormat: {
            Formatter: 'NumberFormatter',
            Options: {
              IntegerSeparator: ',',
            },
          },
        },
      ],
    },
  },
};
```
