DEV Community

Cover image for Python Odds Converter: Decimal, American & Fractional Odds
orbistats
orbistats

Posted on

Python Odds Converter: Decimal, American & Fractional Odds

Build a tested Python odds converter: decimal, American, fractional, implied probability and margin removal, plus live odds from an API. Full code included.

Odds Converter in Python: Decimal, American, Fractional and Implied Probability

If you have ever touched betting data, you have hit this wall. One bookmaker shows -110. Another shows 1.91. A third shows 10/11. They are all (almost) the same price written three different ways, and your code has to understand all of them.

In this guide we will build a small, dependency-free odds converter in Python from scratch. It is the kind of utility you end up needing in every sports-data project, whether you are building a fantasy app, a trading dashboard, a model backtest or just a personal betting tracker.

By the end you will have:

Converters between decimal, American and fractional odds
A parser that auto-detects the format from a string
Implied probability calculation
Margin (overround) removal with two methods, proportional and power
A basic expected value helper and a best-price finder
A working example that feeds live odds from an API into the converter
A small pytest suite and a CLI

Everything uses only the Python standard library, except requests and pytest in the later sections.

Table of contents
The three odds formats
Implied probability
Conversion functions
Auto-detecting the format
A clean Odds class
The bookmaker margin (overround)
Two ways to remove the margin
Expected value and best price
Getting real odds from an API
Tests
A tiny CLI
Common mistakes
FAQ
Where to go next

  1. The three odds formats Format Example Where you see it Decimal 2.50 Europe, Australia, Canada, most APIs American (moneyline) +150 / -110 United States Fractional 3/2 UK and Ireland, horse racing

All three describe the same idea: how much you get back relative to what you stake.

Decimal 2.50: a 1 unit stake returns 2.50 in total (1.50 profit plus your 1 stake).
American +150: a 100 stake wins 150 in profit. American -110: you need to stake 110 to win 100.
Fractional 3/2: 3 units of profit for every 2 staked.

Decimal is the easiest format to calculate with, so we will treat it as the canonical format. Convert everything to decimal first, then convert out to whatever you need.

  1. Implied probability

Implied probability is the chance that a price suggests:

implied_probability = 1 / decimal_odds

So 2.50 implies 1 / 2.50 = 40%. A -110 line (decimal 1.909) implies about 52.4%.

If you want a plain-English refresher on this and related terms, the Orbistats glossary explains odds, xG and implied probability without jargon.

  1. Conversion functions python from future import annotations

from fractions import Fraction

def american_to_decimal(american: int) -> float:
if -100 < american < 100:
raise ValueError("American odds must be <= -100 or >= +100")
if american > 0:
return 1 + american / 100
return 1 + 100 / abs(american)

def decimal_to_american(decimal: float) -> int:
if decimal <= 1:
raise ValueError("Decimal odds must be greater than 1.0")
if decimal >= 2:
return round((decimal - 1) * 100)
return round(-100 / (decimal - 1))

def fractional_to_decimal(fractional: str) -> float:
text = fractional.strip().lower()
if text in {"evens", "evs"}:
return 2.0
num, den = text.split("/")
if int(den) == 0:
raise ValueError("Denominator cannot be zero")
return 1 + int(num) / int(den)

def decimal_to_fractional(decimal: float, max_denominator: int = 100) -> str:
if decimal <= 1:
raise ValueError("Decimal odds must be greater than 1.0")
# Going through str() avoids float noise like 1.5000000000000002
profit = Fraction(str(round(decimal, 4))) - 1
profit = profit.limit_denominator(max_denominator)
return f"{profit.numerator}/{profit.denominator}"

def implied_probability(decimal: float) -> float:
if decimal <= 1:
raise ValueError("Decimal odds must be greater than 1.0")
return 1 / decimal

A few design notes worth knowing:

American odds have a built-in gap. Anything strictly between -100 and +100 is not a valid price, so the function rejects it.
The decimal >= 2 branch is where American odds flip sign. Underdogs (decimal 2.00 or higher) are positive, favourites are negative.
Fractions are messy. limit_denominator turns ugly values into bookmaker-style fractions. For example 3.50 becomes 5/2, not 2.5/1.
Everything validates input. Silent bad data is the worst bug in odds code, so we fail loudly.

Try it in a REPL:

python

american_to_decimal(150)
2.5
decimal_to_american(3.40)
240
fractional_to_decimal("5/2")
3.5
decimal_to_fractional(3.5)
'5/2'
round(implied_probability(2.5), 4)
0.4

  1. Auto-detecting the format

Real data rarely tells you which format it is in. This parser guesses from the shape of the string:

