> For the complete documentation index, see [llms.txt](https://docs.predicthq.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.predicthq.com/getting-started/guides/events-api-guides/filtering-and-finding-relevant-events.md).

# Filtering and finding relevant events

Learn how to filter and find events relevant to your business using PredictHQ's Events API.

Events such as concerts, expos, and public holidays can shift consumer behavior and [impact demand](https://www.predicthq.com/use-cases/demand-forecasting). Understanding which events are most relevant to a store or location is therefore critical for effective planning and management. By staying ahead of these events, businesses can better prepare for changes in consumer traffic and purchasing patterns, ensuring optimal staffing and inventory levels.

This tutorial will walk through the [Events API](https://www.predicthq.com/apis/event-api) while exploring an example involving a pizzeria interested in identifying major upcoming events. The goal is to learn how to effectively define query parameters, make API calls, and interpret responses.

To monitor upcoming events around your stores or locations without writing queries, use [Saved Locations](https://www.predicthq.com/tools/webapp/saved-locations). In [WebApp](https://control.predicthq.com/location-insights), set up a location to get immediate insights for all created locations. You can also do this securely and at scale from your own environment with the [Saved Locations API](https://docs.predicthq.com/api/saved-locations/overview.md).

## Getting started

A valid access token is required for calling PredictHQ’s APIs. Refer to the [API quickstart](https://docs.predicthq.com/getting-started/api-quickstart.md) for guidance on creating an access token and test our APIs with our [API Explorer](https://control.predicthq.com/explorer/events).

## Scenario

Let's take a fictional example: Tom, the owner of Tom’s Pizzeria in Downtown Seattle, Washington, has experienced overwhelming demand on several occasions, resulting in long lines and significant service delays. Suspecting nearby events were the cause of these surges, he sought to better prepare by identifying upcoming major events. To achieve this, Tom is looking into PredictHQ’s Events API to see how he can obtain this information for the next month.

## How-to guide

The following sections guide you through identifying the top 50 upcoming events near Tom’s Pizzeria over the next month. Follow the steps and code snippets to understand how this can be adapted to fit other business scenarios.

### Step 1. Define query parameters for the Events API

Given the volume of events happening all the time, choosing the right query parameters is crucial for identifying relevant events. The next section outlines the most commonly used parameters from the [Events API](https://docs.predicthq.com/api/events/search-events.md), providing guidance on how to use them along with Tom’s choices:

<details>

<summary>Date range</summary>

To set the date range for the search, use one of these parameters:

* **Active**: To include all events that are ongoing in the date range, use the `active` parameter.
* **Start**: To focus on the start dates of events, set the date range with the `start` parameter.

**Settings for Tom’s Pizzeria**

Tom is interested in events taking place in the month of June 2024. He will configure the search to include active events from June 1st to June 30th, considering the local time zone:

```python
params={
   "active.gte": "2024-06-01",
   "active.lte": "2024-06-30",
   "active.tz": "America/Los_Angeles"
   }
```

</details>

<details>

<summary>Location type</summary>

Define the catchment area for the search. Refer to our [industry recommendations](https://docs.predicthq.com/getting-started/guides/industry-specific-event-filters.md#location-type) for which location type to start with:

* **Saved Location (Recommended)**: Create a [Saved Location](https://docs.predicthq.com/api/saved-locations/overview.md) for each of your business locations. When you create one from a lat/lon origin, PredictHQ automatically calculates the [Predicted Impact Area](https://docs.predicthq.com/api/impact-area/get-impact-area.md) and stores it as the location boundary. You can then use `saved_location.location_id` in Events API, Features API, and Beam queries, with no manual boundary management needed.
* **Center Point & Radius**: For a search without a Saved Location, use the `within` parameter with lat/lon and a radius. To get an appropriate radius for your location and industry rather than guessing, use the [Predicted Impact Area API](https://docs.predicthq.com/api/impact-area/get-impact-area.md) with `area_type=radius`.
* **City, State, Country**: For targeted searches across a predefined area e.g. specific cities, states, or countries, use the `place` parameter and provide a place ID. The [Places API](https://docs.predicthq.com/api/places/search-places) can assist in finding correct place IDs.
* **Country-wide**: If your interest spans an entire country, use the `country` parameter and set it to the relevant ISO country code.

**Settings for Tom’s Pizzeria**

Tom creates a Saved Location for his pizzeria at (47.60, -122.33) in the `restaurants` industry. PredictHQ calculates Predicted Impact Area automatically when Tom creates the location, defining the polygon boundary where event-driven demand impact actually occurs for his location. Tom then queries events using `saved_location.location_id`, with no separate area lookup needed:

```python
params={
  "saved_location.location_id": "<location_id>",
  "category": "concerts,sports,festivals,community,performing-arts",
  "state": "active,predicted"
}
```

</details>

<details>

<summary>Event type</summary>

Select the types of events for the search:

* **Relevant Event Categories**: To identify [event categories](https://docs.predicthq.com/getting-started/predicthq-data/event-categories.md) that are most relevant to your location, use [Beam](https://docs.predicthq.com/getting-started/core-concepts/what-is-beam.md) in the [WebApp](https://control.predicthq.com/beam) or the [Beam API](https://docs.predicthq.com/api/beam/overview.md). Alternatively, start with our [industry recommendations](https://docs.predicthq.com/getting-started/guides/industry-specific-event-filters.md#relevant-event-categories) for which categories to start with.
* **Specific Themes**: To focus on particular themes within a category, use the `phq_label` parameter. For example, to find baseball-related events, set `phq_label` to `baseball`.

**Settings for Tom’s Pizzeria**

For a broad initial survey of upcoming events, Tom has chosen to focus on categories that are likely to influence restaurant visits:

```python
params={
  "category": "public-holidays,performing-arts,conferences,concerts,festivals"
  } 
```

Next, Tom plans to use Beam in the [WebApp](https://control.predicthq.com/beam) to help refine these categories further based on actual data-driven insights, tailored to his pizzeria.

</details>

<details>

<summary>Event impact</summary>

Define the event impact for the search:

* **PHQ Rank**: To target events based on their [predicted impact](https://docs.predicthq.com/getting-started/predicthq-data/ranks/phq-rank.md), use the `rank` parameter, with values ranging from 0 to 100. This is useful for filtering out smaller events, ensuring focus on those likely to impact demand. To set the minimum rank threshold, set `rank.gte` based on our [recommended industry minimums](https://docs.predicthq.com/getting-started/guides/industry-specific-event-filters.md#minimum-phq-rank).
  * The `rank_level` parameter divides the PHQ Rank into five equal bands, for simplified categorization. Levels range from 1 to 5, where 1 represents minor impact, such as a community workshop, and 5 represents major impact, like the Olympics.
* **Local Rank**: To consider the event's impact on the local area, use `local_rank`, which also ranges from 0 to 100. By considering factors like population density, [Local Rank](https://docs.predicthq.com/getting-started/predicthq-data/ranks/local-rank.md) helps differentiate the impact of similar-sized events in different locations, such as Aspen, Colorado versus New York City.
  * The `local_rank_level` parameter divides Local Rank into five equal bands, for simplified categorization. Levels also range from 1 to 5, with 1 representing minor impact and 5 representing major impact, similar to the PHQ Rank.
* **Predicted Attendance**: For [attendance-based events](https://docs.predicthq.com/getting-started/predicthq-data/event-categories/attendance-based-events.md), impact can be directly measured with `phq_attendance` which is the [number of people predicted to attend an event](https://docs.predicthq.com/getting-started/predicthq-data/predicted-attendance.md).

**Settings for Tom’s Pizzeria**

To focus his resources efficiently and avoid spending time on smaller, less impactful events, Tom sets a minimum PHQ Rank threshold of 30, which is recommended for his industry:

```python
params={
  "rank.gte": 30
  }
```

</details>

<details>

<summary>Event state</summary>

Track events based on their likelihood of occurring:

* **Event state**: Events with the `active` state have confirmed details including start dates and locations, whereas the details of \`predicted\` events are [subject to change](https://docs.predicthq.com/getting-started/predicthq-data/predicted-events.md) as more information becomes available. PredictHQ marks events as `deleted` if they are canceled, postponed, or otherwise removed.

Focusing primarily on `active` and `predicted` event states ensures that only events which are relevant and likely to occur are tracked

**Settings for Tom’s Pizzeria**

Tom is interested in all upcoming events in June 2024 and has decided to include `predicted` events as well:

```python
params={
  "state": "active,predicted"
  }
```

</details>

<details>

<summary>Query modifiers</summary>

Optimize search results with these parameters:

* **Limit**: Specify the maximum number of events per page to return, managing the volume of results and focusing on the most relevant events. To navigate to additional results, use the `next` field in the API response (refer to [#handling-paginated-api-responses](#handling-paginated-api-responses "mention") for more details).
* **Sort**: Order the search results according to specific attributes, most commonly event impact such as `rank` or `phq_attendance`, to prioritize high impact events.

**Settings for Tom’s Pizzeria**

Tom is interested in the top 50 upcoming events for June 2024 that could impact his business. He sets the search parameters to not only manage the scope of results but also ensure that the most significant events are returned first:

```python
params={
   "limit": 50,
   "sort": "rank"
   }
```

</details>

{% hint style="info" %}
For detailed information on all query parameters (including those not shown here), consult [Events API](https://docs.predicthq.com/api/events/search-events.md).
{% endhint %}

### Step 2. Call Events API

With the query parameters configured, call the Events API. This can be done using our [API Explorer](https://control.predicthq.com/explorer/events) or via your preferred tool. The following is an example of Tom's request using Python:

```python
import requests

base_url = "https://api.predicthq.com/v1/events"

headers = {
    "Authorization": "Bearer $API_TOKEN",  # Replace $API_TOKEN with your actual token
    "Accept": "application/json"
}

params = {
    "saved_location.location_id": "<location_id>",  # Use the location_id from the Saved Location created in Step 1
    "category": "public-holidays,school-holidays,conferences,concerts,performing-arts",
    "active.gte": "2024-06-01",
    "active.lte": "2024-06-30",
    "rank.gte": 30,
    "limit": 50,
    "sort": "rank",
    "state": "active,predicted"
}

response = requests.get(base_url, headers=headers, params=params)
if response.status_code == 200:
    print(response.json())
else:
    print(f"Error fetching response: {response.status_code}")
```

#### Handling paginated API responses

The Events API responses come in a paginated format to limit the amount of data sent in a single response. Here's how you can automatically loop through the paginated API responses to collect all available results:

```python
def fetch_all_pages(base_url=base_url, headers=headers, params=params):
    results = []
    next_url = base_url  # Start with the base URL

    while next_url:
        response = requests.get(next_url, headers=headers, params=params)
        params = None  # After the first request, prevent re-sending initial parameters
        if response.status_code == 200:
            data = response.json()
            results.extend(data['results'])
            next_url = data.get('next')  # Update the next_url from the 'next' field in the response
        else:
            print(f"Failed to fetch data: {response.status_code}, Message: {response.text}")
            break

    return results

all_events = fetch_all_pages()
print("Total events fetched:", len(all_events))

```

For information on how to search for events using our SDK, refer to [Python SDK](https://docs.predicthq.com/sdks/python-sdk.md)

{% hint style="info" %}
For more details, visit:

* [Search events](https://docs.predicthq.com/api/events/search-events.md)
* [Python SDK](https://docs.predicthq.com/sdks/python-sdk.md)
  {% endhint %}

### Step 3. Interpret the response

After you call the API, the Events API returns a structured JSON response containing detailed information about the events that match the query parameters. The following is an illustrative example of what the first page of this response might look like, demonstrating initial pagination details and a sample event listing:

<details>

<summary>Example response</summary>

```json
{
  "count": 388,
  "overflow": false,
  "next": "https://api.predicthq.com/v1/events/?active.gte=2024-06-01&active.lte=2024-06-30&category=public-holidays%2Cschool-holidays%2Cconferences%2Cconcerts%2Cperforming-arts&limit=50&offset=50&rank.gte=30&saved_location.location_id=%3Clocation_id%3E&sort=rank&state=active%2Cpredicted",
  "previous": null,
  "results": [
    {
      "relevance": null,
      "id": "4hFctf3GqQ2MS5qYLW",
      "title": "Itzy",
      "alternate_titles": [
        "ITZY 2ND WORLD TOUR 'BORN TO BE'",
        "ITZY at WAMU Theater",
        "Itzy (Concert)"
      ],
      "description": "",
      "category": "concerts",
      "labels": [
        "concert",
        "music"
      ],
      "rank": 62,
      "local_rank": 77,
      "phq_attendance": 4201,
      "entities": [
        {
          "entity_id": "hckgG3yNMg5PRGsL49pNzK",
          "name": "ITZY",
          "type": "organization"
        },
        {
          "entity_id": "3AedBWTgigZjWx9NhwLsvgU",
          "name": "CenturyLink Field - WaMu Theater",
          "type": "venue",
          "formatted_address": "800 Occidental Avenue South\nSeattle, WA 98134\nUnited States of America"
        }
      ],
      "duration": 0,
      "start": "2024-06-07T03:00:00Z",
      "start_local": "2024-06-06T20:00:00",
      "end": "2024-06-07T03:00:00Z",
      "end_local": "2024-06-06T20:00:00",
      "predicted_end": "2024-06-07T07:10:00Z",
      "predicted_end_local": "2024-06-07T00:10:00",
      "updated": "2024-05-15T18:25:53Z",
      "first_seen": "2024-01-26T02:32:24Z",
      "timezone": "America/Los_Angeles",
      "location": [
        -122.3322862,
        47.5933082
      ],
      "geo": {
        "geometry": {
          "coordinates": [
            -122.3322862,
            47.5933082
          ],
          "type": "Point"
        },
        "placekey": "zzw-223@5x4-4vs-mp9"
      },
      "impact_patterns": [
        {
          "vertical": "accommodation",
          "impact_type": "phq_attendance",
          "impacts": [
            {
              "date_local": "2024-06-05",
              "value": 841,
              "position": "leading"
            },
            {
              "date_local": "2024-06-06",
              "value": 4201,
              "position": "event_day"
            },
            {
              "date_local": "2024-06-07",
              "value": 421,
              "position": "lagging"
            }
          ]
        },
        {
          "vertical": "hospitality",
          "impact_type": "phq_attendance",
          "impacts": [
            {
              "date_local": "2024-06-04",
              "value": 85,
              "position": "leading"
            },
            {
              "date_local": "2024-06-05",
              "value": 1051,
              "position": "leading"
            },
            {
              "date_local": "2024-06-06",
              "value": 4201,
              "position": "event_day"
            },
            {
              "date_local": "2024-06-07",
              "value": 127,
              "position": "lagging"
            }
          ]
        }
      ],
      "scope": "locality",
      "country": "US",
      "place_hierarchies": [
        [
          "6295630",
          "6255149",
          "6252001",
          "5815135",
          "5799783",
          "7174408",
          "5809844"
        ]
      ],
      "state": "active",
      "private": false,
      "predicted_event_spend": 325046,
      "predicted_event_spend_industries": {
        "accommodation": 77435,
        "hospitality": 188904,
        "transportation": 58707
      },
      "phq_labels": [
        {
          "label": "pop",
          "weight": 0.53
        },
        {
          "label": "other",
          "weight": 0.47
        }
      ]
    },
    {
      // More results...
    }
  ]
}
```

</details>

#### Key response fields

<details>

<summary>Pagination</summary>

The Events API returns results in a paginated format, where your subscription limits determine the number of events per page. The key fields related to pagination include:

* `count`: The total number of events that match the search criteria.
* `next` and `previous`: URLs that can be used to navigate to the next or previous pages of results, respectively.
* `overflow`: If `true`, this indicates more results are available but cannot be reached through normal pagination due to subscription limits. To reduce the number of results returned, make your search query more specific.

For more comprehensive guidelines on navigating paginated results, refer to [Pagination](https://docs.predicthq.com/api/overview/pagination.md).

</details>

<details>

<summary>Events</summary>

The response lists events in the results section, each as a JSON block. The amount of information provided for each event can vary depending on the type of event and other factors. A comprehensive guide that covers each available field can be found in [Search events](https://docs.predicthq.com/api/events/search-events.md). Common response fields include:

**Dates**:

* `start_local`, `end_local`: Indicates the start and end dates of the event in the local time zone. If an end date is not available, it defaults to the start date. For some events where the end date is not available, a [Predicted End Time](https://docs.predicthq.com/getting-started/predicthq-data/predicted-end-times.md) fills this gap with `predicted_end_local`.
* `start`, `end`, `predicted_end`: Indicates the start, end, and predicted end dates in UTC.

**Location**:

* `geo`: Includes the latitude/longitude coordinates of the event as well as additional location information which is especially useful for events that cover an area rather than a point (see [working with polygons](https://docs.predicthq.com/getting-started/guides/geolocation-guides/working-with-polygons.md)), such as parades.
* `place_hierarchies`: Lists the [place IDs](https://docs.predicthq.com/getting-started/guides/geolocation-guides/understanding-place-hierarchies.md) associated with the event location.
* `country`: Identifies the country where the event takes place.

**Event descriptors**:

* `title`: The name of the event.
* `description`: A brief description of what the event entails, if available.
* `category`: The [type of event](https://docs.predicthq.com/getting-started/predicthq-data/event-categories.md), such as concerts or public holidays.
* `phq_labels`: [Tags](https://docs.predicthq.com/getting-started/predicthq-data/labels.md) that classify the event into common themes or topics. Note, `labels` is a legacy field that isn't maintained.

**Event impact**:

* `rank`: The [predicted impact](https://docs.predicthq.com/getting-started/predicthq-data/ranks/phq-rank.md) of the event based on a globally comparable rank index.
* `local_rank`: The [predicted impact](https://docs.predicthq.com/getting-started/predicthq-data/ranks/local-rank.md) of the event, taking into account the local area.
* `phq_attendance`: The number of people [predicted to attend](https://docs.predicthq.com/getting-started/predicthq-data/predicted-attendance.md) the event, for [attendance-based events](https://docs.predicthq.com/getting-started/predicthq-data/event-categories/attendance-based-events.md).
* `impact_patterns`: The [predicted impact](https://docs.predicthq.com/getting-started/predicthq-data/impact-patterns.md) of how the event affects various industries on days surrounding the event.
* `predicted_event_spend`: The [predicted financial impact](https://docs.predicthq.com/getting-started/predicthq-data/predicted-event-spend.md) of the event on local businesses.

</details>

{% hint style="info" %}
For more details, visit:

* [Pagination](https://docs.predicthq.com/api/overview/pagination.md)
* [Search events](https://docs.predicthq.com/api/events/search-events.md)
* [Working with dates, times and timezones](https://docs.predicthq.com/getting-started/guides/date-and-time-guides/working-with-dates-times-and-timezones.md)
* [PredictHQ data](https://docs.predicthq.com/getting-started/predicthq-data.md)
  {% endhint %}

## Next steps

With a clear view of upcoming events, Tom plans to leverage this information for various analytical and operational improvements at his Pizzeria:

* **Data Analysis and Reporting**: Tom will load event data into Power BI to generate detailed reports and dashboards, following [Using event data in Power BI](https://docs.predicthq.com/integrations/third-party-integrations/using-event-data-in-power-bi.md) for step-by-step instructions.
* **Relevant Events**: Tom aims to pinpoint event categories that impact his business the most by using [Beam](https://docs.predicthq.com/api/beam/overview.md) in the [WebApp](https://control.predicthq.com/beam). This helps him allocate his resources more effectively.
* **Forecast Future Orders**: Recognizing the benefits of predictive analytics, Tom is considering developing a demand forecasting model using [Power BI’s AutoML feature with PredictHQ’s event data](https://docs.predicthq.com/getting-started/guides/features-api-guides/integrate-with-a-demand-forecast-in-powerbi.md). This helps predict customer flows and optimize resource planning.

## Conclusion

This tutorial has demonstrated how to effectively use the Events API to filter out noise and identify events that are most relevant to your business. From configuring query parameters to interpreting the responses, you now have the tools to make informed decisions and strategically plan for future opportunities.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.predicthq.com/getting-started/guides/events-api-guides/filtering-and-finding-relevant-events.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
