OpenBB-finance/OpenBB · error · ValueError

Invalid port_code: {item}. Must be a valid port ID or name.A

Error message

Invalid port_code: {item}. Must be a valid port ID or name.Available options: {port_id_choices}.

What it means

Raised in the port_code validator when an item matches neither a port id (map key), a port name, a country name, nor the first part of a port name before ' - '. The message dumps the entire `port_id_choices` list, which is large. Note the missing space in 'name.Available' is a message formatting artifact. A sibling 'No valid port_code provided.' error exists when all items are filtered out.

Source

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

                    v_.replace(" - ", "_").replace("-", "_").lower().replace(" ", "_")
                    for v_ in port_id_map.values()
                ]
                idx = values_snake.index(item_lower)
                new_item = port_id_map[idx]
                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."

View on GitHub (pinned to 3e071fcc2c)

Solutions

  1. Look up the exact id/name via the port_info endpoint (or the printed choices) and pass that verbatim.
  2. For names with ' - ' suffixes, try just the part before the dash (e.g. 'new_york').
  3. Trim and normalize whitespace; matching is case-insensitive but exact on characters otherwise.
  4. If the port genuinely is missing from PortWatch, no parameter change will help — choose a nearby covered port.

Example fix

# before
port_volume(port_code='NYC')

# after
port_volume(port_code='usnyc')  # exact PortWatch id from port_info
Defensive patterns

Strategy: validation

Validate before calling

# Resolve against the same sources the validator uses
info = await obb.economy.imf.port_info()
valid_ids = {p.port_id for p in info.results}  # or get_port_id_choices()
valid_names = {p.name.lower().replace(' ', '_') for p in info.results}
item = item.strip().lower().replace(' ', '_')
if item not in valid_ids and item not in valid_names and item.split(' - ')[0] not in valid_names:
    raise ValueError(f'unknown port: {item}')

Type guard

def is_valid_port_code(item: str, port_id_map: dict) -> bool:
    i = item.strip().lower().replace(' ', '_')
    return (i in port_id_map
            or i in {v.lower().replace(' ', '_') for v in port_id_map.values()}
            or i in {v.split(' - ')[0].lower().replace(' ', '_') for v in port_id_map.values()})

Prevention

When it happens

Trigger: Passing a port code that is not in the PortWatch ports database (e.g. wrong UN/LOCODE or LMIS id), a misspelled port name, or a name whose 'before dash' part differs from the entry. Matching is on lowercased, space-to-underscore forms, so unusual punctuation or full names containing ' - ' can fail.

Common situations: Guessing port ids instead of looking them up via maritime port_info; using a different id scheme (UN/LOCODE vs PortWatch id); trailing whitespace or casing from user input; port names that changed in the database.

Related errors


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