- What is xG in football and how does this metric affect betting
- How xG analytics works: formulas, models, and data sources
- Where to find xG statistics: overview of sports event APIs and their capabilities
- How to use the xG statistics API for match analysis and betting predictions
- Typical mistakes bettors make when interpreting xG and why the metric is underestimated
- Integrating xG analytics through API into your own betting models and strategies
What is xG in football and how does this metric affect betting
xG (expected goals) is the probability that a specific shot on goal will result in a goal. Each shot is assigned a value from 0 to 1 depending on the position, angle, type of pass, body part, pressure from defenders, and other factors. The sum of xG for all shots by a team shows how many goals they «should have» scored on average according to statistics, rather than by one-time luck or misfortune.
For bettors, xG is important because it describes the actual quality of play, not just the final score. A team can win 1:0 with an xG of 0.4 against 2.1 — with a high probability, such a result is unstable over the long term. By analyzing xG over a series of matches, one can identify teams that systematically outperform their opponents but temporarily underperform in points, and vice versa. Based on detailed match statistics provided Sports events API, it is easier to build your own xG-like metrics and use them when searching for inflated odds with bookmakers.
Through the Sport Events API, you receive structured data on shots, ball possession, dangerous moments, positional statistics, and live events. This allows you to build your own «expected goals» models by leagues, seasons, and specific teams, compare xG with actual goals and odds dynamics. Data on markets and quotes from the oddsBase block in the same API response helps to immediately link the quality of play with the bookmaker’s line and check where the market undervalues or overvalues a team.
fetch('https://api.api-sport.ru/v2/football/matches?ids=14570728', {
headers: {
'Authorization': 'YOUR_API_KEY'
}
})
.then(response => response.json())
.then(data => {
const match = data.matches[0];
// matchStatistics содержит агрегированную статистику по ударам и моментам
console.log(match.matchStatistics);
});
How xG analytics works: formulas, models, and data sources
The classic xG model is built on the basis of logistic regression or other machine learning methods. The model is fed historical data on tens of thousands of shots: coordinates on the field, angle to the goal, distance, type of pass, whether the shot was a header, goalkeeper position, pressure from defenders, and so on. The model learns to predict the probability of a goal, and the final xG value of an individual shot is the predicted probability of a goal scored by the model.
In practice, the coordinates of each shot and complete player tracking are not always available. In such cases, approximate models are used based on aggregated features: the number of shots from the penalty area, shots on target, «big chances,» penalties, the number of touches in the opponent’s penalty area, and the quality of attacking actions. It is these advanced metrics that are found in the matchStatistics field returned by the Sport Events API. Based on them, a simplified but stable xG index for teams and matches can be built, which already provides an advantage over bettors who focus only on the score and possession.
The source of data for calculating xG is the match stream itself: events, statistics by halves, attack structure, and shots. Through Sports events API it is possible to regularly export this data by seasons and tournaments, save it in your database, and train your own models. In the future, the development of the API includes adding WebSocket streams for live data and AI tools for more accurate assessment of goal moments in real time, which will allow recalculating xG «on the fly» during the match.
from math import exp
# Простейшая логистическая функция для иллюстрации идеи xG
def shot_xg(distance_meters: float, is_header: bool) -> float:
b0 = 2.0 # свободный коэффициент
b1 = -0.18 # штраф за расстояние
b2 = -0.7 # штраф за удар головой
z = b0 + b1 * distance_meters + b2 * int(is_header)
return 1 / (1 + exp(-z))
Where to find xG statistics: overview of sports event APIs and their capabilities
Ready-made xG estimates are available only from a limited number of providers, most often in closed or expensive solutions. A more flexible and controlled way for an analyst or bettor is to calculate xG independently based on detailed match statistics. For this, reliable, full-format data on the event series and advanced statistics are needed. This is exactly what the Sport Events API provides on the platform. api-sport.ru: matches, events, lineups, statistics on shots, possession, actions in the final third, and other metrics necessary for building your own models.
The basic set of endpoints includes obtaining a list of sports (/v2/sport), categories, and tournaments, and most importantly — detailed information about matches: /v2/{sportSlug}/matches and /v2/{sportSlug}/matches/{matchId}. The response for a match includes a matchStatistics block with a breakdown by periods and groups of metrics (Shots, Attack, Passes, Duels, Goalkeeping, etc.), as well as oddsBase with markets and odds. This format allows for simultaneous assessment of the teams’ playing advantage and the bookmaker market’s reaction to that advantage.
To get started, simply register and obtain an access key at your personal account at api-sport.ru. You can then set up regular exports of matches for the desired tournaments, collect historical statistics, and build your xG metrics based on them. As the service develops, new sports, additional fields, and WebSocket subscriptions will appear, which is especially important for live analytics and dynamic recalculation of expected goals in real time.
curl \ -H "Authorization: YOUR_API_KEY" \ "https://api.api-sport.ru/v2/football/matches?date=2025-09-03&tournament_id=7"
How to use the xG statistics API for match analysis and betting predictions
A practical scenario for a bettor looks like this: you regularly export historical matches of the leagues of interest via the API, calculate your expected goals metric for each team based on matchStatistics, and then compare the average xG of teams with their actual goals and results. Teams that consistently create many chances (high xG for) and allow few (low xG against), but have weak results, often end up being undervalued in odds.
Next, this data is linked to markets and odds obtained from oddsBase. The calculation of fair probabilities of outcomes based on the xG model and comparing them with the implied probability from the odds allows for finding value bets — situations where the bookmaker underestimates the actual chances of a team. An important advantage of working through the Sport Events API is that you control the entire pipeline: from extracting primary data to calculating xG and checking lines, without relying on black boxes from third-party providers.
Additionally, you can build rolling metrics: xG for the last 5–10 matches, the difference in xG home/away, tournament-dependent adjustments, and in the future — supplement this with online data via WebSocket when such an opportunity arises in the API. This provides a foundation for semi-automatic and fully automatic betting models that take into account not only the form based on scores but also the actual quality of play.
import requests
API_KEY = "YOUR_API_KEY"
BASE_URL = "https://api.api-sport.ru/v2/football"
params = {
"team_id": 195801, # ID команды
"status": "finished"
}
resp = requests.get(f"{BASE_URL}/matches", headers={"Authorization": API_KEY}, params=params)
matches = resp.json()["matches"]
def simple_match_xg(stats_groups):
shots_inside = 0
big_chances = 0
for group in stats_groups:
if group["groupName"] == "Shots":
for item in group["statisticsItems"]:
if item["key"] == "totalShotsInsideBox":
shots_inside = int(item["homeValue"])
if group["groupName"] == "Attack":
for item in group["statisticsItems"]:
if item["key"] == "bigChanceCreated":
big_chances = int(item["homeValue"])
return 0.1 * shots_inside + 0.4 * big_chances
Typical mistakes bettors make when interpreting xG and why the metric is underestimated
One of the main mistakes is trying to draw conclusions about xG based on one or two matches. Expected goals are a probabilistic metric and require a distance: in individual games, significant deviations from the average are possible, and it is these deviations that constitute the «noise» of football. The correct approach is to analyze xG on a sample of dozens of matches, comparing long-term trends rather than isolated spikes.
The second typical mistake is perceiving xG as an absolute truth without considering the context. Different models calculate xG differently and on different sets of features, so it is incorrect to directly compare values from different sources. It is also important to consider the team’s style, squad condition, schedule, and motivation. For example, a team may consciously give up the ball, playing defensively, but create higher quality chances through counterattacks, which is poorly reflected in simple possession metrics but is clearly visible in xG.
Many bettors use open xG graphs without understanding how they were calculated, and as a result, they bet on «overvalued» figures. When working through your own model based on the Sport Events API, you get a single, transparent source of data and can control the calculation algorithm. This reduces the risk of interpretation errors and allows for a more accurate assessment of where xG truly indicates a hidden advantage and where it is merely a consequence of specific model characteristics or a small sample size.
async function getLastTeamMatches(teamId, limit = 10) {
const url = `https://api.api-sport.ru/v2/football/matches?team_id=${teamId}&status=finished`;
const res = await fetch(url, {
headers: { 'Authorization': 'YOUR_API_KEY' }
});
const json = await res.json();
return json.matches.slice(0, limit);
}
Integrating xG analytics through API into your own betting models and strategies
Technically, the integration of xG analytics is built as a chain: Sport Events API → data storage → calculation scripts and models → dashboards for decision-making (dashboards, alerts, automated strategies). You regularly request matches and statistics for the necessary leagues, save API responses to the database (PostgreSQL, ClickHouse, BigQuery, etc.), and then run xG calculation tasks and derived metrics on a schedule or triggered by an event (for example, the end of a match).
For live betting, minimal latency is important. Today, you can poll the API at a specified frequency and update xG estimates during the match, and with the emergence of WebSocket subscriptions on the platform api-sport.ru, this process will become even more responsive: events and statistical updates will come to your service via a push model. On top of this, you can build your own AI models that predict the dynamics of xG and outcome probabilities in real-time based on match history and the current state of play.
Proper integration also implies control of limits, error logging, and data quality monitoring. By using a single API for football, basketball, hockey, tennis, and esports, you can scale the «expected points/goals» approach to other sports, building a comprehensive system of analytics and trading. To get started, it is enough to obtain an access key in your personal account at api-sport.ru and connect your scripts to the production endpoint.
import time
import requests
API_KEY = "YOUR_API_KEY"
BASE = "https://api.api-sport.ru/v2/football"
headers = {"Authorization": API_KEY}
match_id = 14570728
while True:
r = requests.get(f"{BASE}/matches/{match_id}", headers=headers)
match = r.json()
# здесь можно пересчитывать live-xG по обновленной статистике
print("Текущая минута:", match["currentMatchMinute"])
time.sleep(60)




