Get Tanzanian Shilling (TZS) - N/A Historical Prices using this API — Python requests example
If your product needs Tanzanian Shilling (TZS) historical prices—for example, to backfill a daily FX series for P&L reporting in Tanzania, to mark local jewelry inventory priced against metals and settled in TZS, or to normalize nickel purchase orders into a TZS base—Metals-API gives you a clean, consistent way to fetch and store those values. In this guide, we’ll focus on TZS historical prices via the Historical and Time-series endpoints and finish with a Python requests example you can copy into your pipeline.
Why TZS historical prices matter for pricing, analytics, and hedging
Whether you’re a fintech developer, a quant building risk models, or a product manager overseeing an ERP rollout, you often need reproducible foreign exchange history for audits, pricing reconciliation, or model training. Tanzanian Shilling (TZS) historical prices are particularly useful when:
- You maintain inventory, invoices, or hedges in TZS but fund operations in another currency.
- You benchmark Tanzanian import costs for metals or manufactured inputs over time.
- You reconcile settlements or internal books to a consistent, dated FX source of record.
- You build dashboards for CFOs and traders that track volatility and trend regimes in TZS.
With Metals-API, you can query TZS historical rates in a few lines and store clean, timestamped results that are easy to audit and share across teams. In addition, you can set your base currency to TZS to price metals or other supported symbols directly in TZS, or convert between TZS and metals via the Convert endpoint.
What we’ll build: a clean TZS historical time series for analytics
We’ll cover two core workflows:
- Fetch a single-day TZS historical price for a deterministic backfill on a given date.
- Fetch a multi-day TZS time series to chart trends, compute percent changes, and identify volatility regimes.
You’ll see a cURL request, a Python requests example, and realistic JSON response structures that map directly to analytics tasks. We will also cover practical details—UTC timestamps, base currency behavior, caching, and handling weekends/market closures—so you can deploy the integration confidently.
Key capabilities we’ll use
We’ll keep focus on two to three endpoints that matter for TZS historical pricing:
- Historical Rates Endpoint: fetch TZS rates for a specific historical date.
- Time-series Endpoint: fetch daily TZS rates for a date range.
- Convert Endpoint: convert between TZS and another symbol (e.g., a metal) when needed.
For broader capabilities—OHLC, fluctuation, bid/ask, LME historical data—refer to the Metals-API Documentation. You can also check which symbols are supported at any time via the Metals-API Supported Symbols page.
TZS historical pricing data model and units
Before we query, align on what you will receive:
- Base currency: By default, Metals-API expresses rates relative to USD. That means the value in rates.TZS is “TZS per USD.” If you prefer “USD per TZS,” invert the number (1 / rates.TZS).
- Timestamps and timezone: Responses include a UNIX timestamp and a date string. Treat timestamps as UTC.
- Units: For currencies (like TZS), think “quote currency per base currency.” For metals, think “per troy ounce” if you’re pulling metal prices.
- Symbols: TZS is a fiat currency symbol. If you want metals directly in TZS, you can set base=TZS to retrieve metals quoted in TZS per troy ounce.
Authentication and setup
You’ll need an API key. Create a free account on the Metals-API Website and get your access key. Keep your key private and never commit it to public repos. Use environment variables or your vault of choice.
Security best practices for your API key
- Store in secrets managers (e.g., AWS Secrets Manager, HashiCorp Vault) or environment variables.
- Scope access in CI/CD to the least privilege required.
- Rotate keys periodically and on team member offboarding.
- Instrument usage monitoring and alerts for anomalous request volume.
Endpoint 1: Historical Rates for TZS (single date)
Use the Historical Rates endpoint when you need a precise, backdated rate for a single day—for example, month-end close on a specific date. You append a date to the URL and include your access_key.
Purpose and functionality
This endpoint returns the exchange rates for the specified historical date. For our use case, we focus on the TZS rate relative to the base currency. If you keep the default base USD, the response includes how many TZS equaled 1 USD on that date.
Parameters
- date (path): Historical date in YYYY-MM-DD format.
- access_key (query): Your API key.
- base (query, optional): Defaults to USD. Set base=TZS if you want to price metals or other supported symbols directly in TZS.
- symbols (query, optional): Filter to TZS to reduce payload size when base is USD, or filter to specific target symbols when base=TZS.
Example cURL request: TZS per USD for a past date
curl -s "https://metals-api.com/api/2024-08-30?access_key=YOUR_API_KEY&symbols=TZS"
Example JSON response (historical TZS)
{
"success": true,
"timestamp": 1724976000,
"base": "USD",
"date": "2024-08-30",
"rates": {
"TZS": 2575.35
}
}
Field-by-field explanation you’ll actually use
- success: Boolean indicating request success.
- timestamp: UNIX epoch (UTC) representing the pricing time.
- base: The base currency of all returned rates. Here it’s USD.
- date: Effective historical date for the rates.
- rates.TZS: TZS per base unit. With base=USD, interpret as “TZS per 1 USD.”
Common use cases
- Accounting close: Store rates.TZS for the close date to translate USD ledger entries into TZS.
- Invoice replay: Recompute historical TZS totals for invoices denominated in USD.
- Hedge effectiveness: Compare your TZS hedge marks versus the spot history.
Pitfalls and troubleshooting
- Non-trading days and weekends: On certain dates, FX markets may close early or liquidity is thin. Expect stable values around weekends; if you see repeated values, it can be normal for static reference sources on off days.
- Base currency confusion: If you need “USD per TZS,” invert the number: usd_per_tzs = 1.0 / rates.TZS.
- Timestamp handling: Always treat timestamps as UTC. Persist both date and timestamp for auditability.
- Symbol validation: Ensure TZS is supported via the Metals-API Supported Symbols page.
Performance considerations
- Caching: Cache by (date, base, symbols) key to avoid refetching immutable history.
- Batching: Prefer Time-series for long spans instead of iterating single-date queries.
- Retry logic: Implement exponential backoff on transient network issues and handle HTTP timeouts gracefully.
Endpoint 2: Time-series for TZS (date ranges)
Use the Time-series endpoint to fetch day-by-day TZS rates for charting, volatility analysis, and training features in ML models. It returns a dictionary keyed by date.
Purpose and functionality
Query daily historical rates between start_date and end_date. For TZS, you typically ask for rates with base=USD (default) and symbols=TZS to retrieve “TZS per USD” each day. Alternatively, set base=TZS to quote metals or supported currencies per TZS over a date range.
Parameters
- start_date (query): Inclusive start date, YYYY-MM-DD.
- end_date (query): Inclusive end date, YYYY-MM-DD.
- access_key (query): Your API key.
- base (query, optional): Defaults to USD.
- symbols (query, optional): Use symbols=TZS to minimize payload.
Example cURL request: TZS per USD for a date range
curl -s "https://metals-api.com/api/timeseries?access_key=YOUR_API_KEY&start_date=2024-08-26&end_date=2024-09-02&symbols=TZS"
Example JSON response (TZS timeseries)
{
"success": true,
"timeseries": true,
"start_date": "2024-08-26",
"end_date": "2024-09-02",
"base": "USD",
"rates": {
"2024-08-26": { "TZS": 2572.10 },
"2024-08-27": { "TZS": 2573.55 },
"2024-08-28": { "TZS": 2574.20 },
"2024-08-29": { "TZS": 2574.90 },
"2024-08-30": { "TZS": 2575.35 },
"2024-08-31": { "TZS": 2575.35 },
"2024-09-01": { "TZS": 2575.35 },
"2024-09-02": { "TZS": 2576.00 }
}
}
How to use these fields
- rates[date].TZS: TZS per USD for each date. Weekend values may repeat the last available fixing.
- start_date / end_date: Confirm your training or reporting window coverage.
- base: Confirm consistency across runs; mixing base currencies will corrupt downstream analytics.
Derived analytics examples
- Day-over-day pct change: (TZS_t / TZS_t-1) - 1
- Volatility estimate: compute rolling standard deviation of pct changes.
- Regime flags: label stretches of strengthening/weakening TZS for risk overlays in procurement tools.
Practical tips
- Missing days: If your date window includes holidays, expect flat repeats or no changes; forward-fill to keep a continuous series for models that require it.
- Storage schema: Use a composite key of (date, base, symbol). Store raw JSON if needed for audit replays.
- Validation: After fetching, assert base==expected and presence of TZS in each date slice; log any anomalies.
Endpoint 3: Convert TZS to/from other symbols (optional add-on)
When you need to quote metals directly in Tanzanian Shilling or translate TZS amounts to another symbol, use the Convert endpoint. This is helpful for pricing nickel imports to TZS or reconciling USD invoices paid in TZS.
Purpose and functionality
Convert a monetary amount from one symbol to another. With TZS, common patterns include:
- Convert TZS to USD for accounting normalization.
- Convert USD to TZS for local pricing and payroll planning.
- Convert between TZS and a supported metal symbol to price inventory or POs in TZS.
Parameters
- from (query): Source symbol (e.g., TZS or USD).
- to (query): Destination symbol (e.g., USD or a metal symbol).
- amount (query): Numeric amount to convert.
- access_key (query): Your API key.
Example cURL: Convert 1,000,000 TZS to USD
curl -s "https://metals-api.com/api/convert?access_key=YOUR_API_KEY&from=TZS&to=USD&amount=1000000"
Example JSON response (conversion)
{
"success": true,
"query": {
"from": "TZS",
"to": "USD",
"amount": 1000000
},
"info": {
"timestamp": 1724976000,
"rate": 0.0003882
},
"result": 388.2
}
How to interpret
- info.rate: USD per TZS in this example. Multiplying rate by amount yields result.
- result: Converted amount (here, 1,000,000 TZS equals 388.2 USD at the given rate).
- timestamp: Use this for auditability and to track when the conversion rate was observed.
Implementation guidance
- Deterministic conversions: For historical conversions, pair Convert with a specific historical date or retrieve the historical rate first to lock in pricing.
- Rounding: Decide on rounding modes for financial correctness (e.g., bankers’ rounding for accounting).
- Idempotency: Cache conversions keyed by (from, to, amount, date) to ensure consistent results across retries.
Python requests example: building a TZS timeseries backfill
Below is a minimal Python requests example that fetches a TZS time series and computes daily percent changes. You can adapt this into your data pipeline or notebook. Be sure to set your API key securely as an environment variable.
# Python 3 example: Fetch TZS time series and compute daily pct change
import os
import sys
import json
from datetime import date, timedelta
import requests
API_KEY = os.getenv("METALS_API_KEY")
if not API_KEY:
sys.exit("Please set METALS_API_KEY in your environment")
start_date = "2024-08-26"
end_date = "2024-09-02"
url = "https://metals-api.com/api/timeseries"
params = {
"access_key": API_KEY,
"start_date": start_date,
"end_date": end_date,
"symbols": "TZS"
}
resp = requests.get(url, params=params, timeout=20)
resp.raise_for_status()
data = resp.json()
if not data.get("success"):
raise RuntimeError(f"API error: {data}")
base = data.get("base")
if base != "USD":
raise ValueError(f"Unexpected base {base}, expected USD")
rates = data.get("rates", {})
# Extract sorted dates
dates = sorted(rates.keys())
series = [(d, rates[d]["TZS"]) for d in dates if "TZS" in rates[d]]
# Compute simple day-over-day percent change
pct_changes = []
for i in range(1, len(series)):
prev_d, prev_v = series[i-1]
curr_d, curr_v = series[i]
if prev_v and curr_v:
pct = (curr_v / prev_v) - 1.0
pct_changes.append((curr_d, pct))
print("TZS per USD time series:")
for d, v in series:
print(d, v)
print("\nDay-over-day percent changes:")
for d, pct in pct_changes:
print(d, round(pct * 100, 4), "%")
What this example demonstrates
- How to parameterize start and end dates for a backfill.
- How to validate base currency and handle missing symbols safely.
- How to compute daily changes as a quick proxy for volatility.
Understanding response fields you’ll actually consume
- success: Use it as a first guard; if false, parse the error payload and decide on retry vs. fail.
- timestamp: Store it alongside the date for forensic accuracy and consistent replays.
- base: Critical for interpreting rates; never mix bases in the same dataset without normalizing.
- rates: A mapping from symbol to numeric rate. For TZS, interpret as “TZS per base” when base=USD.
- timeseries / start_date / end_date: Indicates a range response; ensure your window matches expectations.
- query/info/result (Convert): Supports transparent conversions; log the rate and timestamp for audit.
Advanced use cases: pricing metals in TZS
Suppose your Tanzanian operations want daily nickel costs in local currency. You can set base=TZS on the Latest, Historical, or Time-series endpoints and request the appropriate metal symbol to receive “metal price per troy ounce, denominated in TZS.” While our focus in this post is TZS FX history, this integration pattern makes it trivial to:
- Mark-to-market inventory in TZS.
- Quote spot offers to local customers in TZS.
- Budget procurement with TZS volatility baked in.
To explore metal symbols and confirm availability, review the full list of supported symbols. For precise endpoint parameters when quoting metals in a non-USD base, see the endpoint documentation.
Data sanity checks and validation
- Monotonic weekends: If a Saturday/Sunday repeats Friday’s rate, that can be expected for reference feeds. Don’t treat that as an anomaly unless your business logic requires settlement-only days.
- Outlier guardrails: Set percent-change thresholds and flag extreme moves for manual review.
- Base drift: Hard-fail if base changes mid-job. Normalize or restart the job with a consistent base.
- Schema versioning: Persist a simple schema version in your warehouse to handle downstream transformations predictably.
Caching and performance optimization
- Immutable history cache: Since historical data doesn’t change, cache responses by endpoint, date window, base, and symbols.
- Eager backfills: Prefetch month-to-date and prior month in a single time-series call to minimize round-trips.
- Concurrency: For large backfills, shard by year or quarter. Respect your plan’s request cadence.
- Compression: Enable gzip on HTTP requests; store compressed payloads for audit logs to save space.
Error handling, retries, and recovery strategies
- HTTP layer: Retry 429/5xx with exponential backoff and jitter. Cap retries to avoid runaway loops.
- Application errors: Inspect success=false payloads, log error codes/messages, and surface actionable diagnostics.
- Partial data: If a time-series call returns a subset of dates, record which dates are missing and schedule a targeted retry.
- Idempotency: Write results with upserts keyed by (date, base, symbol) so reruns don’t duplicate data.
Security considerations
- Key management: Store API keys securely and rotate periodically.
- Outbound egress control: Restrict your network egress policies to approved domains.
- Least privilege CI/CD: Inject keys at deploy time only to jobs that need them.
- PII free: The data here is rates, not PII, but apply your org’s data governance tagging and retention policies.
Integrating TZS history into analytics and apps
- Warehousing: Land raw JSON in a data lake, then ETL to structured tables: fx_daily(base, quote, date, rate, timestamp).
- BI dashboards: Build TZS trend charts and YoY comparisons for CFO and procurement teams.
- Risk engines: Use daily pct changes for VaR approximations and stress tests on TZS exposures.
- Fintech apps: Show transparent conversion breakdowns at checkout or in remittance flows.
About nickel, digital transformation, and local pricing in TZS
As the metals market digitizes, combining metals pricing with local currency views such as TZS is becoming essential. For Tanzanian manufacturers importing nickel-based alloys, having TZS-denominated historical series supports smarter inventory hedging and cost-plus quoting. Developers can incorporate TZS series into planning tools that forecast TZS cash needs under different nickel price paths, bringing together data analytics, smart alerts, and ERP integration. The same architecture you build for TZS FX history scales to nickel-in-TZS pricing and variance analysis without major refactors.
Units and conversions: troy ounces vs grams when quoting in TZS
- Metals are quoted per troy ounce by default. If you need grams or kilograms in TZS, convert units after retrieval: 1 troy ounce ≈ 31.1034768 grams.
- Flow: Fetch metal price in TZS per troy ounce → convert to TZS per gram → multiply by grams needed.
- Be explicit about unit labels in UI and reports to avoid confusion across procurement and finance teams.
Handling weekends and market closures with TZS
- Expect flat values across weekends if the feed references last known prices.
- Set business rules for weekend display (e.g., gray-out points) and ensure backtests treat flat segments correctly.
- For backdated accounting, align to your policy—e.g., last business day close vs. calendar day mark.
Versioning and change management
- Pin your integration to a tested response shape. If you evolve parsing logic, deploy behind a feature flag.
- Add contract tests: Validate presence and type of fields (success, base, date/timeseries, rates.TZS).
- Telemetry: Record fetch durations, success ratios, and endpoint usage to inform scaling decisions.
End-to-end checklist for TZS historical rates
- Obtain API key from the Metals-API Website and store it securely.
- Decide base currency (keep USD for FX history; use TZS when pricing metals in local currency).
- Build single-date Historical fetch for deterministic backfills.
- Build Time-series fetch for windows, with caching and forward-fill as needed.
- Add Convert for explicit currency translations and TZS price displays.
- Implement retries, logging, and schema validation.
- Persist data with composite keys and audit fields (timestamp, source, request params).
Where to go next
- Get your free API key now: visit the Metals-API Website and start integrating.
- Explore endpoint details and more advanced features in the Metals-API Documentation.
- Confirm symbol coverage for TZS and any metals you plan to quote via the Supported Symbols list.
Frequently Asked Questions
Does Metals-API support TZS historical prices?
Yes. You can request TZS as a currency symbol. With base=USD (default), you’ll receive “TZS per USD” for historical dates or time ranges.
How do I invert TZS to get USD per TZS?
Compute 1.0 / rates.TZS when base=USD to obtain “USD per TZS.” Persist both forms if different teams prefer different conventions.
Can I price metals directly in TZS?
Yes. Set base=TZS and request the relevant metal symbols so you receive “TZS per troy ounce.” Then convert to grams or kilograms if needed.
How should I handle weekends and holidays?
Expect static values for calendar dates that fall on weekends. If your policy is business-day only, filter or forward-fill accordingly.
What’s the best way to minimize requests for historical backfills?
Use the Time-series endpoint for ranges, cache immutable results by parameter set, and retry only for missing or errored slices.
Where can I find all supported symbols?
See the full up-to-date list here: Metals-API Supported Symbols.
How do I get started?
Sign up and get your key on the Metals-API Website, then review the Documentation for endpoint specifics and examples.