Arko007's picture
Add Apple Price Prediction Model: Prophet+ARIMA hybrid ensemble
7e2d89c verified
"""
Apple Price Prediction Model - Inference Script
Indian Market | Prices in INR (β‚Ή) per kg
Hybrid Prophet + ARIMA Ensemble
"""
import os
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
import joblib
from datetime import datetime, timedelta
# Paths
_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
_PROPHET_PATH = os.path.join(_BASE_DIR, 'models', 'prophet_model.pkl')
_ARIMA_PATH = os.path.join(_BASE_DIR, 'models', 'arima_model.pkl')
_SCALER_PATH = os.path.join(_BASE_DIR, 'models', 'scaler.pkl')
# Lazy-loaded singletons
_prophet_model = None
_arima_model = None
_scaler = None
def _load_models():
global _prophet_model, _arima_model, _scaler
if _prophet_model is None:
_prophet_model = joblib.load(_PROPHET_PATH)
if _arima_model is None:
_arima_model = joblib.load(_ARIMA_PATH)
if _scaler is None:
_scaler = joblib.load(_SCALER_PATH)
def _storage_cost_inr(days: int) -> float:
"""
Indian cold-storage rate: β‚Ή0.75/kg/day.
Returns total storage cost for given number of days.
"""
return days * 0.75
def predict_price(input_features: dict) -> dict:
"""
Predict apple wholesale price 7 days ahead and recommend
whether to SELL now or STORE for higher future returns.
Parameters
----------
input_features : dict
Required:
current_price (float) Current wholesale price in β‚Ή/kg
Optional:
date (str) 'YYYY-MM-DD' (default: today)
storage_time_days (int) Days already in cold storage (default: 0)
apple_variety (str) One of: Shimla, Kinnauri,
Royal Delicious, Golden Delicious, Maharaji
region (str) Indian growing region
Returns
-------
dict
{
"predicted_price_7d": float # β‚Ή/kg forecast 7 days ahead
"recommendation": str # "SELL" or "STORE"
"current_price": float # β‚Ή/kg (input)
"storage_cost_7d": float # β‚Ή/kg cost for 7 more days
"breakeven_price": float # min price needed to justify storing
"currency": str # "INR"
"confidence": str
}
"""
_load_models()
date_str = input_features.get('date', datetime.today().strftime('%Y-%m-%d'))
current_price = float(input_features.get('current_price', 90.0)) # β‚Ή/kg default
storage_days = int(input_features.get('storage_time_days', 0))
target_date = pd.to_datetime(date_str) + timedelta(days=7)
# ── Prophet forecast ──────────────────────────────────────
future_df = pd.DataFrame({'ds': [target_date]})
prophet_forecast = _prophet_model.predict(future_df)
prophet_pred = float(prophet_forecast['yhat'].iloc[0])
# ── ARIMA forecast (7 steps ahead) ───────────────────────
arima_pred = float(_arima_model.predict(n_periods=7)[-1])
# ── Hybrid blend ─────────────────────────────────────────
predicted_price_7d = 0.6 * prophet_pred + 0.4 * arima_pred
predicted_price_7d = max(30.0, round(predicted_price_7d, 2))
# ── Sell / Store decision ─────────────────────────────────
# Store only if the predicted price after 7 days exceeds
# current price + cost of storing 7 more days
storage_cost_7d = _storage_cost_inr(7)
breakeven_price = round(current_price + storage_cost_7d, 2)
recommendation = "STORE" if predicted_price_7d > breakeven_price else "SELL"
return {
"predicted_price_7d": predicted_price_7d,
"recommendation": recommendation,
"current_price": round(current_price, 2),
"storage_cost_7d": round(storage_cost_7d, 2),
"breakeven_price": breakeven_price,
"currency": "INR",
"confidence": "hybrid Prophet+ARIMA (0.6/0.4)",
}
# ─── CLI demo ────────────────────────────────────────────────
if __name__ == '__main__':
# Example: Kinnauri apples at β‚Ή120/kg, 15 days in cold storage
sample = {
'date': '2026-03-07',
'current_price': 120.0, # β‚Ή/kg
'storage_time_days': 15,
'apple_variety': 'Kinnauri',
'region': 'Himachal Pradesh',
}
result = predict_price(sample)
print("\n=== Apple Price Prediction (Indian Market) ===")
print(f" Variety : {sample['apple_variety']} ({sample['region']})")
print(f" Current Price : β‚Ή{result['current_price']:.2f}/kg")
print(f" Storage Cost (7d) : β‚Ή{result['storage_cost_7d']:.2f}/kg")
print(f" Break-even Price : β‚Ή{result['breakeven_price']:.2f}/kg")
print(f" Predicted (7d) : β‚Ή{result['predicted_price_7d']:.2f}/kg")
print(f" Recommendation : *** {result['recommendation']} ***")
print(f" Confidence : {result['confidence']}")