I have been using the below code to fetch the Google Trends data but constantly getting errors is there any way to do this and get the trends data which I want?
I tried using it with some third party apis its working fine the issue arises with google API trying to time out and I am running the code from collab.
# Install pytrends library if not already installed
# !pip install pytrends
import pandas as pd
import matplotlib.pyplot as plt
import time
from pytrends.request import TrendReq
# Initialize pytrends
pytrends = TrendReq(hl='en-US', tz=360)
# List of search terms
search_terms = [
"GBTC ETF", "GBTC price",
"Bitcoin ETF", "Ethereum ETF"
]
# Function to fetch and plot Google Trends data
def fetch_and_plot_trends(search_terms, time_frame='2010-01-01 2024-01-01', frequency='weekly'):
all_data = pd.DataFrame()
for term in search_terms:
try:
pytrends.build_payload([term], timeframe=time_frame)
data = pytrends.interest_over_time()
if 'isPartial' in data.columns:
data = data.drop(columns=['isPartial'])
data.rename(columns={term: 'search_score'}, inplace=True)
data['search_term'] = term
all_data = pd.concat([all_data, data])
# Adding a delay to avoid hitting rate limits
time.sleep(10)
except Exception as e:
print(f"An error occurred for term '{term}': {e}")
# Plot the data
plt.figure(figsize=(14, 8))
for term in search_terms:
term_data = all_data[all_data['search_term'] == term]
plt.plot(term_data.index, term_data['search_score'], label=term)
plt.title('Google Search Scores for Specified Terms')
plt.xlabel('Date')
plt.ylabel('Search Score')
plt.legend()
plt.grid(True)
plt.show()
# Fetch and plot the trends data
fetch_and_plot_trends(search_terms, time_frame='2010-01-01 2024-01-01', frequency='weekly')