Averages

Learn to fetch the moving averages of securities.

Moving averages are critical technical indicators that help traders visualize securities trends. In this lesson, we’ll look at various endpoints for moving averages available in Polygon API.

Press + to interact
The moving averages endpoint
The moving averages endpoint

Simple moving average

A simple moving average (SMA) is the stock’s average price over a defined time period. It determines if a security is in an uptrend or a downtrend.

Press + to interact

The base URL for the SMA endpoint is as follows:

https://api.polygon.io/v1/indicators/sma/{Ticker}

This endpoint requires some mandatory and optional request parameters. An overview of these parameters is given in the table below:

Request Parameters

Name

Type

Category

Description

ticker

String

Mandatory

The ticker associated with the security whose SMA we want.

timestamp

String

Optional

The starting time of the aggregate window given in the YYYY-MM-DD format or in milliseconds.

timespan

String

Optional

The time span over which we want to calculate the average.

Accepted input: minute, hour, day, week, month, quarter, and year.

adjusted

Boolean

Optional

If this is set to false, the response is not adjusted for splits. By default, it is set to true.

window

Integer

Optional

The window size over which the SMA is calculated.

series_type

String

Optional

The type of price over which the SMA is calculated.

Accepted input: open, close, high, and low for opening, closing, highest, and lowest security prices, respectively.

expand_underlying

Boolean

Optional

If this is set to true, the aggregates used to calculate the SMA are included in the response object.

order

String

Optional

This will order the results according to timestamp.

Accepted input: asc and desc for ascending and descending, respectively.

limit

Integer

Optional

This is the number of results required in the response. By default, it is set to 10, and the max value is 1000.

Let’s try to call the SMA endpoint for a ticker, where SMA is calculated according to the highest prices of the security in the following code:

Press + to interact
// Importing libraries here
import fetch from "node-fetch";
// Define API key here
const apiKey = '{{API_KEY}}';
// Define endpoint URL here
const endpointUrl = new URL(`https://api.polygon.io/v1/indicators/sma/{{TICKER}}`);
// Define Header Parameters here
const headerParameters = {
authorization: `Bearer ${apiKey}`
};
// Define Query Parameters here
const queryParameters = new URLSearchParams({
series_type: 'high',
limit: '5'
});
// Setting API call options
const options = {
method: 'GET',
headers: headerParameters,
};
// Function to make API call
async function MovingAverage() {
try {
endpointUrl.search = queryParameters;
const response = await fetch(endpointUrl, options);
// Custom function for printing the API response
printResponse(response);
} catch (error) {
// Custom function for printing the error message
printError(error);
}
}
// Calling function to make API call
MovingAverage();

Here’s an explanation for the above code:

  • Line 8: We define the endpoint URL.

  • Lines 11–13: We define the API key in the header parameter.

  • Lines 16–19: We set the query parameters.

  • Lines 22–25: We define the options parameters and set the request type as GET.

  • Lines 28–39: We define the MovingAverage function, which calls the endpoint.

  • Line 42: We call the MovingAverage function.

Try to change the value of Ticker by clicking “Edit.” Also, play with the code by changing the query parameters.

Response Fields

Name

Type

Description

results

Object

This contains the results of our query, including the aggregate details and values array.

results.underlying

Object

This includes details about the ticker specified.

results.values

Array

This includes the value of the moving average and the timestamp used in the calculation of the moving average of the specified ticker.

status

String

The response status to our query.

request_id

String

The ID associated with our query.

next_url

String

The URL to the next page, if it exists.

Exponential moving average

Like the simple moving average, the exponential moving average (EMA) is used to calculate the average price of a security over a specific time period. However, in EMA, recent prices are given more weight during calculations.

The base URL for the EMA endpoint is as follows:

https://api.polygon.io/v1/indicators/ema/{Ticker}

The request and response parameters for the EMA endpoint are the same as the SMA endpoint. Let’s call the EMA endpoint below.

Press + to interact
// Importing libraries here
import fetch from "node-fetch";
// Define API key here
const apiKey = '{{API_KEY}}';
// Define endpoint URL here
const endpointUrl = new URL(`https://api.polygon.io/v1/indicators/ema/{{TICKER}}`);
// Define Header Parameters here
const headerParameters = {
authorization: `Bearer ${apiKey}`
};
// Define Query Parameters here
const queryParameters = new URLSearchParams({
timespan: "quarter",
order: "desc"
});
// Setting API call options
const options = {
method: 'GET',
headers: headerParameters,
};
// Function to make API call
async function MovingAverage() {
try {
endpointUrl.search = queryParameters;
const response = await fetch(endpointUrl, options);
// Custom function for printing the API response
printResponse(response);
} catch (error) {
// Custom function for printing the error message
printError(error);
}
}
// Calling function to make API call
MovingAverage();

Here’s an explanation for the above code:

  • Line 8: We define the endpoint URL for EMA.

  • Lines 16–19: We define the query parameters and set the timespan to quarter and order the results in descending order.

  • Lines 22–25: We define the options parameters and set the request type as GET.

  • Lines 28–39: We define the MovingAverage function, which calls the endpoint.

  • Line 42: We call the MovingAverage function.

