Decision Support (kadi.market.decision_support)¶
The Advisor class converts price forecasts and market data into operational recommendations: spatial arbitrage between markets, storage decision timing, and crop portfolio optimization.
It is used internally by the Market facade and accessible via market.advisor. It can also be instantiated directly.
Direct Importing¶
Initialization¶
Advisor is created automatically by Market and is accessible via market.advisor. For direct instantiation:
from kadi.market import Advisor, Forecasting, Logistics, Pricing
advisor = Advisor(
forecast=Forecasting(),
logistics=Logistics(),
pricing=Pricing(),
)
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
forecast |
Forecasting |
None |
Forecasting instance to estimate future prices |
logistics |
Logistics |
None |
Logistics instance for transport costs |
pricing |
Pricing |
None |
Pricing instance for real market prices |
If pricing is None, methods fall back to a default price of 300 XOF/kg with is_simulated=True and confidence_score=0.0.
Public Attributes:
| Attribute | Type | Description |
|---|---|---|
forecast |
Forecasting |
Price forecasting module |
logistics |
Logistics |
Logistics module |
pricing |
Pricing |
Pricing module |
Methods¶
arbitrage(crop, m_from, to, qty)¶
Evaluates the profitability of a physical merchandise transfer between two markets.
Formula:
The minimum profitability threshold is configurable in config.py (key logistics.seuil_rentabilite_pct, default: 10%).
import kadi as kd
weather = kd.Weather(lat=9.3, lon=2.3, name="Parakou")
market = kd.Market(lat=9.3, lon=2.3, location="Parakou", weather=weather)
# Is it profitable to transport 10 tonnes of maize from Parakou to Cotonou?
decision = market.advisor.arbitrage(
crop="maize",
m_from="Parakou",
to="Cotonou",
qty=10.0,
)
print(decision["recommandation"]) # 'TRANSPORTER' or 'NE PAS TRANSPORTER'
print(f"Total net gain: {decision['gain_net_total_cfa']:,.0f} XOF")
print(f"Net gain : {decision['gain_net_percent']:.1f}%")
print(f"Transport cost: {decision['frais_logistiques_total']:,.0f} XOF")
print(f"Rain forecast : {decision['prob_pluie'] * 100:.0f}%")
print(f"Confidence : {decision['confidence_score']:.2f}")
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
crop |
str |
required | Crop code (e.g. 'maize') |
m_from |
str |
'Parakou' |
Purchase market |
to |
str |
'Cotonou' |
Sale market |
qty |
float |
1.0 |
Quantity to transport in metric tonnes |
Returns: dict
| Key | Type | Description |
|---|---|---|
recommandation |
str |
'TRANSPORTER' or 'NE PAS TRANSPORTER' |
gain_net_total_cfa |
float |
Total net gain in XOF |
gain_net_percent |
float |
Net gain as % of invested capital |
frais_logistiques_total |
float |
Total transport costs in XOF |
prix_origine_xof_kg |
float |
Purchase market price in XOF/kg |
prix_destination_xof_kg |
float |
Sale market price in XOF/kg |
is_simulated |
bool |
True if used prices are dummy/simulated |
confidence_score |
float |
Recommendation confidence score (0-1) |
prob_pluie |
float |
Rain probability used for logistics calculation |
Confidence Score:
Calculated as a weighted combination of three factors:
score = 0.5 * price_confidence
+ 0.3 * (0 if simulated, 1 if real)
+ 0.2 * min(1, |net_gain_pct| / 30)
Exceptions:
No exception is raised if data is missing: the method falls back to a default price of 300 XOF/kg with is_simulated=True.
store_sell(crop, market, price, qty, months)¶
Evaluates whether it is more profitable to store a harvest or sell immediately.
Net Expected Gain Formula per Tonne:
Where:
- C_storage = 3,200 XOF/tonne/month (storage, loss, bags)
- C_opportunity = 1.5%/month of current price (working capital lock-up)
- theta = 0.04 (risk aversion coefficient)
# Store 5 tonnes of yam for 3 months or sell now?
storage = market.advisor.store_sell(
crop="yam",
market="Abomey",
price=250_000.0, # Current price in XOF/tonne
qty=5.0,
months=3,
)
print(storage["recommandation_binaire"]) # 'STOCKER' or 'VENDRE IMMÉDIATEMENT'
print(f"Total net margin : {storage['marge_nette_cfa']:,.0f} XOF")
print(f"Margin per tonne : {storage['marge_nette_par_tonne']:,.0f} XOF")
print(f"Estimated future P : {storage['prix_futur_estime']:,.0f} XOF/tonne")
print(f"Horizon : {storage['horizon_mois']} months")
print(f"Confidence : {storage['confidence_score']:.2f}")
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
crop |
str |
required | Crop code |
market |
str |
'Parakou' |
Reference market for forecasting |
price |
float |
300000.0 |
Current price in XOF per tonne |
qty |
float |
1.0 |
Quantity in tonnes |
months |
int |
None |
Storage horizon in months. If None, reads default from config.py (default: 3 months) |
Returns: dict
| Key | Type | Description |
|---|---|---|
recommandation_binaire |
str |
'STOCKER' or 'VENDRE IMMEDIATEMENT' |
marge_nette_cfa |
float |
Total expected net gain in XOF |
marge_nette_par_tonne |
float |
Expected net gain per tonne |
prix_futur_estime |
float |
Predicted price at horizon (XOF/tonne) |
horizon_mois |
int |
Storage horizon used |
is_simulated |
bool |
True if forecast data is simulated |
confidence_score |
float |
Confidence score (0-1) |
If no forecast module is available, the method applies a conservative 15% increase assumption on the current price.
optimize(land_ha, climate, market, yields)¶
Optimizes crop allocation over available arable land.
Uses scipy.optimize.linprog (HiGHS method) to maximize expected revenue under land capacity and diversification constraints. If scipy is unavailable, a heuristic fallback is applied.
Optimization Model:
Maximize: sum(price_i * yield_i * x_i)
Subject to: sum(x_i) <= land_ha
0 <= x_i <= 0.7 * land_ha (minimum 30% diversification)
Climate Adjustments (key drought_severity):
| Severity | Effect |
|---|---|
'severe' |
cowpea yield * 1.3, maize and rice * 0.7 |
'moderate' |
maize yield * 0.85 |
'mild' or 'no_drought' |
no adjustment |
# Optimization under mild climate conditions
portfolio_decision = market.advisor.optimize(
land_ha=10.0,
climate={"drought_severity": "mild"},
market={"maize": 285.0, "cowpea": 580.0, "sorghum": 210.0},
)
print(f"Method : {portfolio_decision['methode']}")
print(f"Expected revenue: {portfolio_decision['revenu_attendu_cfa']:,.0f} XOF")
print(f"Confidence : {portfolio_decision['confidence_score']:.2f}")
for crop, ha in portfolio_decision["repartition_hectares"].items():
print(f" {crop} : {ha:.1f} ha")
# Severe drought scenario (favors cowpea)
drought_decision = market.advisor.optimize(
land_ha=5.0,
climate={"drought_severity": "severe"},
market={"maize": 285.0, "cowpea": 620.0, "sorghum": 210.0},
)
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
land_ha |
float |
1.0 |
Available arable land in hectares |
climate |
dict |
None |
Climate forecast dictionary (see table below) |
market |
dict |
None |
Current median prices per crop in XOF/kg |
yields |
dict |
None |
Expected yields in t/ha. If None, uses FAO/INSAE Benin reference yields |
Keys in climate:
| Key | Type | Description |
|---|---|---|
drought_severity |
str |
Severity: 'no_drought', 'mild', 'moderate', 'severe' |
secheresse_anticipee |
bool |
V1 backward compatibility: True maps to severity 'severe' |
prob_pluie_7j |
float |
7-day rain probability |
Reference Yields (FAO/INSAE Benin):
| Crop | Yield (t/ha) |
|---|---|
maize |
1.8 |
sorghum |
1.2 |
millet |
1.0 |
rice |
2.5 |
cowpea |
0.7 |
soybean |
1.2 |
yam |
8.0 |
cassava |
12.0 |
Returns: dict
| Key | Type | Description |
|---|---|---|
repartition_hectares |
dict[str, float] |
Allocated land per crop (ha) |
revenu_attendu_cfa |
float |
Total expected revenue in XOF |
recommandation |
str |
Explanatory text of the decision |
methode |
str |
'scipy_linprog' or 'heuristique' |
confidence_score |
float |
Confidence score (0.75 normal, 0.55 drought, 0.3 heuristic) |
Heuristic Fallback:
Activated if scipy is missing or if no crop has a known price. Default allocation is: maize 50%, soybean 30%, cowpea 20%. Under severe drought: maize 30%, soybean 30%, cowpea 40%.
Deprecated Methods¶
| Legacy Method | Replaced By | Since |
|---|---|---|
arbitrage_decision(crop, origine, destination, qty_tons) |
arbitrage(crop, m_from, to, qty) |
v1.2.0 |
storage_vs_sell_now(crop, market, current_price, qty_tons, mois_stockage) |
store_sell(crop, market, price, qty, months) |
v1.2.0 |
portfolio_optimization(available_land_ha, climate_forecast, market_forecast) |
optimize(land_ha, climate, market) |
v1.2.0 |
Deprecated Class¶
| Legacy Class | Replaced By | Since |
|---|---|---|
DecisionSupport |
Advisor |
v1.2.0 |
Advisor ¶
Classe convertissant les prévisions de prix et les données de marché en recommandations opérationnelles : arbitrage spatial, stockage, et optimisation de portefeuille de cultures.
Phase 4
Chaque recommandation inclut un 'confidence_score' (0.0 à 1.0) calculé à partir de la qualité des données de prix, du flag is_simulated et de la magnitude du gain estimé.
optimize() utilise scipy.optimize.linprog si disponible, avec un fallback heuristique si scipy est absent.
Source code in kadi/market/decision_support.py
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 | |
__init__ ¶
Initialise le module d'aide à la décision.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
forecast
|
Forecasting
|
Instance de Forecasting pour les prévisions. |
None
|
logistics
|
Logistics
|
Instance de Logistics pour les coûts de transport. |
None
|
pricing
|
Pricing
|
Instance de Pricing pour les prix réels du marché. Si None, les méthodes utiliseront des prix estimés par défaut. |
None
|
Source code in kadi/market/decision_support.py
__getattr__ ¶
Intercepte les accès aux anciens noms de méthodes.
Délègue vers le nouveau nom et émet un DeprecationWarning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Nom de la méthode demandée. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
callable |
La méthode sous son nouveau nom. |
Raises:
| Type | Description |
|---|---|
AttributeError
|
Si le nom est inconnu. |
Source code in kadi/market/decision_support.py
arbitrage ¶
arbitrage(crop: str, m_from: str = 'Parakou', to: str = 'Cotonou', qty: float = 1.0, **kwargs) -> dict
Évalue la rentabilité d'un transfert physique de marchandises entre deux marchés.
Utilise les prix réels du marché (via pricing) pour calculer la marge brute. Les coûts logistiques (avec ajustement météo si disponible) sont calculés par le module logistics.
Formule
Gain net = (prix_destination - prix_origine) * 1000 * qty - cout_transport
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
crop
|
str
|
La culture concernée (ex: 'maize'). |
required |
m_from
|
str
|
Le marché d'achat (ex: 'Parakou'). |
'Parakou'
|
to
|
str
|
Le marché de vente (ex: 'Cotonou'). |
'Cotonou'
|
qty
|
float
|
La quantité à transporter en tonnes métriques. |
1.0
|
**kwargs
|
Anciens nom de paramètres (market_from, market_to, qty_tons). |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
Dictionnaire contenant : - 'recommandation' : 'TRANSPORTER' ou 'NE PAS TRANSPORTER' - 'gain_net_total_cfa' : gain net total en XOF - 'gain_net_percent' : gain net en % du capital investi - 'frais_logistiques_total' : coûts de transport totaux en XOF - 'prix_origine_xof_kg' : prix au marché d'achat - 'prix_destination_xof_kg' : prix au marché de vente - 'is_simulated' : True si les prix utilisés sont fictifs - 'confidence_score' : score de confiance de la recommandation (0-1) - 'prob_pluie' : probabilité de pluie utilisée (0 si sans météo) |
Source code in kadi/market/decision_support.py
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 | |
store_sell ¶
store_sell(crop: str, market: str = 'Parakou', price: float = 300000.0, qty: float = 1.0, months: int = None, **kwargs) -> dict
Évalue s'il est plus rentable de stocker ou de vendre immédiatement.
Phase 4 : l'horizon de stockage est maintenant configurable via le paramètre months. La valeur par défaut est lue depuis config.py (clé de configuration horizon stockage mois, défaut : 3 mois).
Formule
E = E[P_{t+n}] - P_t - C_stockage(n) - C_opportunite(n) - theta * Var(P)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
crop
|
str
|
La culture concernée. |
required |
market
|
str
|
Le marché de référence. |
'Parakou'
|
price
|
float
|
Prix actuel en XOF par tonne. |
300000.0
|
qty
|
float
|
Quantité récoltée en tonnes. |
1.0
|
months
|
int
|
Horizon de stockage en mois. Si None, utilise la valeur par defaut configuree (3 mois). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
Dictionnaire contenant : - 'recommandation_binaire' : 'STOCKER' ou 'VENDRE IMMÉDIATEMENT' - 'marge_nette_cfa' : espérance de gain total en XOF - 'marge_nette_par_tonne' : espérance de gain par tonne - 'prix_futur_estime' : prix prévu à l'horizon (XOF/tonne) - 'horizon_mois' : horizon de stockage utilisé - 'is_simulated' : True si les données de prévision sont simulées (mode offline ou stub). Propagé depuis predict_price(). Vaut True par défaut si aucun module de prévision n'est disponible. - 'confidence_score' : score de confiance (0-1) |
Source code in kadi/market/decision_support.py
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 | |
optimize ¶
optimize(land_ha: float = 1.0, climate: dict = None, market: dict = None, yields: dict = None, **kwargs) -> dict
Optimise la répartition des cultures sur la surface disponible.
Phase 4 : utilise scipy.optimize.linprog pour maximiser le revenu attendu sous contraintes agronomiques et de surface. Si scipy n'est pas disponible, utilise un fallback heuristique.
Modèle d'optimisation (programmation linéaire) : - Variables : x_i = hectares alloués à la culture i - Objectif : maximiser sum(prix_i * rendement_i * x_i) - Contraintes : * sum(x_i) <= land_ha (surface totale) * x_i >= 0 * x_i <= 0.7 * land_ha (diversification minimale)
Ajustements climatiques (SPI de sécheresse) : - Sécheresse sévère (drought_severity='severe') : rendement_niébé * 1.3 (résistant), rendement_maïs * 0.7 - Sécheresse modérée ('moderate') : rendement_maïs * 0.85
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
land_ha
|
float
|
Surface arable disponible en hectares. |
1.0
|
climate
|
dict
|
Prévisions climatiques. Clés attendues : - 'secheresse_anticipee' (bool) : compatibilité V1 - 'drought_severity' (str) : 'no_drought', 'mild', 'moderate', 'severe' - 'prob_pluie_7j' (float) : probabilité de pluie sur 7 jours |
None
|
market
|
dict
|
Prix médians actuels par culture (XOF/kg). Exemple : {'maize': 285, 'cowpea': 580, 'sorghum': 210} |
None
|
yields
|
dict
|
Rendements attendus en tonnes/hectare. Si None, utilise les rendements de référence béninois. |
None
|
**kwargs
|
Anciens arguments (available_land_ha, climate_forecast, market_forecast). |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
Dictionnaire contenant : - 'repartition_hectares' : répartition optimale par culture (hectares) - 'revenu_attendu_cfa' : revenu total attendu en XOF - 'recommandation' : texte explicatif - 'methode' : 'scipy_linprog' ou 'heuristique' - 'confidence_score' : score de confiance de l'optimisation |
Source code in kadi/market/decision_support.py
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 | |