Understanding Data Types, Data Structures, and Data Sources#
Before we write code to analyze data, we need to understand what data actually is. In practice, data comes in many forms—numbers, text, timestamps, categorical labels, images, transaction records—and each form affects how we load, clean, interpret, store, and model it.
Different types of data:
are stored and structured in different ways,
permit different operations,
require different cleaning or transformation steps,
influence the choice of visualization,
and determine which statistical or machine-learning models are appropriate.
These differences show up everywhere in finance: market prices, order-book data, economic indicators, corporate fundamentals, credit histories, blockchain events, and more. Knowing what kind of data you are working with and how it is represented is the first step toward working with it effectively.
By the end of this chapter, you will understand:
how core data types (numbers, text, booleans, timestamps) behave,
how Python represents these types internally,
how composite structures like lists, dictionaries, Series, and DataFrames organize data,
and how different data sources (files, APIs, databases, web streams) shape the workflows you will build.
We’ll use plain Python here. In later chapters, you’ll see how NumPy and pandas build on top of these foundational ideas.
Why Data Matters in Finance#
Finance is built on data. Every valuation, risk estimate, trading strategy, customer decision, regulatory report, and audit trail originates from structured, semi-structured, or unstructured data. Understanding what kind of data you’re working with — and how it’s represented — directly affects the quality of every analysis that follows.
Financial decisions depend on precision#
Minor numerical errors can cascade into significant financial consequences. A rounding mistake in currency conversion, an incorrectly parsed timestamp, or a misclassified transaction can:
distort performance metrics,
trigger incorrect trading signals,
misstate risk exposure, or
lead to compliance violations.
Financial models are only as reliable as the data they rely on. Precise representation and interpretation of data types is therefore not optional — it’s foundational.
Different data types allow different operations#
Not all data behaves the same. An interest rate, a trade timestamp, a customer ID, and a credit rating look simple on the surface, but require very different handling:
You can add and average numeric values.
You cannot average categorical labels without encoding them.
You can compute time deltas from timestamps, but not from raw strings.
Boolean fields drive filters, masks, and logic, not arithmetic.
Using the wrong type (e.g., storing a date as a string) silently breaks analyses. Choosing the right type simplifies, speeds up, and makes operations more reliable.
Data structure determines how we access and interpret information#
The shape of data — not just its values — determines how we work with it:
A list preserves order but not relationships.
A dictionary models mappings, such as ticker → price.
A table (DataFrame) organizes rows and columns for analytics.
Nested records (JSON) capture hierarchical financial objects, like order books or transaction metadata.
Poorly structured data leads to complex, fragile code. Well-structured data reduces friction and reveals the underlying relationships.
Financial data comes from diverse sources#
Real financial workflows rarely rely on one source. Instead, they integrate:
market feeds (order books, trades, quotes),
corporate fundamentals and regulatory filings,
customer transactions and behavioral logs,
economic indicators and macro datasets,
blockchain events, and
internal systems or partner APIs.
Each source introduces variation in:
format,
frequency,
reliability,
latency, and
structure.
A key skill in financial engineering is understanding how to unify these heterogeneous sources into a coherent analytical pipeline.
Takeaway#
Data matters because every financial computation depends on its type, structure, and origin. Before analyzing or modeling anything, a practitioner must understand:
what the data represents,
how it is stored,
what operations are valid,
and what risks arise from misinterpretation.
This chapter builds that foundation.
Primitive Data Types#
Primitive data types represent the smallest units of information in Python — individual numbers, booleans, and pieces of text.
Although they seem simple, choosing the right type affects:
numerical accuracy,
memory usage and performance,
the validity of computations,
and the reliability of financial analysis.
Before examining each type, we need to understand Python’s underlying model.
Everything Is an Object in Python#
Unlike languages such as C or Java, Python does not have low-level primitives. Instead:
Every value in Python is an object — including integers, floats, booleans, strings, and None.
This means:
each value has a type (int, float, str, etc.),
each value has methods and attributes,
all values live on the heap,
variables are references (pointers), not storage boxes.
1x = 5
2x.bit_length() # Works because 5 is an int object
3
Even 5 is a full object with behavior defined by the int class.
Why this matters in finance:
Python integers can grow arbitrarily large (no overflow),
floats behave consistently as IEEE-754 objects (with known limitations),
strings are immutable, which reduces bugs in data pipelines,
Decimalobjects carry precise arithmetic rules, critical for currency,Booleans behave as a specialized integer subclass, useful for masks and filtering.
Understanding Python’s object model provides a foundation for reasoning about mutability, performance, and numerical correctness.
Numeric Types: int, float, Decimal#
Numbers dominate financial systems: prices, quantities, rates, balances, and timestamps all depend on correct numeric representation.
Python offers several numeric types, each suited to different tasks.
Integers (int)#
Integers represent whole numbers without fractions.
Common financial examples:
number of shares traded
days to maturity
count of transactions
unique identifiers (though IDs should not be treated as numeric quantities)
Properties:
unlimited precision
exact arithmetic
safe for operations that cannot tolerate rounding error
Integers are great for counting and indexing, but not for continuous quantities.
1shares = 75
2days_to_settle = 2
Floating-Point Numbers (float)#
Floats represent real numbers but with limited precision. They are fast and widely used, but cannot represent most decimal fractions exactly.
1print(0.1 + 0.2 == 0.3) # False due to binary floating-point rounding
2print(0.1 + 0.2) # 0.30000000000000004
False
0.30000000000000004
0.1 + 0.2 == 0.3 # False due to binary floating-point rounding
Appropriate for:
rates of return
statistical metrics (mean, variance, volatility)
optimization routines
ML and numerical computing frameworks
Not appropriate for:
currency
ledger balances
financial contracts
cumulative interest calculations
Float rounding errors accumulate silently, making them dangerous for monetary work.
Exact Decimal Numbers (Decimal)#
The decimal.Decimal type provides base-10 exact arithmetic — matching how humans and financial institutions handle money.
1from decimal import Decimal
2Decimal("0.1") + Decimal("0.2") == Decimal("0.3") # True
True
However, you still have to avoid conversion errors, especially when using floats.
1from decimal import Decimal
2from decimal import ROUND_HALF_UP
3
4print("expected:", Decimal("0.1") + Decimal("0.2"))
5
6# Potential pitfall when using Decimal with floats
7print("pitfall:", Decimal(0.1) + Decimal(0.2))
8
9# Python recmommends creating Decimals from strings to avoid precision issues,
10# but this can be done from floats if you quantize the result.
11Decimal.from_float(3.14159).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
expected: 0.3
pitfall: 0.3000000000000000166533453694
Decimal('3.14')
Advantages:
no hidden rounding errors
configurable precision and rounding rules
compliance with accounting standards
Use Decimal for:
prices and currency
tax and fee calculations
FX conversions
interest accrual
audit/compliance systems
Decimals are slower than floats, but correctness matters more than speed in financial applications involving money.
When to use which numeric type#
Requirement |
Use |
Reason |
|---|---|---|
Exact cents/dollars |
|
Prevents rounding drift |
Whole counts |
|
Exact and efficient |
Vectorized math, ML, statistics |
|
Extremely fast |
Time intervals |
|
Simple and efficient |
Rule of thumb:
Use Decimal for money, int for counts, and float for analytical/continuous quantities.
Boolean Data: True and False#
Booleans represent decisions, conditions, and logic - concepts that are binary states.
In financial systems, booleans appear everywhere:
Is a company in the S&P 500?
Is the stock price above its 200-day moving average?
Did the portfolio outperform the benchmark today?
Is the customer’s account active?
Has a risk threshold been reached.
Although booleans behave like integers (True == 1, False == 0), they should be treated as logical values unless intentionally aggregated (e.g., proportion of trades that were profitable).
1amount = 1200
2limit = 1000
3
4is_over_limit = amount > limit
5is_over_limit
True
Common boolean variables include items such as -
is_fraud_suspectedis_active_accountis_trading_dayis_margin_call_triggered
Booleans also form the basis of filtering, classification, and rules engines.
Strings: Textual and Categorical Data#
Strings are a fundamental data type representing textual information. In financial data science, strings are less often used for prose and more often as labels that encode critical information:
Categories: Transaction channels (
'mobile','web'), bond ratings ('AAA','junk'), or security types ('common stock','warrant').Identifiers: Ticker symbols (
'AAPL','MSFT'), CUSIPs, ISINs, or account numbers.Metadata: Status codes, log messages, or flags.
Semi-structured Data: Complex financial identifiers (
'USD/JPY','EURUSD=X') or log lines.
As strings come from heterogeneous systems, they are also one of the most error-prone data types:
inconsistent casing, punctuation, or whitespace
multiple formats representing the same concept
embedded structure that must be extracted
typos, aliases, and system-specific naming conventions
Strings are essential but introduce unique challenges that typically account for the majority of data-cleaning effort. These challenges involve converting raw, unstructured, or inconsistent text into a usable, consistent format.
Parsing#
Parsing is the process of extracting structured data (numbers, dates, typed identifiers) embedded within a string field. Raw financial data often embeds multiple pieces of information into a single text string.
Example 1 (Time Series): Extracting the timestamp and value from a log line like
'2024-02-14T09:30:00Z | TRD | AAPL | 185.50'.Example 2 (Complex Tickers): Decoding a corporate bond identifier that encodes the issuer, maturity date, and coupon rate.
Outcome: Transforms messy text into correctly typed data (e.g., converting a text date '12/6/2025' into a proper datetime object) essential for numerical analysis.
Cleaning and Normalization#
These two steps are often performed together but serve distinct purposes:
Concept |
Goal |
Problem Solved |
Example |
|---|---|---|---|
Cleaning |
Fix the format of the string. |
Inconsistent capitalization, extra whitespace, or noise characters. |
|
Normalization |
Standardize the meaning (semantics). |
Multiple valid strings referring to the same concept. |
|
Cleaning ensures strings are well-formed and comparable. Normalization ensures that all syntactic variations of a concept are mapped to a single, canonical label for accurate grouping, aggregation, and joining.
Entity Resolution#
Entity resolution is the process of ensuring that different string representations referring to the same real-world entity are recognized as identical. It is crucial in finance where entity names are highly variable:
Inconsistent Naming:
'J.P. Morgan','JP Morgan', and'JPMorgan Chase'.Synonyms/Aliases:
'MSFT'and'Microsoft Corp'.
Objective: To unify records and prevent artificial inflation of counts (de-duplication) or failed joins. This often involves applying sophisticated rules, fuzzy matching, or mapping to a trusted external identifier (e.g., a Legal Entity Identifier or LEI).
String Wrap-Up#
Strings are deceptively simple but foundational to financial datasets, where most identifiers, labels, and classifications are text-based. Mastery of string handling, encompassing parsing, cleaning, normalization, and entity resolution, is arguably the most critical and time-consuming prerequisite for successful financial data analysis. It is where the most significant complexity and effort in data preparation reside.
From Representation to Meaning#
These primitive types describe how data is represented inside a program, but representation alone is not enough. We must also understand what the data represents:
some values are categories,
some are ordered rankings,
some are continuous quantities,
and others are identifiers that must never be averaged or added.
To work with financial data responsibly, we must distinguish not just how data is stored but what analytical role it plays.
Statistical Meaning and Levels of Measurement#
Understanding how data is represented inside a program (ints, floats, strings) is important — but it is only the beginning. To work responsibly with financial data, we also need to understand what each value represents in the real world. Different kinds of data support different operations, transformations, visualizations, and models. Using the wrong technique for the wrong type can produce misleading or even invalid results.
This brings us to the idea of statistical meaning.
Qualitative vs. Quantitative Data#
Before examining the detailed levels of measurement, it helps to divide data into two broad families: qualitative and quantitative.
Qualitative Data (Categorical Data)#
Qualitative data describes categories, labels, or classes, not numerical amounts.
Examples in finance:
industry sector:
"Energy","Technology"order type:
"LIMIT","MARKET"credit ratings when treated as labels (e.g.,
"AAA","BBB")customer segment:
"Retail","Wealth"ticker symbols or product codes
You cannot add or average qualitative values. Instead, they are used for grouping, counting, segmentation, filtering, and classification.
Quantitative Data (Numeric Data)#
Quantitative data represents measurable amounts or numeric magnitudes.
Examples:
prices, quantities, balances
returns and rates
days to maturity
volatility, risk measures
trading volume
Quantitative values support arithmetic, statistical modeling, and continuous analysis.
how they connect to levels of measurement#
Qualitative data aligns with nominal and sometimes ordinal levels.
Quantitative data aligns with interval and ratio levels.
A simple summary:
Qualitative data tells you what something is. Quantitative data tells you how much there is.
With this foundation established, we can now look at the four classic levels of measurement.
Levels of Measurement#
Levels of measurement describe not just how data is stored, but what operations and interpretations are valid.
Nominal Data (Categories Without Order)#
Nominal data consists of labels with no inherent ordering.
Financial examples:
ticker symbols (
"AAPL","MSFT")sector classifications (
"Energy","Utilities")country or currency codes
order types (
"LIMIT","MARKET")customer segments
Valid operations:
grouping
counting
computing proportions
Invalid operations:
ordering categories
averaging identifiers
interpreting numeric codes as magnitudes
Ordinal Data (Ranked Categories)#
Ordinal values have an inherent order, but the “distance” between categories is unknown or unequal.
Examples:
credit ratings (
AAA > AA > A > BBB > …)risk tiers (
Low,Medium,High)customer loyalty levels (
Silver,Gold,Platinum)satisfaction surveys (
1–5ratings)
Valid operations:
comparisons (
>,<)sorting
Invalid operations:
subtracting levels
averaging ordinal encodings
Even if encoded numerically, ordinal values are not continuous quantities.
Interval Data (Meaningful Differences, Arbitrary Zero)#
Interval data allows addition and subtraction, but has no true zero point.
Examples in finance:
timestamps
calendar dates
time-of-day values
index values in some alternative datasets
Valid operations:
compute differences (e.g., days between trades)
averaging values
Invalid operations:
ratios (“twice as late”, “three times the date”)
interpreting zero as “absence”
The distance matters; the absolute value does not.
Ratio Data (Full Numeric Quantities with True Zero)#
Ratio data has:
meaningful differences
meaningful ratios
a true zero representing absence
This is the most powerful and common measurement level in finance.
Examples:
prices
returns expressed as multipliers
balances and quantities
spreads, fees, taxes
trade sizes
days-to-maturity, when treated as duration
Valid operations:
all arithmetic
scaling, normalizing
geometric and harmonic means
Why Levels of Measurement Matter in Finance#
Two fields might both be stored as int or float in Python but have completely different statistical meanings.
Examples:
client_id = 10491→ nominal (identifier, not a quantity)risk_tier = 3→ ordinal (rank, not a magnitude)days_to_maturity = 90→ ratio (true numeric quantity)trade_timestamp = '2024-02-10'→ intervalindustry = 'Energy'→ nominal
Using the wrong operations on the wrong type leads to errors like:
averaging identifiers,
treating ordinal levels as continuous,
correlating dates without converting to intervals,
using nominal fields in numeric models without encoding.
Financial data is full of subtle traps because many fields look numeric but are not.
Before running any analysis, always ask:
What does this value represent in the real world, and what operations does that meaning allow?
Level |
Meaning |
Valid Operations |
Invalid Operations |
Financial Examples |
|---|---|---|---|---|
Nominal |
Unordered categories |
count, mode |
sort, subtract |
ticker symbol, sector, country |
Ordinal |
Ordered categories, unknown spacing |
rank, compare |
add, average |
credit ratings (AAA > AA > A), risk tiers |
Interval |
Numeric scale, equal spacing, no true zero |
add, subtract |
ratios (“twice as much”) |
dates, times, temperatures, log returns |
Ratio |
Numeric scale with meaningful zero |
add, subtract, multiply, divide |
none |
prices, volumes, balances, returns |
From Meaning to Computation#
Levels of measurement help determine:
what transformations are appropriate,
how to encode categories,
which models can be used,
how to engineer features correctly,
and how to interpret results responsibly.
With this conceptual foundation, we can now transition into the computational side: how tools like NumPy represent arrays of values, enforce type constraints, and perform vectorized operations that respect these meanings.
Dates, Times, and Time Deltas#
Financial data is inseparable from time.
Prices evolve over time, trades occur at specific instants, contracts have maturities, and economic indicators follow reporting periods. Because of this, timestamps and date-like fields require careful handling. They are not just strings or numbers — they carry temporal meaning that determines what operations are valid.
But time data is also one of the most complex data types due to:
different time frequencies,
irregular intervals,
time-zone differences,
daylight savings changes,
market closures and holidays,
changing calendars,
and the math required to compute differences between timestamps.
As such, we’ve provided more details on date and time datea as compared to many of the other types covered. Do not focus too much on the details now, but keep this section in mind as you begin to analyze data with date/time fields.
The built-in datetime module provides the essential tools.
Most financial workflows also rely heavily on pandas, which builds on these core objects with more powerful time-aware indexing and frequency support.
Dates (datetime.date)#
A date represents a calendar day without any time-of-day information.
Examples in finance:
trade settlement date
option expiration date
earnings announcement date
coupon payment date
Valid operations include:
comparing dates (
<,>)computing differences
determining weekdays/weekends
aligning with business calendars
Invalid operations:
multiplying dates
interpreting a date numeral as a quantity
subtracting without converting meaningfully (e.g., “20240210” - “20240110” as strings)
1from datetime import date
2
3trade_date = date(2024, 2, 10)
4settlement = date(2024, 2, 13)
5
6days_to_settle = (settlement - trade_date).days
7days_to_settle
3
DateTime (datetime.datetime)#
A datetime includes both a date and a specific time-of-day, optionally with a timezone.
Examples:
timestamp of a trade execution
when a market data tick arrived
the moment a client authenticated
when a margin call was triggered
Financial analysis often depends on:
ordering events precisely
adjusting timestamps for timezones
aligning trades to the market session
calculating time lags (latency between event arrival and processing)
1from datetime import datetime
2
3trade_timestamp = datetime(2024, 5, 1, 9, 30, 15)
4trade_timestamp
datetime.datetime(2024, 5, 1, 9, 30, 15)
Generally speaking, you should always use timezone aware datetimes.
Times (datetime.time)#
A time object represents a clock time without a date.
Used for:
defining market open/close hours
intraday schedule boundaries
recurring events (e.g., 4pm NAV calculation)
Times are less commonly stored directly, but they’re important for session logic — e.g., “flag trades occurring before market open.”
Time Deltas (datetime.timedelta)#
timedelta represents the difference between two dates or datetimes.
In finance, time deltas matter for:
holding periods,
duration of trades,
time between transactions,
accrual calculations (e.g., interest, bond coupons),
volatility estimation (annualizing std dev),
computing business-day differences (e.g., T+2 settlement).
1from datetime import timedelta
2
3trade = datetime(2024, 5, 1, 9, 30)
4settlement = datetime(2024, 5, 3, 9, 30)
5
6settlement - trade
datetime.timedelta(days=2)
Time Zones#
Financial markets do not share a common time zone:
NYSE closes at 4 PM Eastern Time
London Stock Exchange: GMT/BST
Tokyo Stock Exchange: JST
Crypto exchanges: global, often UTC-based
APIs may return timestamp data in UTC
Time-zone problems arise when:
merging data from multiple markets,
comparing returns on global portfolios,
timestamping events from different systems,
computing intraday indicators across markets.
Example Pitfall
A trade recorded at 16:01 UTC might be:
just after close in New York,
mid-evening in London,
early morning in Tokyo.
If your timestamps aren’t localized (e.g., tz_localize("America/New_York")), analytics can break.
Later in pandas:
ts = ts.tz_localize("UTC").tz_convert("America/New_York")
** Naive vs. Aware Timestamps (Time Zones) **
A major source of real-world bugs.
Naive datetime
No timezone attached. Python assumes nothing.
Aware datetime
Explicitly linked to a timezone (UTC, US/Eastern, etc.)
# Naive timestamps (no timezone info)
t1 = datetime(2024, 5, 1, 16, 0) # 4 PM "somewhere"
t2 = datetime(2024, 5, 1, 20, 0) # 8 PM "somewhere"
# We cannot reliably compare them without knowing the timezone!
Irregular Timestamps#
Not all financial data is evenly spaced:
Examples
Trades occur whenever someone buys or sells — timestamps are irregular.
News events arrive at unpredictable times.
Crypto markets trade continuously, unlike stock exchanges.
Corporate actions happen on specific but irregular dates.
Working with irregular timestamps often requires:
resampling (e.g., converting trades → 1-minute bars)
aggregation (OHLC: open, high, low, close)
interpolation (fill missing minutes)
forward-fill (carry the last known price)
Later in pandas, we’ll use:
prices.resample("D").last()
trades.resample("1min").agg({"price": "last", "volume": "sum"})
to regularize uneven time series.
timestamps = [
datetime(2024, 5, 1, 9, 30, 1),
datetime(2024, 5, 1, 9, 30, 1, 500000),
datetime(2024, 5, 1, 9, 30, 2),
]
timestamps
Frequency Mismatches#
In finance, different datasets come in different frequencies:
Data Type |
Frequency |
|---|---|
Market prices |
daily / minute / second / tick |
Fundamentals |
quarterly / annual |
Economic indicators |
monthly / quarterly |
Transactions |
irregular, event-driven |
Problems arise when combining datasets:
price is daily but financial statements are quarterly
interest rates may be quoted annually but accrued daily
intraday data must be aligned to daily close
This is one of the most common errors made by inexperienced analysts.
Business Time vs. Calendar Time#
A critical concept in finance is the difference between:
Calendar time
Includes weekends and holidays.
Useful for things like date-based reporting.
Business time
Excludes weekends and market holidays.
Essential for:
calculating trading days
computing returns over business intervals
modeling volatility
creating features aligned with trading sessions
ISO 8601: The Standard for Representing Dates and Times#
In real-world financial systems, timestamps often come from multiple sources — exchanges, brokers, internal services, logs, APIs, and client devices. These sources may use inconsistent or ambiguous formats like:
02/10/24 9:30 AM
10-02-2024 09:30
2/10/2024 09:30:00 EST
Without context, even a simple date like "02/10/24" is ambiguous:
Is it February 10th?
Or October 2nd?
Or 1924?
Or 2024?
To avoid these ambiguities, most modern financial systems rely on ISO 8601, the international standard for representing dates and times in a consistent, unambiguous, machine-friendly way.
What ISO 8601 Looks Like#
The core format is:
YYYY-MM-DD
Examples:
2024-02-10
2023-12-31
Timestamps add time-of-day using 24-hour format:
2024-02-10T09:30:00
Including UTC time (with “Z”):
2024-02-10T09:30:00Z
Including offsets for timezones:
2024-02-10T09:30:00-05:00 # Eastern Time
2024-02-10T14:30:00+00:00 # UTC
ISO 8601 uses:
Tas the separator between date and timeZto indicate UTC (“Zulu time”)+HH:MMand-HH:MMto represent timezone offsets
This format avoids nearly all cross-regional ambiguity.
Why ISO 8601 Matters in Finance#
Financial systems depend on precise, unambiguous time alignment:
matching quotes and trades
computing time-weighted returns
latency measurement
market data replay and backtesting
regulatory reporting (MiFID II, FINRA CAT)
cross-region trading where markets open in different timezones
When timestamps are not in ISO format, errors creep in silently — especially when logs are merged, ingested, or compared across systems.
Using ISO 8601 ensures:
consistency across services
correct sorting (ISO timestamps sort lexicographically)
easy parsing in Python and pandas
timezone clarity when offsets are included
ISO 8601 in Python#
Python’s datetime and pandas both handle ISO formats naturally.
Parsing:
from datetime import datetime
ts = datetime.fromisoformat("2024-02-10T09:30:00")
With timezone:
ts = datetime.fromisoformat("2024-02-10T09:30:00-05:00")
Parsing ISO timestamps “just works,” which is a major reason to use them.
ISO 8601 provides:
a single, unambiguous format,
clear timezone representation,
correct sorting and comparison behavior,
compatibility with nearly all financial data tools.
Whenever you design a data pipeline, define a schema, or record timestamps, prefer ISO 8601 — it prevents subtle but consequential errors that can propagate through downstream analysis.
Summary: Temporal Data Is About Meaning#
Working with time in finance requires understanding:
what kind of temporal value you have (date vs datetime vs timedelta)
what operations are valid for that type
how timezones, DST, and market calendars affect meaning
how to convert raw strings into true temporal objects
Time values are not just numbers or strings — they encode real-world constraints that must be handled with precision.
Structured, Semi-Structured, and Unstructured Data#
Data in financial systems does not come in a single, uniform form. Some datasets are clean and tabular. Others are nested, event-oriented, or completely unstructured. Understanding these distinctions is essential because each type requires different tools, transformations, and modeling strategies.
There are three broad categories:
Structured data (tables with defined fields)
Semi-structured data (partially organized, flexible schema)
Unstructured data (free-form, no predefined structure)
Each category affects how we store, parse, transform, and analyze information.
Structured Data#
Structured data adheres to a well-defined schema: fixed fields, consistent types, and predictable layout. This is the most common form in databases, spreadsheets, and financial analysis.
Examples in finance:
Trade blotters
Order execution reports
Customer master records
Market data snapshots
Securities reference data
Transaction ledgers
Characteristics:
predictable schema (columns, types, constraints)
rows representing repeated entities
easily validated
easily queried with SQL
ideal for statistical and machine-learning models
Typical Python representation:
1trade = {
2 "ticker": "AAPL",
3 "price": 189.22,
4 "quantity": 100,
5 "timestamp": "2024-05-01 09:30:05"
6}
7trade
{'ticker': 'AAPL',
'price': 189.22,
'quantity': 100,
'timestamp': '2024-05-01 09:30:05'}
Why structured data matters:
Easy to query and filter
Easy to aggregate (sum, average, group)
Ideal for relational databases and later Pandas DataFrames
Most machine learning workflows ultimately rely on structured data - much of the work that we need to perform with datasets is transitioning to structured data when the data is in one for the following formats:
Semi-Structured Data#
Semi-structured data sits between structured and unstructured data.
It typically has some predictable fields (timestamps, IDs, codes) combined with free-form or irregular content in the same record.
Unlike purely structured data, semi-structured records:
don’t always follow a strict, fixed schema,
may have optional or varying fields,
often mix well-defined attributes with unstructured text.
Examples in finance and computing:
Web server logs: each line might contain a timestamp, IP address, HTTP status code (structured), plus a request URL or user agent string that can be long, messy, and only partially structured.
API responses: JSON objects with some standard keys (e.g.,
ticker,price,timestamp) and a nestedmetaordescriptionfield containing free-form text.Event logs: trading or risk system logs where each event has an ID, time, and type, but the message field is a human-written explanation.
Semi-structured data is often self-describing (e.g., key–value pairs, tagged fields), which makes it easier to parse than raw text, but it still doesn’t fit neatly into rows and columns the way traditional database tables do.
1# Example: semi-structured JSON-like data from a trade API
2# Both the "meta" field (as the entries may vary) and the
3# log entry would be considered semi-structured/unstructured data.
4
5trade_event = {
6 "trade_id": 123456,
7 "ticker": "AAPL",
8 "price": 195.25,
9 "quantity": 100,
10 "side": "BUY",
11 "timestamp": "2025-01-02T14:35:10Z",
12 "meta": {
13 "exchange": "NASDAQ",
14 "order_type": "LIMIT",
15 "tags": ["retail", "mobile_app"],
16 },
17 "web_log": "158.62.92.53 - - [11/Oct/2025:14:32:15 -0400] \"GET /api/v1/prices?tickers=AAPL,MSFT&range=1y HTTP/1.1\" 200 5321 \"-\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)\""
18}
19
20trade_event
{'trade_id': 123456,
'ticker': 'AAPL',
'price': 195.25,
'quantity': 100,
'side': 'BUY',
'timestamp': '2025-01-02T14:35:10Z',
'meta': {'exchange': 'NASDAQ',
'order_type': 'LIMIT',
'tags': ['retail', 'mobile_app']},
'web_log': '158.62.92.53 - - [11/Oct/2025:14:32:15 -0400] "GET /api/v1/prices?tickers=AAPL,MSFT&range=1y HTTP/1.1" 200 5321 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)"'}
For the web_log field, although it appears as one long string, we can conceptually extract:
IP address
timestamp
HTTP verb
resource path
status code
response size
user agent (browswer)
Note that the resource path and user agent fields can vary dramatically in structure and length.
Semi-structured data often must be parsed before analysis.
Why semi-structured data matters:
Many real-world systems generate logs, not tables
High-frequency trading systems instrument events as logs
Fraud detection pipelines often consume JSON records
Data engineers spend large amounts of time transforming semi-structured into structured form
Unstructured Data#
Unstructured data has no fixed schema and cannot be easily decomposed into predefined fields without additional processing.
Examples in finance:
Earnings call transcripts
News articles
Analyst reports
Research PDFs
Customer service emails
Voice recordings
Social media text
Scanned documents or images
Characteristics:
meaning must be extracted using NLP, OCR, embeddings, or computer vision
storage structure does not imply analytical structure
may be large and noisy
often carries rich qualitative insight
1# Example: a piece of unstructured text from an earnings call transcript
2
3earnings_snippet = """
4Our Q4 revenue grew 12% year-over-year, driven primarily by cloud services.
5We see strong demand in our enterprise segment, particularly in North America and Europe.
6"""
7
8print(earnings_snippet.strip())
Our Q4 revenue grew 12% year-over-year, driven primarily by cloud services.
We see strong demand in our enterprise segment, particularly in North America and Europe.
Modern financial analytics increasingly uses:
natural language processing (NLP) on earnings reports
sentiment analysis on news and social media
document extraction from SEC filings
speech-to-text for call transcripts
These workflows require transforming unstructured data into structured or semi-structured representations.
Key Concept: Structure Determines What You Can Do
Structured → ready for analysis
Semi-structured → requires parsing
Unstructured → requires feature extraction (e.g., NLP, OCR)
Understanding data structure helps analysts plan:
cleaning steps
storage formats
query patterns
ETL processes
And it helps avoid mistakes—such as treating unstructured text as something that can be used directly in regression models.
Now that we understand what data represents and how it can be structured, we turn to the conceptual data structures used inside Python to store and work with data—lists, dictionaries, tables, and nested or relational models.
These are the building blocks for analysis, long before we introduce libraries like NumPy and Pandas.
Conceptual Data Structures#
Primitive types describe how individual values are represented — one number, one string, one boolean. But real financial datasets are collections of values: time series, records, tables, portfolios, order books, customer hierarchies. To analyze financial data effectively, we must understand how these collections are organized conceptually, independent of Python’s syntax.
Conceptual data structures help us answer:
Is this data a sequence? a table? a tree? a graph?
Is order important?
Are there keys linking records across tables?
Is the data flat or nested?
What operations are naturally supported?
Before selecting specific Python structures (lists, dicts, DataFrames), it helps to classify the kinds of collections we encounter in finance.
Sequences#
A sequence is an ordered collection of items where position matters.
Finance examples:
daily price series
ordered trade events
intraday bars
transaction logs
chronological event streams
Characteristics:
indexed by position or time
supports slicing (e.g., last 30 days)
duplicates allowed
useful for time-series analysis
Python representations:
list,tuple,range,numpy.ndarray, pandasSeries
Questions sequences answer:
How did the price evolve over time?
What happened in the last hour?
What is the rolling 20-day volatility?
Mappings#
Mappings associate keys with values.
Finance examples:
ticker → latest price
account_id → account record
date → holiday flag
symbol → metadata
Characteristics:
fast lookup
key uniqueness
order not inherently meaningful
Python representation: dict
Mappings answer:
What is the most recent price of AMZN?
Is this date a trading day?
Who owns this account?
Records (Structured Entities)#
A record represents one real-world entity using multiple fields.
Examples:
a single trade:
{symbol, qty, price, timestamp}a customer profile
a security master entry
a single holdings record
Records are typically represented as:
dictionaries
rows in a table
JSON objects
dataclasses
Records capture attributes, not collections.
Tables (Collections of Records)#
A table is a collection of records that all share the same schema.
Examples:
trade blotters
option chains
customer or account lists
daily factor exposures
position or holdings datasets
Tables support:
filtering, grouping, aggregating
sorting
computing statistics
merging with other tables
time series alignment
Typical representation:
pandas
DataFrameSQL tables
spreadsheets
Parquet files
Tables are the backbone of analytics and reporting in finance.
Relational Data (Linked Tables with Keys)#
In many systems, no single table contains all the information you need. Instead, data is distributed across multiple related tables, connected by keys that represent real-world relationships.
Finance is full of relational structures:
Customers → Accounts → Transactions
Issuers → Securities → Corporate Actions
Orders → Executions
Portfolios → Holdings → Prices
Funds → Share Classes → NAV History
Example:
customer_id |
name |
segment |
|---|---|---|
101 |
Alice Li |
Retail |
account_id |
customer_id |
type |
|---|---|---|
A-9001 |
101 |
Brokerage |
txn_id |
account_id |
symbol |
qty |
price |
|---|---|---|---|---|
T1001 |
A-9001 |
AAPL |
25 |
185.50 |
Here:
customer_idlinks Customers → Accountsaccount_idlinks Accounts → Transactions
Why relational modeling matters:
avoids duplication (store customer once)
reflects real-world relationships
supports efficient queries and joins
scales cleanly in large systems
forms the basis of SQL databases and modern data warehouses
In Python/pandas:
each table becomes a DataFrame
keys become columns
joins become
merge()operations
Understanding relational structures is essential for any real financial analytics pipeline.
Hierarchical / Nested Structures#
Some datasets are not flat. They contain nested records, lists, and sub-objects.
Examples:
order books with multiple price levels
multi-leg options
portfolios containing accounts containing holdings
regulatory filings
JSON returned by APIs
Example:
{
"order_id": 127583,
"symbol": "AAPL",
"legs": [
{"qty": 50, "side": "BUY"},
{"qty": 50, "side": "SELL", "conditional": true}
]
}
Challenges:
inconsistent depth
optional fields
schema may evolve over time
difficult to query directly
Typical workflow:
parse
flatten
normalize
load into relational tables or DataFrames
Nested structures capture complexity but often require transformation for analysis.
Conceptual vs. Python Implementations#
Once you know the conceptual structure, the Python representation becomes straightforward:
Conceptual Structure |
Natural Python Type |
Financial Use Case |
|---|---|---|
Sequence |
list, tuple, NumPy array, Series |
time series, trade streams |
Mapping |
dict |
lookup tables, metadata |
Record |
dict, dataclass, row in DataFrame |
trades, customers, securities |
Table |
DataFrame |
datasets, factor tables, ledgers |
Relational dataset |
multiple DataFrames + keys |
CRM, OMS, accounting |
Nested structure |
dict + lists (JSON) |
APIs, order books, filings |
Understanding conceptual structures first ensures that your data pipelines match the meaning of the data, not just the syntax of Python.
Big Picture: Why Data Structures Matter
Understanding conceptual data structures helps you:
decide how to represent data internally
parse and transform raw data correctly
understand what makes data “tidy” or analyzable
work effectively with APIs, logs, relational databases, and (later) Pandas
This knowledge forms the foundation for every data manipulation task in finance.
Now that we’ve covered how data is represented and organized, the next step is to understand where financial data comes from. Different sources provide data in different structures, with different quirks, delays, frequencies, and reliability characteristics.
This prepares us for the final part of the chapter: Financial Data Sources.
Financial Data Sources#
Financial systems generate and consume data from a wide variety of sources. Each source has its own structure, frequency, latency, reliability, and cleaning requirements. Understanding where data comes from is just as important as understanding how it is represented.
Financial data sources fall into several broad categories, each shaping how we load, transform, and interpret the data.
Market Data#
Market data describes the behavior of traded instruments on exchanges and electronic trading venues.
Examples:
Trades: executed transactions with price, size, timestamp
Quotes: bid/ask prices and sizes
Order books: depth levels, updates, cancellations, executions
Bars: OHLC data in fixed intervals (1-min, 5-min, daily)
Reference data: symbol identifiers, tick sizes, trading hours
Characteristics:
high volume
time-sensitive, latency-critical
often semi-structured (FIX messages, proprietary feeds)
requires normalization across venues
timezone and microsecond precision matter
Use cases:
algorithmic trading
risk modeling
portfolio analytics
regulatory reporting
market microstructure research
Fundamentals and Corporate Data#
Fundamental datasets describe companies, financial statements, corporate actions, and business attributes.
Examples:
balance sheets and income statements
earnings reports (raw text or structured feeds)
dividends and splits
corporate actions calendars
industry classifications (GICS, NAICS)
Characteristics:
slower cadence (quarterly, annual)
available from vendors (FactSet, Bloomberg, S&P)
mixture of structured (tables) and unstructured (filings, press releases)
Use cases:
equity valuation
factor modeling
risk attribution
fundamental screening
Economic and Macro Data#
Macro data aggregates economic indicators from governments, central banks, and statistical agencies.
Examples:
GDP, inflation, unemployment
interest rates and yield curves
central bank rate decisions
housing starts, PMI, retail sales
Characteristics:
typically time series
may have revisions (retroactive updates)
often sourced via APIs or CSV downloads
Use cases:
macroeconomic modeling
asset allocation
forecasting and scenario analysis
stress testing
Alternative Data#
Alternative data includes any dataset not traditionally used in financial analysis but providing economic signals.
Examples:
web traffic and search trends
credit card aggregates
satellite imagery
ESG metrics
supply-chain and shipping data
social media sentiment
job postings and hiring trends
Characteristics:
often unstructured or semi-structured
requires heavy cleaning
may raise ethical or regulatory considerations
vendor-specific formats
Use cases:
alpha research
anomaly detection
risk signals
nowcasting economic activity
Internal Operational Data#
Financial institutions generate extensive internal data describing accounts, positions, customers, and operational workflows.
Examples:
account records and customer profiles
trades and orders
positions and exposures
margin requirements
loan applications
CRM data
internal event logs
Characteristics:
highly structured and often relational
strict compliance and audit requirements
essential for reporting and regulatory filings
Use cases:
risk management
billing and fee calculations
customer analytics
compliance monitoring
internal dashboards
External APIs and Partner Data#
APIs from brokers, custodians, exchanges, and fintech partners provide essential feeds.
Examples:
brokerage APIs (executions, positions, balances)
custodian data (holdings, valuations)
payment processors (transactions, settlements)
identity and compliance services (KYC/AML)
clearing and settlement systems
Characteristics:
typically JSON or XML (semi-structured)
authentication and rate-limits must be handled
versioning and schema changes common
Use cases:
automated trading
reconciliation
operational dashboards
client reporting
Logs and Event Streams#
Modern financial systems are event-driven, emitting logs and telemetry at high frequency.
Examples:
order routing logs
risk system alerts
pricing engine events
distributed service logs
tracing and observability data
Characteristics:
semi-structured or unstructured
extremely high volume
require parsing and filtering
essential for debugging, monitoring, and compliance
Use cases:
post-trade analysis
incident response
latency measurement
fraud detection
Why Understanding Data Sources Matters#
Each source influences:
Dimension |
Meaning |
|---|---|
Format |
structured? JSON? flat files? logs? |
Latency |
real-time, end-of-day, quarterly |
Frequency |
tick-level, minute, daily, annual |
Reliability |
noisy? missing? subject to revisions? |
Cost |
vendor licensing, API limitations |
Cleaning requirements |
identifiers, timezones, normalization |
Storage strategies |
relational DB, time-series DB, object store |
Transformations |
parsing, merging, enriching, flattening |
A robust financial analytics workflow must identify:
the type of source
the structure of the data
the operations required to prepare it
the limitations and risks of each provider
Reliable models require reliable data; misunderstanding the source undermines everything built on top of it.
Review: What We Learned#
In this chapter, we explored the foundational ideas that shape how financial data is represented, interpreted, and organized. Before analyzing or modeling data, a data scientist must understand the form data takes and the meaning that form carries.
Key Takeaways#
Primitive data types define how individual values are stored
intfor discrete countsfloatfor approximate numerical valuesDecimalfor exact currency calculationsstrfor identifiers, labels, and textboolfor logical conditions and decision rules
You learned why the wrong type—such as using
floatfor money—can lead to real financial errors.Statistical meaning determines what operations are valid
Not all numbers are quantitative, and not all strings are categories. You learned the four measurement levels:
Nominal (e.g., tickers, sectors)
Ordinal (e.g., credit ratings, risk tiers)
Interval (e.g., dates, log-returns)
Ratio (e.g., prices, volumes, balances)
Correct analysis depends on recognizing what each variable represents, not just how it’s stored.
Dates and times introduce complexity in financial systems
Finance is time-driven, and timestamps raise challenges involving:
time zones
irregular tick-level data
frequency mismatches (daily prices vs. quarterly fundamentals)
differences between naive and aware datetime objects
Understanding these ideas prepares you for time-series analysis in later chapters.
Data may be structured, semi-structured, or unstructured
The core distinctions:
Structured → tables, schemas, rows/columns
Semi-structured → JSON, logs, event messages
Unstructured → text, audio, PDFs, images
Most real-world data workflows involve transforming semi-structured or unstructured data into structured representations suitable for analysis.
Conceptual data structures determine how we organize information
You saw how to represent financial data conceptually using:
lists (ordered sequences)
dictionaries (records)
tables (collections of records)
nested structures (hierarchical relationships)
relational structures (linking tables via keys)
These structures are the conceptual foundation for everything Pandas will automate later.
Financial data sources are diverse and domain-specific
The major categories:
market data
fundamentals
transactional data
alternative data
logs and event streams
Each source differs in structure, frequency, reliability, and use case—shaping how we clean, join, and analyze data.
Why This Chapter Matters#
Everything that follows—NumPy, Pandas, visualization, EDA, machine learning—depends on these foundational ideas. Data science is not just about running algorithms; it begins with correctly understanding the data itself.
This chapter gave you the conceptual “mental model” needed to recognize how real-world financial data is structured, stored, typed, and organized.
From Concepts to Computation with NumPy#
Now that you understand the forms and meanings of data, the next step is learning how to compute efficiently with that data.
NumPy provides:
fast numerical arrays,
vectorized operations,
tools for working with homogeneous data,
and the computational foundation for Pandas, SciPy, scikit-learn, and most of the Python data ecosystem.
Where this chapter focused on representation, the next chapter focuses on computation: performing calculations, generating new values, and working with numerical data at scale.
Understanding data types and structures makes NumPy much easier to learn—now you are ready to use these concepts in practice.
Exercises#
Identify Types and Meanings#
Consider the following dictionary representing a loan application:
record = {
"applicant_id": "A1023",
"fico_score": 688,
"loan_amount": "25000",
"interest_rate": 0.074,
"risk_tier": "B",
"application_date": "2024-02-12",
"approved": False
}
Identify the Python primitive type of each field.
Identify the measurement level (nominal, ordinal, interval, ratio).
Identify which fields should be converted to different types for analysis — and explain why.
Normalize Categorical Text#
Financial datasets often contain inconsistent text labels. Normalize the following list so that all values refer to the same city:
cities = ["St Louis", "st. louis ", "St. Louis", "ST LOUIS", "stl"]
Requirements:
remove punctuation
trim whitespace
convert to a single, consistent representation
Then answer:
Should this field be treated as nominal or ordinal?
In what cases might inconsistent categories break an analysis?
Parse a Log Line (Semi-Structured Data)#
Given the following web server log entry from an online trading platform:
log = '10.0.0.5 - - [12/Dec/2024:10:15:32 -0500] "POST /order/submit HTTP/1.1" 200 812'
Using only Python string methods or slicing (no regex):
Extract:
IP address
timestamp
HTTP method
endpoint (path)
status code
response size
Classify the data structure (structured, semi-structured, unstructured).
Explain why this form of data is challenging for downstream analytics.
Compute Time Differences#
You are given two trade execution timestamps:
from datetime import datetime
t1 = datetime(2024, 5, 1, 9, 30, 15)
t2 = datetime(2024, 5, 1, 9, 30, 18, 500000)
Compute the time difference using
timedelta.Convert that difference into seconds and milliseconds.
Explain why naive vs. aware timestamps might produce incorrect comparisons in a global trading system.
Build a Table from Raw Strings#
You receive a data feed where each line is "ACCOUNT,BALANCE":
lines = ["A1,100", "A2,250", "A3,175"]
Write code to convert this into a list of dictionaries like:
[
{"account": "A1", "balance": 100},
{"account": "A2", "balance": 250},
{"account": "A3", "balance": 175},
]
Then answer:
What conceptual data structure does this represent?
Which field(s) are ratio, nominal, or interval?
Why is this structure easier to analyze than a list of strings?
Nested Data Interpretation#
Consider the nested data structure:
portfolio = {
"owner": "Jane Doe",
"positions": [
{"ticker": "AAPL", "shares": 50, "avg_price": 172.4},
{"ticker": "MSFT", "shares": 20, "avg_price": 315.2},
{"ticker": "TSLA", "shares": 10, "avg_price": 198.0}
],
"opened": "2022-10-15"
}
Identify all primitive data types in this structure.
Identify all conceptual structures (list, dict, nested).
Explain why nested structures often need to be “flattened” before analysis.
Describe (in words) how you would convert this into a structured table for Pandas.
Categorize Data Sources#
For each of the following examples, identify whether the data source is market, fundamental, transactional, alternative, or log/event AND whether it is structured / semi-structured / unstructured:
JSON response from
/v1/tradesAPIQuarterly balance sheet
Credit card transactions from last month
Satellite image of parking lots
Earnings call transcript
Web server authentication log
Minute-level OHLC price bars
Then answer:
Which of these require the most cleaning?
Which require feature extraction (NLP, image processing)?
Which can be modeled immediately once loaded?
Spot the Modeling Mistake#
For each scenario below, identify the measurement level mistake and describe a correct alternative:
Averaging ZIP codes to find “typical customer region”
Computing percentage change of credit ratings
Sorting tickers alphabetically and interpreting the order as meaningful
Adding two dates together
Performing regression on unprocessed earnings call text
Explain why each mistake violates measurement-level rules.
Join Two Conceptual Tables (by hand)#
You are given:
Customers
customers = [
{"id": 1, "name": "Jane"},
{"id": 2, "name": "Sam"}
]
Accounts
accounts = [
{"id": 10, "customer_id": 1, "balance": 1200},
{"id": 11, "customer_id": 1, "balance": 5500},
{"id": 12, "customer_id": 2, "balance": 700}
]
Without using Pandas:
Create a Python structure that associates each customer with their list of accounts.
Identify the relationship type (one-to-many, many-to-one, many-to-many).
Explain why relational thinking is essential before learning SQL or Pandas.
Classify Timestamps by Frequency#
Given timestamps:
ts = [
"2024-05-01 09:30:01",
"2024-05-01 09:30:01.500000",
"2024-05-01 09:30:02",
"2024-05-01 09:31:15",
"2024-05-02 09:30:01"
]
Explain why this is not a regular time series.
Describe at least two frequency conversions you might perform (e.g., minute bars, daily bars).
Discuss why resampling and alignment are essential in financial time-series analysis.