python
def parse_odds(text: str) -> float:
"""Return decimal odds from '+150', '-110', '5/2', 'evens' or '1.91'."""
t = text.strip().lower()
if t in {"evens", "evs"} or "/" in t:
return fractional_to_decimal(t)
if t.startswith(("+", "-")):
return american_to_decimal(int(t))
value = float(t)
if value <= 1:
raise ValueError("Decimal odds must be greater than 1.0")
return value

The rules are simple. A slash means fractional, a leading + or - means American, and anything else is decimal. One honest limitation: an American price without a sign (for example 150) is ambiguous, so we treat it as decimal and reject it. Always keep the sign on American odds.

  1. A clean Odds class

Calling five functions gets old quickly. A small frozen dataclass makes the code read naturally:

python
from dataclasses import dataclass

@dataclass(frozen=True)
class Odds:
decimal: float

def __post_init__(self):
    if self.decimal <= 1:
        raise ValueError("Decimal odds must be greater than 1.0")

@classmethod
def parse(cls, text: str) -> "Odds":
    return cls(parse_odds(text))

@classmethod
def from_american(cls, value: int) -> "Odds":
    return cls(american_to_decimal(value))

@classmethod
def from_fractional(cls, value: str) -> "Odds":
    return cls(fractional_to_decimal(value))

@classmethod
def from_probability(cls, p: float) -> "Odds":
    if not 0 < p < 1:
        raise ValueError("Probability must be between 0 and 1 (exclusive)")
    return cls(1 / p)

@property
def american(self) -> int:
    return decimal_to_american(self.decimal)

@property
def fractional(self) -> str:
    return decimal_to_fractional(self.decimal)

@property
def probability(self) -> float:
    return implied_probability(self.decimal)

def __str__(self) -> str:
    sign = "+" if self.american > 0 else ""
    return (
        f"{self.decimal:.2f} | {sign}{self.american} | "
        f"{self.fractional} | {self.probability:.1%}"
    )
Enter fullscreen mode Exit fullscreen mode

Now conversions are one-liners:

python

print(Odds.parse("+150"))
2.50 | +150 | 3/2 | 40.0%
print(Odds.parse("-110"))
1.91 | -110 | 10/11 | 52.4%
print(Odds.parse("5/2"))
3.50 | +250 | 5/2 | 28.6%
print(Odds.from_probability(0.25))
4.00 | +300 | 3/1 | 25.0%


Notice that Odds.parse("1.91") gives 91/100 as the fraction, while Odds.parse("-110") gives 10/11. Both are correct for their input. Bookmaker prices are rounded, so a decimal price and its “equivalent” fraction rarely match exactly.

  1. The bookmaker margin (overround)

Here is the part most converters skip. If you add up the implied probabilities of every outcome in a market, you should get 100%. You never do.

Take a football 1X2 market with these sample prices:

python
odds = {"home": 1.91, "draw": 3.40, "away": 4.20}

The implied probabilities are 52.36%, 29.41% and 23.81%. They add up to 105.58%. That extra 5.58% is the bookmaker’s margin, also called the overround or vig.

python
def market_overround(decimal_odds: dict[str, float]) -> float:
"""Total implied probability minus 1. 0.0558 means a 5.58% margin."""
return sum(1 / o for o in decimal_odds.values()) - 1
python

f"{market_overround(odds):.2%}"
'5.58%'


This number is useful by itself. A lower margin means a sharper (better value) price. Comparing overround across bookmakers is one of the quickest ways to see who is pricing most efficiently.

  1. Two ways to remove the margin

To estimate what the market really thinks, you strip the margin out and get fair probabilities that sum to exactly 100%.

Method 1: Proportional (the simple default)

Divide each implied probability by the total:

python
def fair_probabilities(decimal_odds: dict[str, float]) -> dict[str, float]:
implied = {k: 1 / o for k, o in decimal_odds.items()}
total = sum(implied.values())
return {k: p / total for k, p in implied.items()}
python

{k: f"{v:.2%}" for k, v in fair_probabilities(odds).items()}
{'home': '49.59%', 'draw': '27.86%', 'away': '22.55%'}


This is easy to explain and good enough for most uses. Its weakness is that it assumes the margin is spread evenly across all outcomes.

Method 2: Power method (handles longshot bias)

In practice, bookmakers often load more margin onto longshots. The power method finds an exponent k such that the implied probabilities raised to k sum to 1:

python
def fair_probabilities_power(decimal_odds: dict[str, float]) -> dict[str, float]:
implied = {k: 1 / o for k, o in decimal_odds.items()}
lo, hi = 1.0, 2.0
while sum(p ** hi for p in implied.values()) > 1:
hi = 2
for _ in range(100):
mid = (lo + hi) / 2
if sum(p *
mid for p in implied.values()) > 1:
lo = mid
else:
hi = mid
k = (lo + hi) / 2
return {name: p ** k for name, p in implied.items()}
python