Try to change the values of the request parameters by clicking “Edit.” Also, try to provide some additional parameters in the given code widget.

Moving average convergence and divergence

The moving average convergence and divergence (MACD) is a technical indicator that defines the relationship between two moving averages and the trend they follow.

The base URL for the MACD endpoint is as follows:

https://api.polygon.io/v1/indicators/macd/{Ticker}

An overview of the request parameters we can provide to the MACD endpoint is given in the table below.

Request Parameters

Name

Type

Category

Description

ticker

String

Mandatory

The ticker associated with the security whose SMA we want.

timestamp

String

Optional

The timestamp, given in YYYY-MM-DD format or in milliseconds.

timespan

String

Optional

The time span over which we want to calculate the average.

Accepted input: minute, hour, day, week, month, quarter, and year.

adjusted

Boolean

Optional

If this is set to false, the response is not adjusted for splits. By default, it is set to true.

short_window

Integer

Optional

The short window size over which the MACD is calculated.

long_window

Integer

Optional

The long window size over which the MACD is calculated.

signal_window

Integer

Optional

The window size over which the MACD signal line is calculated.

series_type

String

Optional

The type of price over which the MACD is calculated.

Accepted input: open, close, high, and low for opening, closing, highest, and lowest security prices, respectively.

expand_underlying

Boolean

Optional

If this is set to true, the aggregates used to calculate the MACD are included in the response object.

order

String

Optional

This will order the results according to timestamp.

Accepted input: asc and desc for ascending and descending, respectively.

limit

Integer

Optional

The number of results required in the response. By default, it is set to 10, and the max value is 1000.

Let’s try to call the MACD endpoint in the following code:

Press + to interact
// Importing libraries here
import fetch from "node-fetch";
// Define API key here
const apiKey = '{{API_KEY}}';
// Define endpoint URL here
const endpointUrl = new URL(`https://api.polygon.io/v1/indicators/macd/{{TICKER}}`);
// Define Header Parameters here
const headerParameters = {
authorization: `Bearer ${apiKey}`
};
// Define Query Parameters here
const queryParameters = new URLSearchParams({
timespan: 'minute',
limit: 15
});
// Setting API call options
const options = {
method: 'GET',
headers: headerParameters,
};
// Function to make API call
async function MACD() {
try {
endpointUrl.search = queryParameters;
const response = await fetch(endpointUrl, options);
// Custom function for printing the API response
printResponse(response);
} catch (error) {
// Custom function for printing the error message
printError(error);
}
}
// Calling function to make API call
MACD();

Here’s an explanation for the above code:

  • Line 8: We define the endpoint URL.

  • Lines 16–19: We set the query parameters.

  • Lines 22–25: We define the options parameters and set the request type as GET.

  • Lines 28–39: We define the MACD function, which calls the endpoint.

  • Line 42: We call the MACD function.

The attributes in the response object of MACD are similar to the response object of SMA and EMA. However, the results object includes some additional parameters. The following table contains details of these parameters.

Response Fields

Name

Type

Description

results.values.histogram

Integer

The MACD value minus the signal value.

results.values.signal

Integer

The EMA value of the asset over nine days.

results.values.timestamp

Integer

The timestamp (in milliseconds) starting from the previous aggregate window.

results.values.value

Integer

Thee MACD value of the asset specified.

Relative strength index

The relative strength index (RSI) is used to measure the change in the recent prices of a security. It lets us know if a security is overbought or oversold. Polygon API provides the RSI of a security over a specific time period.

The base URL for the RSI endpoint is as follows:

https://api.polygon.io/v1/indicators/rsi/{Ticker}

The request and response parameters of RSI are the same as those of SMA and EMA.

Let’s try to call this endpoint in the code widget given below:

Press + to interact
// Importing libraries here
import fetch from "node-fetch";
// Define API key here
const apiKey = '{{API_KEY}}';
// Define endpoint URL here
const endpointUrl = new URL(`https://api.polygon.io/v1/indicators/rsi/{{TICKER}}`);
// Define Header Parameters here
const headerParameters = {
authorization: `Bearer ${apiKey}`
};
// Define Query Parameters here
const queryParameters = new URLSearchParams({
adjusted: 'false',
window: 14,
series_tyoe: 'low',
limit: 5
});
// Setting API call options
const options = {
method: 'GET',
headers: headerParameters,
};
// Function to make API call
async function RSI() {
try {
endpointUrl.search = queryParameters;
const response = await fetch(endpointUrl, options);
// Custom function for printing the API response
printResponse(response);
} catch (error) {
// Custom function for printing the error message
printError(error);
}
}
// Calling function to make API call
RSI();

Here’s an explanation for the above code:

  • Line 8: We define the endpoint URL.

  • Lines 16–21: We set the query parameters.

  • Lines 30–41: We define the RSI function, which calls the endpoint.

  • Line 44: We call the RSI function.

Try to change the query parameters and click the “Run” button to see the change in values.