Skip to content
TheChatArchiveThe Chat Archive
Amazon Novaamazon.nova-pro-v1:0· AmazonHugging Face LMArena Human Preference 140K

write a code in python to find multi seasonality patterns in time series. time series…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Geminigemini-2.5-flash’s answer.
  1. User

    write a code in python to find multi seasonality patterns in time series. time series can be non stationary. there are too many time series for visual analysis

  2. Amazon Nova Assistant

    To find multi-seasonality patterns in a time series, especially when dealing with non-stationary data and a large number of series, you can use a combination of statistical methods and machine learning techniques. One effective approach is to use the statsmodels library for statistical analysis and the fbprophet library for time series forecasting, which can handle multiple seasonalities.

    Here's a Python code example that demonstrates how to identify and model multi-seasonality in time series data:

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    from statsmodels.tsa.seasonal import seasonal_decompose
    from fbprophet import Prophet
    import pmdarima as pm
    
    # Generate sample time series data with multiple seasonalities
    np.random.seed(42)
    date_range = pd.date_range(start='1/1/2020', periods=365*3, freq='D')
    data = pd.DataFrame(date_range, columns=['ds'])
    data['y'] = 10 + 5 * np.sin(2 * np.pi * (data.index.day / 365)) +  # Yearly seasonality
             3 * np.sin(2 * np.pi * (data.index.day / 7)) +  # Weekly seasonality
             np.random.normal(scale=2, size=len(data))  # Noise
    
    # Seasonal Decomposition to identify seasonality
    result = seasonal_decompose(data['y'], model='additive', period=365)
    result.plot()
    plt.show()
    
    # Using FBProphet to model multiple seasonalities
    prophet_model = Prophet(yearly_seasonality=True, weekly_seasonality=True)
    prophet_model.fit(data)
    future = prophet_model.make_future_dataframe(periods=365)
    forecast = prophet_model.predict(future)
    prophet_model.plot(forecast)
    plt.show()
    
    # Using auto_arima to find the best ARIMA model
    arima_model = pm.auto_arima(data['y'], seasonal=True, m=365, 
                                trace=True, error_action='ignore', suppress_warnings=True)
    print(arima_model.summary())
    
    # Forecasting with the best ARIMA model
    n_periods = 365
    forecast, conf_int = arima_model.predict(n_periods=n_periods, return_conf_int=True)
    index_of_fc = pd.date_range(data['ds'].iloc[-1], periods=n_periods, freq='D', closed='right')
    
    # Plotting the forecast
    plt.figure(figsize=(10, 5))
    plt.plot(data['ds'], data['y'], label='Historical')
    plt.plot(index_of_fc, forecast, label='Forecast')
    plt.fill_between(index_of_fc, conf_int[:, 0], conf_int[:, 1], color='k', alpha=0.2)
    plt.xlabel('Date')
    plt.ylabel('Value')
    plt.legend()
    plt.show()
    

    Explanation:

    1. Data Generation:

      • A sample time series with yearly and weekly seasonality is generated.
    2. Seasonal Decomposition:

      • seasonal_decompose from statsmodels is used to decompose the time series into trend, seasonal, and residual components.
    3. FBProphet:

      • Prophet is used to model the time series with specified seasonalities (yearly and weekly).
    4. ARIMA Modeling:

      • auto_arima from pmdarima is used to find the best ARIMA model for the time series.
    5. Forecasting:

      • Both Prophet and the best ARIMA model are used to forecast future values, and the results are plotted.

    This approach allows you to identify and model multi-seasonality patterns in non-stationary time series data efficiently.

  3. User

    consider that data aggregated by weeks. output should contain significant lags detected in series

  4. Amazon Nova Assistant

    To detect significant lags in a time series aggregated by weeks, you can use the statsmodels library to perform an autocorrelation analysis. The plot_acf function from statsmodels.graphics.tsaplots can help visualize the autocorrelation at different lags, and you can use the acf function to get the actual autocorrelation values.

    Here's a Python code example that demonstrates how to detect significant lags in a weekly aggregated time series:

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    from statsmodels.graphics.tsaplots import plot_acf
    from statsmodels.tsa.stattools import acf
    
    # Generate sample weekly aggregated time series data with multiple seasonalities
    np.random.seed(42)
    date_range = pd.date_range(start='1/1/2020', periods=52*3, freq='W')  # 3 years of weekly data
    data = pd.DataFrame(date_range, columns=['ds'])
    data['y'] = 10 + 5 * np.sin(2 * np.pi * (data.index / 52)) +  # Yearly seasonality (52 weeks in a year)
             3 * np.sin(2 * np.pi * (data.index / 13)) +  # Quarterly seasonality (13 weeks in a quarter)
             np.random.normal(scale=2, size=len(data))  # Noise
    
    # Plot ACF to visualize significant lags
    plot_acf(data['y'], lags=52)  # Plotting up to 52 lags to cover yearly seasonality
    plt.show()
    
    # Calculate ACF values
    acf_values = acf(data['y'], nlags=52)
    
    # Determine significant lags using a threshold (e.g., 2/sqrt(n))
    n = len(data)
    threshold = 2 / np.sqrt(n)
    significant_lags = [(lag, corr) for lag, corr in enumerate(acf_values) if np.abs(corr) > threshold]
    
    print("Significant Lags:")
    for lag, corr in significant_lags:
        print(f"Lag: {lag}, Correlation: {corr:.2f}")
    
    # Output the significant lags
    significant_lags_df = pd.DataFrame(significant_lags, columns=['Lag', 'Correlation'])
    print(significant_lags_df)
    

    Explanation:

    1. Data Generation:

      • A sample weekly aggregated time series with yearly and quarterly seasonality is generated.
    2. Plot ACF:

      • plot_acf from statsmodels.graphics.tsaplots is used to visualize the autocorrelation at different lags.
    3. Calculate ACF Values:

      • acf from statsmodels.tsa.stattools is used to calculate the autocorrelation values for the time series.
    4. Determine Significant Lags:

      • A threshold is calculated using 2 / sqrt(n) to determine significant lags.
      • Lags with autocorrelation values exceeding this threshold are considered significant.
    5. Output Significant Lags:

      • The significant lags are printed and stored in a DataFrame for further analysis.

    This approach allows you to identify and output the significant lags in a weekly aggregated time series.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.