Package: kpytrends
pytrendsIntroductionUnofficial API for Google TrendsAllows simple interface for automating downloading of reports from Google Trends. Main feature is to allow the script to login to Google on your behalf to enable a higher rate limit. Only good until Google changes their backend again :-P. When that happens feel free to contribute!Looking for maintainers!Table of contensInstallationAPIAPI MethodsCommon API parametersInterest Over TimeHistorical Hourly InterestInterest by RegionRelated TopicsRelated QueriesTrending SearchesTop ChartsSuggestionsCaveatsCreditsInstallationpip install pytrendsRequirementsWritten for both Python 2.7+ and Python 3.3+Requires Requests, lxml, Pandasback to topAPIConnect to Googlefrom pytrends.request import TrendReq

pytrends = TrendReq(hl='en-US', tz=360)or if you want to use proxies as you are blocked due to Google rate limit:from pytrends.request import TrendReq

pytrends = TrendReq(hl='en-US', tz=360, timeout=(10,25), proxies=['https://34.203.233.13:80',], retries=2, backoff_factor=0.1)timeout(connect, read)Timezone OffsetFor example US CST is'360'proxieshttps proxies Google passed ONLYlist['https://34.203.233.13:80','https://35.201.123.31:880', ..., ...]retriesnumber of retries total/connect/read all represented by one scalarbackoff_factorA backoff factor to apply between attempts after the second try (most errors are resolved immediately by a second try without a delay). urllib3 will sleep for:{backoff factor} * (2 ^ ({number of total retries} - 1))seconds. If the backoff_factor is 0.1, then sleep() will sleep for [0.0s, 0.2s, 0.4s, …] between retries. It will never be longer than Retry.BACKOFF_MAX. By default, backoff is disabled (set to 0).Note: the parameterhlspecifies host language for accessing Google Trends.
Note: only https proxies will work, and you need to add the port number after the proxy ip addressBuild Payloadkw_list = ["Blockchain"]
pytrends.build_payload(kw_list, cat=0, timeframe='today 5-y', geo='', gprop='')Parameterskw_listRequiredKeywords to get data forback to topAPI MethodsThe following API methods are available:Interest Over Time: returns historical, indexed data for when the keyword was searched most as shown on Google Trends' Interest Over Time section.Historical Hourly Interest: returns historical, indexed, hourly data for when the keyword was searched most as shown on Google Trends' Interest Over Time section. It sends multiple requests to Google, each retrieving one week of hourly data. It seems like this would be the only way to get historical, hourly data.Interest by Region: returns data for where the keyword is most searched as shown on Google Trends' Interest by Region section.Related Topics: returns data for the related keywords to a provided keyword shown on Google Trends' Related Topics section.Related Queries: returns data for the related keywords to a provided keyword shown on Google Trends' Related Queries section.Trending Searches: returns data for latest trending searches shown on Google Trends' Trending Searches section.Top Charts: returns the data for a given topic shown in Google Trends' Top Charts section.Suggestions: returns a list of additional suggested keywords that can be used to refine a trend search.back to topCommon API parametersMany API methods use the following:kw_listkeywords to get data forExample['Pizza']Up to five terms in a list:['Pizza', 'Italian', 'Spaghetti', 'Breadsticks', 'Sausage']Advanced KeywordsWhen using Google Trends dashboard Google may provide suggested narrowed search terms.For example"iron"will have a drop down of"Iron Chemical Element, Iron Cross, Iron Man, etc".Find the encoded topic by using the get_suggestions() function and choose the most relevant one for you.For example:https://www.google.com/trends/explore#q=%2Fm%2F025rw19&cmpt=q"%2Fm%2F025rw19"is the topic "Iron Chemical Element" to use this with pytrendsYou can also usepytrends.suggestions()to automate this.catCategory to narrow resultsFind available cateogies by inspecting the url when manually using Google Trends. The category starts aftercat=and ends before the next&or view thiswiki page containing all available categoriesFor example:"https://www.google.com/trends/explore#q=pizza&cat=71"'71'is the categoryDefaults to no categorygeoTwo letter country abbreviationFor example United States is'US'Defaults to WorldMore detail available for States/Provinces by specifying additonal abbreviationsFor example: Alabama would be'US-AL'For example: England would be'GB-ENG'tzTimezone Offset (in minutes)For more information of Timezone Offset,view this wiki page containing about UCT offsetFor example US CST is'360'timeframeDate to start fromDefaults to last 5yrs,'today 5-y'.Everything'all'Specific dates, 'YYYY-MM-DD YYYY-MM-DD' example'2016-12-14 2017-01-25'Specific datetimes, 'YYYY-MM-DDTHH YYYY-MM-DDTHH' example'2017-02-06T10 2017-02-12T07'Note Time component is based off UTCCurrent Time Minus Time Pattern:By Month:'today #-m'where # is the number of months from that date to pull data forFor example:'today 3-m'would get data from today to 3months agoNOTEGoogle uses UTC date as'today'Seems to only work for 1, 2, 3 months onlyDaily:'now #-d'where # is the number of days from that date to pull data forFor example:'now 7-d'would get data from the last weekSeems to only work for 1, 7 days onlyHourly:'now #-H'where # is the number of hours from that date to pull data forFor example:'now 1-H'would get data from the last hourSeems to only work for 1, 4 hours onlygpropWhat Google property to filter toExample'images'Defaults to web searchesCan beimages,news,youtubeorfroogle(for Google Shopping results)back to topInterest Over Timepytrends.interest_over_time()Returns pandas.Dataframeback to topHistorical Hourly Interestpytrends.get_historical_interest(kw_list, year_start=2018, month_start=1, day_start=1, hour_start=0, year_end=2018, month_end=2, day_end=1, hour_end=0, cat=0, geo='', gprop='', sleep=0)Parameterskw_listRequiredlist of keywords that you would like the historical datayear_start, month_start, day_start, hour_start, year_end, month_end, day_end, hour_endthe time period for which you would like the historical datasleepIf you are rate-limited by Google, you should set this parameter to something (i.e. 60) to space off each API call.Returns pandas.Dataframeback to topInterest by Regionpytrends.interest_by_region(resolution='COUNTRY', inc_low_vol=True, inc_geo_code=False)Parametersresolution'CITY' returns city level data'COUNTRY' returns country level data'DMA'  returns Metro level data'REGION'  returns Region level datainc_low_volTrue/False (includes google trends data for low volume countries/regions as well)inc_geo_codeTrue/False (includes ISO codes of countries along with the names in the data)Returns pandas.DataFrameback to topRelated Topicspytrends.related_topics()Returns dictionary of pandas.DataFramesback to topRelated Queriespytrends.related_queries()Returns dictionary of pandas.DataFramesback to topTrending Searchespytrends.trending_searches(pn='united_states') # trending searches in real time for United States
pytrends.trending_searches(pn='japan') # JapanReturns pandas.DataFrameback to topTop Chartspytrends.top_charts(date, hl='en-US', tz=300, geo='GLOBAL')ParametersdateRequiredYYYY or YYYYMM integerExample201611for November 2016 Top Chart dataReturns pandas.DataFrameback to topSuggestionspytrends.suggestions(keyword)ParameterskeywordRequiredkeyword to get suggestions forReturns dictionaryback to topCategoriespytrends.categories()Returns dictionaryback to topCaveatsThis is not an official or supported APIGoogle may change aggregation level for items with very large or very small search volumeGoogle will send you an email saying that you had a new login after running this.Rate Limit is not publicly known, let me know if you have a consistent estimateOne user reports that 1,400 sequential requests of a 4 hours timeframe got them to the limit. (Replicated on 2 networks)It has been tested, and 60 seconds of sleep between requests (successful or not) is the correct amount once you reach the limit.For certain configurations the dependency lib certifi requires the environment variable REQUESTS_CA_BUNDLE to be explicitly set and exported. This variable must contain the path where the ca-certificates are saved or a SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] error is given at runtime.CreditsMajor JSON revision ideas taken from pat310's JavaScript libraryhttps://github.com/pat310/google-trends-apiConnecting to google code heavily based off Stack Overflow posthttp://stackoverflow.com/questions/6754709/logging-in-to-google-using-pythonWith some ideas pulled from Matt Reid's Google Trends APIhttps://bitbucket.org/mattreid9956/google-trend-api/overview