01 · SETUP
Install the libraries and set your API key
You’ll need Python 3.10 or newer and a VizualStocks API key. Save revenue_segmentation.py in your working folder, then install requests and pandas:
python -m pip install requests pandasLog in to get your API key. In the dashboard, click Create API key → Create key → Copy, then return here and replace YOUR_API_KEY below.
$env:VIZUALSTOCKS_API_KEY = "YOUR_API_KEY"export VIZUALSTOCKS_API_KEY="YOUR_API_KEY"The script sends the key through the X-API-Key header. Requests use timeouts and retry transient errors, including rate limits, with backoff and support for Retry-After.
02 · DISCOVERY
Find companies and their segment groups
First list the companies with segment coverage available to your key, then inspect Microsoft’s groups and metric definitions.
python revenue_segmentation.py --list-companies
python revenue_segmentation.py --ticker MSFT --list-groupsThe first command calls GET /v1/companies?hasSegments=true. The second retrieves segment history and prints the returned segmentGroups and metric definitions. For frequency coverage and first/last reported periods, use the metric catalog endpoint.
| Group ID | What it contains |
|---|---|
revenueByBusinessAndProduct | Reporting segments plus overlapping product and cloud measures |
revenueByGeography | United States and other countries revenue |
operatingIncomeByBusiness | Operating income, not revenue |
Prefer a notebook? Keep it beside the downloaded script and run this equivalent request. The same payload is used in the pandas example below.
from revenue_segmentation import make_session, api_get
with make_session() as session:
payload = api_get(
session, "/companies/MSFT/metrics",
type="segment", frequency="quarterly",
status="all", order="asc",
)
for group in payload["segmentGroups"]:
print(group["groupId"], group["metricIds"])type="segment" selects breakdowns; status="all" retains discontinued series for historical research; order="asc" returns periods in chronological order. Omit a history limit to retrieve the available history for that selection.
03 · BUSINESS SEGMENTS
Export Microsoft revenue by business segment
Select the three reporting-segment metric IDs explicitly: Productivity and Business Processes, Intelligent Cloud, and More Personal Computing. Run this as one command:
python revenue_segmentation.py --ticker MSFT --group revenueByBusinessAndProduct --metrics productivityAndBusinessProcessesRevenue intelligentCloudRevenue morePersonalComputingRevenue --output msft-business.csvThis creates msft-business.csv, with one row per available period and a column for each selected metric. Values remain in the API’s reporting currency and base units, not millions.
These three series are Microsoft’s reporting segments. Other measures in the group, such as LinkedIn and Microsoft Cloud, overlap with them and should not be added to the total.
04 · GEOGRAPHY
Get geographic revenue in pandas and CSV
The geographic group gives you a separate table of Microsoft’s revenue in the United States and other countries.
python revenue_segmentation.py --ticker MSFT --group revenueByGeography --output msft-geography.csvOr continue from the notebook request in step 2. The helper selects only the group’s metric columns, preserves fiscal identity, and leaves missing observations blank.
from revenue_segmentation import segment_frame
geography = segment_frame(payload, "revenueByGeography")
print(geography.tail(3))
# A new file, with missing observations left blank.
geography.to_csv("msft-geography.csv", index=False, na_rep="", mode="x")| Period end | Fiscal period | United States | Other countries |
|---|---|---|---|
| 2026-03-31 | FY2026 Q3 | 42,336,000,000 | 40,550,000,000 |
| 2026-06-30 | FY2026 Q4 | 46,971,000,000 | 43,036,000,000 |
The CSV also includes ticker, reportingCurrency, normalizedPeriod, fiscalYear and fiscalQuarter. Column headers use stable metric IDs, such as unitedStatesRevenue, so a display-name change does not break your model. Responses can change as the dataset is updated.
Need annual revenue instead?
python revenue_segmentation.py --ticker MSFT --frequency annual --group revenueByGeography --output msft-geography-annual.csvRequest annual history directly instead of assuming any four quarterly rows make a complete fiscal year. Coverage can differ by company, metric and frequency.
05 · REVENUE MIX
Calculate revenue mix and segment share changes with pandas
Revenue history shows how much a segment earns. Revenue mix shows how the composition of your selected business changes. Add --revenue-mix to calculate each segment’s share and its change from the preceding quarter:
python revenue_segmentation.py --ticker MSFT --group revenueByBusinessAndProduct --metrics productivityAndBusinessProcessesRevenue intelligentCloudRevenue morePersonalComputingRevenue --revenue-mix --output msft-revenue-mix.csvUse the three reporting segments selected above. Do not add LinkedIn, Microsoft Cloud or geographic revenue to this basket: those measures overlap. A group can contain overlapping metrics; the script requires an explicit selection, but it cannot decide whether that selection is economically additive for you.
| Column | Calculation and interpretation |
|---|---|
selectedRevenueTotal | Sum of the selected non-overlapping revenue metrics for that period, in reporting-currency base units. Not an independently retrieved company total. |
…SharePercent | Segment revenue ÷ selectedRevenueTotal × 100. A value of 40 means 40% of the selected revenue basket. |
…ChangePp | Current share minus prior consecutive-period share, in percentage points. A move from 40% to 45% is +5 pp, not 5% revenue growth. |
comparisonPeriod | The normalized period used for that change. Blank on the first row, across a period gap, or when either period cannot be calculated. |
mixStatus | ok, missing_revenue, negative_revenue, or nonpositive_or_nonfinite_total. Only ok rows receive shares. |
For a notebook, reuse payload from step 2. This prints the latest four returned periods and writes a separate, full-precision CSV:
from revenue_segmentation import revenue_mix_frame
metrics = [
"productivityAndBusinessProcessesRevenue",
"intelligentCloudRevenue",
"morePersonalComputingRevenue",
]
mix = revenue_mix_frame(payload, "revenueByBusinessAndProduct", metrics)
columns = ["normalizedPeriod", "comparisonPeriod", "mixStatus"]
columns += [metric + "SharePercent" for metric in metrics]
columns += [metric + "ChangePp" for metric in metrics]
print(mix[columns].tail(4).round(2).to_string(index=False))
mix.to_csv("msft-mix-notebook.csv", index=False, na_rep="", mode="x")Turn the output into a research question
A positive intelligentCloudRevenueChangePp means Intelligent Cloud accounts for more of the selected revenue basket than in the comparison period. Check its underlying revenue alongside the other segments: a share can rise because that segment grew, because another shrank, or both. It does not by itself establish faster growth, higher margins or a better investment.
Unlike the plain history export, mix analysis retains even all-missing returned periods so you can see gaps. It does not fill missing revenue with zero or make an incomplete basket add to 100%. A genuine zero segment value is allowed when the complete basket has a positive total. Negative values are retained for review, without calculating shares.
For annual analysis, add --frequency annual and a new output filename; in a notebook pass frequency="annual" with an annual API payload. Changes then compare consecutive years. Review issuer restatements and segment reorganizations before interpreting either annual or quarterly changes.
Keep source evidence beside a model with the source-linked KPI workbook. The mix calculation uses the fields documented in All Company Metrics.
06 · RESEARCH CHECKS
Keep the meaning of the data intact
- Missing does not mean zero
- The script preserves nulls and omits rows where every selected metric is missing. It does not interpolate or forward-fill discontinued series.
- Fiscal and normalized periods differ
- For Microsoft, the quarter ending June 30, 2026 is fiscal Q4, while the API’s normalized label is
Q2'26. Join to financial statements using issuer fiscal identity and period end, not just the chart label. - Segments can change over time
- Review metric descriptions, discontinued status and issuer disclosures before comparing growth across reorganizations. The same label does not guarantee an unchanged reporting basis.
- Geographic definitions are issuer-specific
- “Other countries,” “Greater China” and “Asia Pacific” are not interchangeable. Do not present regional data as country-level exposure.
- Source references have partial coverage
- Add
includeSources="true"to the Python API request when you need available reviewed references. Inspect the response’ssourcesarray separately; the CSV script does not export it. Missing references do not imply verification.
To use another company, repeat discovery with its ticker, choose a returned group, and inspect its metric definitions. The Microsoft group IDs and three-metric selection are an example, not a universal company schema.
07 · TROUBLESHOOTING
If the export doesn’t run
- 401, 403, or no segment groups
- Check that your API key is set in this terminal, active, and entitled to the requested data. Check quota and plan coverage in the API dashboard; an empty group list is not proof the company reports no segments.
- 429 or a temporary server error
- The script retries eligible GET requests up to three times. If it still fails, wait for your rate limit to reset before rerunning. Avoid launching many parallel exports.
- Group or metric not found
- Run
--list-groupswith the same ticker and frequency. Copy the exact IDs, including capitalization, and check that each selected metric belongs to the group. - File already exists
- Choose a new
--outputfilename. The script deliberately refuses to overwrite your existing research export. - Python cannot find the module
- Run from the folder containing
revenue_segmentation.py. In a notebook, use that same folder and install the dependencies into the notebook’s Python environment.
Add segment history to your existing research workflow
Keep your current statement and price data. Use the exported segment tables alongside them, with the reporting-period and definition checks above.
Reference: VizualStocks API · Requests timeouts · pandas CSV export