{k: f"{v:.2%}" for k, v in fair_probabilities_power(odds).items()}
{'home': '50.52%', 'draw': '27.49%', 'away': '21.99%'}


Compare the two. The power method gives the favourite a slightly higher fair probability (50.52% vs 49.59%) and the longshot a lower one (21.99% vs 22.55%). That is the favourite-longshot bias showing up in the numbers. Neither method is “the truth”, but knowing both makes your models more honest.

  1. Expected value and best price

Once you have a fair probability, you can ask whether a price is worth taking. Expected value (EV) per unit staked is:

python
def expected_value(decimal: float, true_probability: float, stake: float = 1.0) -> float:
return stake * (true_probability * decimal - 1)
python

expected_value(2.10, 0.50) # 1 unit stake
0.05000000000000004
expected_value(2.10, 0.50, 50) # 50 unit stake
2.500000000000002


If you believe an outcome is 50% likely and a bookmaker offers 2.10, you expect to make 0.05 per unit staked over the long run. The hard part is the “if you believe”, which is where fair probabilities and good historical data come in.

When you have the same market from several bookmakers, picking the best price is one line:

python
def best_price(quotes: dict[str, float]) -> tuple[str, float]:
book = max(quotes, key=quotes.get)
return book, quotes[book]
python

best_price({"BookA": 1.95, "BookB": 2.02, "BookC": 1.98})
('BookB', 2.02)


Line shopping like this is one of the most reliable edges in betting maths, and it only works if every price is in the same format. That is exactly why a normalised feed matters.

  1. Getting real odds from an API

Typing prices by hand is fine for learning. Real projects pull odds from a data provider, and then every one of the problems above shows up at scale: different formats, different markets, different margins.

This is where a normalised sports odds API earns its keep. The Orbistats Odds API delivers pre-match and live odds normalised across bookmakers, so you do not maintain one parser per source. If you want the deeper background, the sports odds API guide covers live, historical and normalised odds in detail.

Getting started follows four steps: request access, open the activation link, grab your API key and make your first request. The quickstart walks through it, the documentation explains authentication and the base URL, and the API reference lists endpoints, parameters and response fields. You can also try requests in the sandbox before writing any code.

Authentication is a bearer token. Here is the pattern. The endpoint path and parameters below are placeholders, so copy the real ones from the API reference:

python
import requests

API_KEY = "YOUR_API_KEY"
BASE_URL = "https://api.orbistats.com/v1"
headers = {"Authorization": f"Bearer {API_KEY}"}

Replace with the real odds endpoint and parameters from the API reference

resp = requests.get(f"{BASE_URL}/odds", headers=headers, params={}, timeout=10)
resp.raise_for_status()
payload = resp.json()

Because payload shapes can differ, wrap the extraction in a small function so the rest of your code never depends on the raw structure. This version assumes a 1X2 market shaped like the sample below, so adjust it to the real response:

python
def extract_1x2(market: dict) -> dict[str, float]:
"""Expecting: {"market": "1X2", "odds": {"home": 1.91, "draw": 3.40, "away": 4.20}}"""
prices = market["odds"]
return {side: float(prices[side]) for side in ("home", "draw", "away")}

market = {"market": "1X2", "odds": {"home": 1.91, "draw": 3.40, "away": 4.20}}
prices = extract_1x2(market)

for side, price in prices.items():
print(f"{side:>5}: {Odds(price)}")

print(f"Margin: {market_overround(prices):.2%}")
print("Fair (proportional):", {k: round(v, 4) for k, v in fair_probabilities(prices).items()})

The numbers in these examples are sample prices for illustration, not live odds.

It is not just football

Odds maths is identical across sports, only the markets change. Orbistats covers 13 sports behind one API, so the same converter works everywhere:

Football for 1X2, handicaps and totals
Cricket for match winner and innings markets
Tennis for two-way moneyline-style prices

Two-way markets like tennis are the simplest case for margin removal. With two outcomes at 1.91 each, the overround is about 4.71% and both fair probabilities come out at exactly 50%.

Backtesting your converter on history

A converter is only as good as the data you test it on. If you want to check how fair probabilities compare with real results over many seasons, you need historical odds, ideally including closing prices. The Historical Sports Data API is built for that kind of backtesting, and this step-by-step article on how to backtest a sports betting model with historical odds data shows the full workflow. Removing the margin from closing odds is a classic way to build a strong baseline probability model.

Pricing note

Access is based on time windows rather than monthly seats. As listed on the pricing page, there is a Free plan (1 hour, no card), Starter at €19 for 24 hours, Growth at €79 for 5 days and an Unlimited monthly plan. Every plan includes all sports and endpoints. Check the page for current details, since plans can change.

  1. Tests

