Overview

The get_historical_interest() function in the pytrends library allows you to retrieve hourly interest data for specific search terms within a given time frame. This can be useful for gaining a more granular understanding of search term popularity and for identifying trends that may not be visible when looking at daily or weekly data.

In this tutorial, we will cover:

  1. Importing the necessary libraries
  2. Setting up the pytrends request
  3. Retrieving historical hourly interest data
  4. Visualizing the results

Installation

To install Pytrends, simply use pip:

pip install matplotlib

Retrieve Historical Hourly Interest Data

To start, we need to import the necessary libraries and set up our pytrends request.

from pytrends.request import TrendReq
import pandas as pd
import matplotlib.pyplot as plt

# Set up pytrends request
pytrends = TrendReq(hl='en-US', tz=360)

Next, we’ll specify the search terms, time range, and other parameters for our request using the get_historical_interest() function.

keywords = ['Python', 'JavaScript']

# Retrieve hourly interest data
hourly_interest = pytrends.get_historical_interest(keywords, year_start=2023, month_start=3, day_start=1, hour_start=0, year_end=2023, month_end=3, day_end=2, hour_end=0, cat=0, geo='', gprop='', sleep=0)

This will return a DataFrame containing hourly interest data for the search terms ‘Python’ and ‘JavaScript’ from March 1st to March 2nd, 2023.

Visualizing the Results

Now, we can visualize the hourly interest data using a simple line plot.

# Plot the hourly interest data
plt.figure(figsize=(12, 6))
plt.plot(hourly_interest.index, hourly_interest['Python'], label='Python')
plt.plot(hourly_interest.index, hourly_interest['JavaScript'], label='JavaScript')

plt.xlabel('Hour')
plt.ylabel('Interest')
plt.title('Hourly Interest for Python and JavaScript')
plt.legend()
plt.show()

This plot shows the hourly interest for both ‘Python’ and ‘JavaScript’ over the specified time frame, allowing you to compare their popularity and identify trends.

Conclusion

In this post, we’ve demonstrated how to use the get_historical_interest() function in the pytrends library to retrieve historical hourly interest data from Google Trends. By diving into this data, you can gain valuable insights into the popularity of search terms and better understand consumer behavior. This tutorial has covered the process of collecting and analyzing hourly interest data, from setting up the pytrends request to visualizing the results.


NOTE : pytrends uses an unofficial API. Please use here for issues.

SAMPLE CODE : https://github.com/hobbyworker/google-trend-for-python