OpenBB-finance/OpenBB · error · ValueError

No valid port_code provided.

Error message

No valid port_code provided.

What it means

Thrown by the port_code field validator on ImfPortVolumeQueryParams when, after normalizing every supplied entry against the IMF PortWatch port ID/name map, zero valid values remain. Individually bad entries raise a separate 'Invalid port_code' error, so this fires when the input itself contains no usable entries (empty string, empty list, or entries that normalize to nothing). It means the query carries no ports to fetch and the request would be meaningless.

Source

Thrown at openbb_platform/providers/imf/openbb_imf/models/port_volume.py:155

                new_values.append(new_item)
            # Accept first part of port name (before dash)
            elif item_lower in [
                v_.split(" - ")[0].lower().replace(" ", "_")
                for v_ in port_id_map.values()
            ]:
                first_parts = [
                    v_.split(" - ")[0].lower().replace(" ", "_")
                    for v_ in port_id_map.values()
                ]
                idx = first_parts.index(item_lower)
                new_values.append(list(port_id_map.keys())[idx])
            else:
                raise ValueError(
                    f"Invalid port_code: {item}. Must be a valid port ID or name.Available options: {port_id_choices}."
                )

        if not new_values:
            raise ValueError("No valid port_code provided.")

        return ",".join(new_values)

    @model_validator(mode="before")
    @classmethod
    def validate_model(cls, values):
        """Validate the model before instantiation."""
        if values.get("start_date") is not None and values["start_date"] < dateType(
            2019, 1, 1
        ):
            raise OpenBBError(
                ValueError(
                    f"Minimum start_date is 2019-01-01. Got {values['start_date']} instead."
                )
            )
        if not values.get("port_code") and not values.get("country"):
            values["port_code"] = "port1114"

View on GitHub (pinned to 3e071fcc2c)

Solutions

  1. Pass at least one valid port ID (e.g. 'port1114') or a valid port name, or omit port_code and pass country instead so the default port is used.
  2. Guard before the call: skip or prompt when the constructed port_code string/list is empty.
  3. List valid IDs/names from the port_id_map used by the provider (keys are IDs, values are 'snake_name - country' labels) to build UI choices.

Example fix

# before
obb.economy.transport_and_shipping.port_volume(provider='imf', port_code=','.join(selected_ports))  # selected_ports == []

# after
if not selected_ports:
    raise ValueError('Select at least one port or pass a country.')
obb.economy.transport_and_shipping.port_volume(provider='imf', port_code=','.join(selected_ports))
Defensive patterns

Strategy: validation

Validate before calling

def valid_port_input(port_code):
    if port_code is None:
        return False
    vals = port_code.split(',') if isinstance(port_code, str) else list(port_code)
    return len([v for v in vals if v and v.strip()]) > 0

if not valid_port_input(port_code):
    raise ValueError('Provide at least one port_code or a country.')

Type guard

def is_non_empty_port_selection(value: str | list[str] | None) -> bool:
    if value is None:
        return False
    items = value.split(',') if isinstance(value, str) else value
    return bool(items) and any(isinstance(i, str) and i.strip() for i in items)

Try / catch

try:
    res = await obb.economy.port_volume(provider='imf', port_code=port_code)
except (ValueError, OpenBBError) as e:
    if 'No valid port_code' in str(e):
        # rebuild selection / prompt user
        ...

Prevention

When it happens

Trigger: Calling the IMF port volume endpoint with port_code='' , port_code=[] , or a whitespace-only value, while also not supplying a country (the before-validator only substitutes the default 'port1114' when port_code is falsy AND country is absent, so an explicitly empty collection that survives to the field validator triggers this).

Common situations: A UI multi-select for ports left empty; code that dynamically joins a port list (','.join([]) yields ''); a previous step resolving country->ports returning an empty result that is passed straight through.

Related errors


AI-assisted analysis of OpenBB-finance/OpenBB@3e071fcc2c (2026-08-14). Data as JSON: /api/errors/146c65b193c05f59. Report an issue: GitHub.