Odds maths is exactly the kind of code that breaks silently, so write tests. Save the code above as odds.py and create test_odds.py:

python
import pytest
from odds import (
Odds,
american_to_decimal,
decimal_to_american,
decimal_to_fractional,
fair_probabilities,
fair_probabilities_power,
fractional_to_decimal,
parse_odds,
)

def test_american_round_trip():
for value in (-300, -110, 100, 150, 500):
assert decimal_to_american(american_to_decimal(value)) == value

def test_fractional_round_trip():
for value in ("1/2", "5/2", "10/11", "11/4"):
assert decimal_to_fractional(fractional_to_decimal(value)) == value

def test_evens():
assert fractional_to_decimal("evens") == 2.0
assert decimal_to_american(2.0) == 100

def test_parse_detects_formats():
assert parse_odds("+150") == pytest.approx(2.5)
assert parse_odds("5/2") == pytest.approx(3.5)
assert parse_odds("1.91") == pytest.approx(1.91)

def test_probability_round_trip():
assert Odds.from_probability(0.4).decimal == pytest.approx(2.5)

@pytest.mark.parametrize("method", [fair_probabilities, fair_probabilities_power])
def test_fair_probabilities_sum_to_one(method):
fair = method({"home": 1.91, "draw": 3.40, "away": 4.20})
assert sum(fair.values()) == pytest.approx(1.0)

@pytest.mark.parametrize("bad", [0, 50, -50])
def test_invalid_american(bad):
with pytest.raises(ValueError):
american_to_decimal(bad)

def test_invalid_decimal():
with pytest.raises(ValueError):
Odds(1.0)

Run it with:

bash
pip install pytest
pytest -q

  1. A tiny CLI

Add this to the bottom of odds.py to convert from the terminal:

python
if name == "main":
import sys

for arg in sys.argv[1:]:
    print(f"{arg:>8}  ->  {Odds.parse(arg)}")
Enter fullscreen mode Exit fullscreen mode

bash
$ python odds.py +150 -110 5/2 1.91 evens
+150 -> 2.50 | +150 | 3/2 | 40.0%
-110 -> 1.91 | -110 | 10/11 | 52.4%
5/2 -> 3.50 | +250 | 5/2 | 28.6%
1.91 -> 1.91 | -110 | 91/100 | 52.4%
evens -> 2.00 | +100 | 1/1 | 50.0%

If you prefer a no-code option for quick checks, Orbistats also publishes odds converters and quick calculators you can use in the browser.

  1. Common mistakes Treating implied probability as true probability. It includes the bookmaker’s margin. Use fair probabilities when you want the market’s real view. Expecting perfect round trips. Rounding to whole American numbers or simple fractions loses a little precision. Treat conversions as approximate and keep decimal as your source of truth. Mixing up favourites and underdogs in American odds. Negative means favourite and positive means underdog, and the flip happens at decimal 2.00. Floating point surprises. Comparing floats with == will bite you. Use pytest.approx in tests and math.isclose in code. Ignoring sign on American odds. 150 and +150 are not the same thing to a parser. Keep the sign. Removing margin from the wrong market. Only normalise a complete market where outcomes are mutually exclusive and cover every possibility, like 1X2 or a two-way moneyline.
  2. FAQ

How do you convert American odds to decimal?
For positive odds, divide by 100 and add 1. For negative odds, divide 100 by the absolute value and add 1. So +150 is 2.50 and -110 is about 1.91.

How do you calculate implied probability from odds?
Divide 1 by the decimal odds. 2.50 gives 0.40, or 40%.

What is the overround?
It is how much the implied probabilities of all outcomes exceed 100%. It is the bookmaker’s built-in margin.

Which margin removal method should I use?
Start with proportional because it is simple and transparent. Move to the power method (or Shin’s method) if you care about longshot bias.

Can I use this with live odds?
Yes. The maths is the same. Live prices just change faster, so pair the converter with a streaming source. Orbistats supports WebSocket delivery for live feeds so you avoid constant polling.

  1. Where to go next

You now have a solid, tested foundation. Natural next steps:

Wrap the converter in a Streamlit or FastAPI app
Compare margins across bookmakers and rank them
Build an expected value finder that flags prices above your fair probability
Add historical backtests to see whether your fair probabilities actually beat closing lines
Start with the developer hub to explore everything the API offers

If you are comparing providers before you build, the Orbistats blog also has a buyer’s guide on how to choose a sports data API.

If this was useful, leave a comment with the odds format you run into most, and I will add more conversions and examples. Happy coding.

Disclosure: I am affiliated with Orbistats. All odds shown in code examples are sample prices for illustration.

Top comments (0)