Untitled

 avatar
unknown
plain_text
2 years ago
1.8 kB
3
Indexable
def get_peaks(kw, geo='IN', timeframe='today 5-y'):
    """
    A function to get the trend for a keyword and to spot when peaks happen.

    Notes
    -----
    This func uses pytrends, an unofficial API for Google Trends

    .. _Pytrends Repo/Docs
        https://github.com/GeneralMills/pytrends

    Parameters
    ----------
    kw : str
        A search term.
    geo : str
        A two-letters string representing a country.
        Default: US
    timeframe : str
        A string representing the timeframe.
        Default: last 3 years.

        Nice timeframes to know:
        * Last 3 years: 'today 3-y'
        * Everything: 'all'
    """
    from pytrends.request import TrendReq
    pytrend = TrendReq()

    pytrend.build_payload(kw_list=[kw], timeframe=timeframe, geo=geo)
    df =pytrend.interest_over_time()
    df.drop(columns='isPartial', inplace=True)
    df = df.resample('M').mean()
    # line chart on resampled DF
    df.plot(figsize=(20,3))
    # bar chart on resampled DF
    df.plot.bar(figsize=(20,3))
    time_series = df[kw]
    cb = np.array(time_series)
    indices = peakutils.indexes(cb, thres=0.60, min_dist=0.1)
    months = []
    for i in indices:
        month = time_series.index[i].to_pydatetime().month
        val = int(time_series.iloc[i])
        months.append(MONTHS[month])
    print("===PEAK MONTHS===")
    sleep=60
    print(Counter(months).most_common(3))
    #Uncomment the following lines if you want rising queries
    #print("===RISING QUERIES===")
    #print(pytrend.related_queries()[kw]['rising'])

    #Uncomment the following lines if you want top queries
    #print("===TOP QUERIES===")
    #print(pytrend.related_queries()[kw]['top'])
Editor is loading...
Leave a Comment