SARIMAX predictions in 0

42 Views Asked by At

I am trying to fit 30 SARIMAX models, one for each pareto supplier. The data I have is missing some of the months but I'm making the program put them in 0. But all the other months do have an interesting variation. I'm trying to predict the same time of data that I have to check the variation between the models and reality but all my predictions go to 0, for all of the suppliers. I also tried making it one by one but I had the same results.

Here the code that I tried

df=pd.read_csv("./Insumos_Tablero_2/Pareto_Proveedores.csv")
Total=df.valor.sum()
df["Porcentaje"]=df.valor/Total
df2=df[["nombre_homologado","valor","Porcentaje","anio"]]
df2=df2[df2.anio.isin([2022,2023])]
df2=df2.drop("anio",axis=1)
df2=df2[["nombre_homologado","valor","Porcentaje"]].groupby("nombre_homologado").sum().reset_index()
df2=df2.sort_values("Porcentaje",ascending=False)
df2["Acumulado"]=df2.Porcentaje.cumsum()
df2=df2[df2["Acumulado"]<=0.85]
prov_pareto=df2["nombre_homologado"].head(30)
prov_pareto.reset_index(drop=True,inplace=True)
df=df.drop(['Porcentaje'],axis=1)
df_pareto = df[df['nombre_homologado'].isin(prov_pareto)]
def ajustar_y_predecir_autoarima(df_proveedor):
    df_proveedor['fecha'] = pd.to_datetime(df_proveedor['anio'].astype(str) + '-' + df_proveedor['mes'].astype(str) + '-01')

    df_proveedor = df_proveedor.sort_values(by='fecha').reset_index(drop=True)

    nombre = df_proveedor['nombre_homologado'][0]
    df_proveedor = df_proveedor.drop(['nombre_homologado', 'anio', 'mes'], axis=1)
    df_proveedor = df_proveedor.set_index('fecha')

    fecha_inicial = df_proveedor.index.min()
    fecha_final = df_proveedor.index.max()
    rango_fechas = pd.date_range(start=fecha_inicial, end=fecha_final, freq='MS')
    df_proveedor = df_proveedor.reindex(rango_fechas, fill_value=0)

    modelo = auto_arima(df_proveedor['valor'], seasonal=True, m=12, stepwise=True, trace=True,
                        error_action='ignore', suppress_warnings=True,
                        max_order=None, seasonal_test='ocsb')

    mejor_p, mejor_d, mejor_q = modelo.order
    mejor_P, mejor_D, mejor_Q, mejor_m = modelo.seasonal_order

    print(f"Mejores parámetros encontrados: ({mejor_p}, {mejor_d}, {mejor_q})x({mejor_P}, {mejor_D}, {mejor_Q}, {mejor_m})")

    mejor_modelo = SARIMAX(df_proveedor['valor'], order=(mejor_p, mejor_d, mejor_q),
                           seasonal_order=(mejor_P, mejor_D, mejor_Q, mejor_m))
    resultado = mejor_modelo.fit()

    inicio_prediccion = df_proveedor.index[0]
    fin_prediccion = df_proveedor.index[-1]
    predicciones = resultado.predict(start=inicio_prediccion, end=fin_prediccion, dynamic=True)

    df_resultado = pd.DataFrame({
        'proveedor': [nombre] * len(predicciones),
        'fecha': predicciones.index,
        'valor_real': df_proveedor['valor'],
        'valor_prediccion': predicciones.values,
        'parametros': [f"SARIMA({mejor_p},{mejor_d},{mejor_q})x({mejor_P},{mejor_D},{mejor_Q},{mejor_m})"]* len(predicciones)
    })

    return df_resultado

resultados = []

for proveedor in prov_pareto:
    df_proveedor = df[df['nombre_homologado'] == proveedor].copy()  # Copia el DataFrame para evitar sobrescribirlo
    resultado = ajustar_y_predecir_autoarima(df_proveedor)
    resultados.append(resultado)

df_resultados = pd.concat(resultados, ignore_index=True)

df_resultados

0

There are 0 best solutions below