Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Quantitative Data Storage

Python Quantitative Data Storage

Strategy research reuses the same batch of data repeatedly; downloading fresh from the source every time is slow and unstable - rate limits, network drops, and API changes all interrupt the work.

Persisting data locally is standard practice in quant engineering.

This article benchmarks the three mainstream options - CSV, SQLite, Parquet - and gives selection advice.


Storage option comparison

The three options represent three typical approaches:

Solution form Advantage Limitation Suitable scenarios
CSV Plain-text table Any tool can open it, zero dependencies Large size, slow read/write, no types Small data, needs manual viewing
SQLite Single-file database Supports SQL queries, conditional filtering, transactions No concurrent writes Structured market-data library, query on demand
Parquet Columnar binary High compression ratio, fast column-pruned reads Cannot be viewed directly by humans Large-volume historical data, batch research

Common production databases like MySQL and ClickHouse follow the same line of thinking as SQLite/Parquet; the latter two are enough for personal research.


CSV: the most universal exchange format

pandas needs only two functions to read/write CSV:

Example

import

yfinance

as

yf

import

pandas

as

pd

Download Moutai daily data (unadjusted, with an adjustment-factor column)

df

=

yf.

download

(

"600519.SS"

,

start

=

"2019-01-01"

,

end

=

"2024-12-31"

,

                 auto_adjust

=

False

,

progress

=

False

,

multi_level_index

=

False

)

Save: index=True writes the date index in as well

df.

to_csv

(

"maotai.csv"

)

Read: parse_dates restores the date column to a time index

back

=

pd.

read_csv

(

"maotai.csv"

,

index_col

=

"Date"

,

parse_dates

=

True

)

print

(

back.

tail

(

2

)

.

round

(

2

)

.

to_string

(

)

)

Common pitfall: when reading CSV you must specify index_col and parse_dates, otherwise the date becomes a plain string column and time-series slicing and resampling all break. This is the most common failure point of the CSV approach.


SQLite: a queryable local database

SQLite is a relational database embedded in a single file; Python's standard library ships with the driver, no service installation needed.

pandas works with it via just two functions, to_sql and read_sql:

Example

import

sqlite3

Connect to the database file (auto-created if absent)

conn

=

sqlite3.

connect

(

"maotai.db"

)

Write: a DataFrame becomes a table

df.

to_sql

(

"maotai"

,

conn

,

if_exists

=

"replace"

)

Conditional query with SQL: take only 2024 data

back

=

pd.

read_sql

(

   

"SELECT * FROM maotai WHERE Date >= '2024-01-01'"

,

    conn

,

index_col

=

"Date"

,

parse_dates

=

{

"Date"

}

)

print

(

"Number of rows returned by the query:"

,

len

(

back

)

)

SQL aggregation: compute the monthly average close right in the database

q

=

pd.

read_sql

(

   

"SELECT strftime('%Y-%m', Date) AS month, "

   

"ROUND(AVG(Close), 2) AS avg_monthly_close "

   

"FROM maotai GROUP BY month ORDER BY month DESC LIMIT 3"

,

conn

)

print

(

q.

to_string

(

index

=

False

)

)

conn.

close

(

)

The output is shown below:



查询返回行数: 241

 月份   月均收盘

2024-12  1533.16

2024-11  1554.50

2024-10  1565.79

The value of SQL lies in "taking only what you need": query just a year, a few columns, or some aggregation, without loading the whole table into memory. Once data reaches hundreds of thousands of rows, this advantage becomes very obvious.


Parquet: columnar storage for research

Parquet is a columnar compressed storage format that organizes data by column; it's small and fast to read, the de facto standard format in data science.

Example

Write Parquet (requires pyarrow: pip install pyarrow)

df.

to_parquet

(

"maotai.parquet"

)

Read

back

=

pd.

read_parquet

(

"maotai.parquet"

)

print

(

back.

shape

)


Benchmark comparison of the three options

Talk is cheap - using Moutai 2019-2024 daily data of 1453 rows x 6 columns, we benchmark the size and speed of the three options (measured on this machine; absolute values vary by machine):

Solution Write time Read time File size
CSV 0.00 s 0.003 s 125 KB
SQLite 0.00 s 0.002 s (with date filtering) 152 KB
Parquet 1.57 s 1.29 s 71 KB

The conclusion may be counterintuitive: on small datasets all three are fast enough, and Parquet is actually the slowest - the columnar engine's initialization overhead isn't worth it on small files.

Parquet's two real advantages only show up once the data gets big:

First, size: this example is already 43% smaller than CSV, and the compression ratio is even higher on datasets with many symbols and long histories.

Second, column pruning: when reading only two columns, Parquet doesn't need to scan the whole table; the bigger the data, the more it saves.

Selection advice: for personal quant research, recommend SQLite as primary storage (queryable, incrementally updatable) + Parquet as the archival format for batch research; use CSV only for exchanging data with others. Once a single table exceeds tens of millions of rows, then consider professional time-series solutions like ClickHouse.


Incremental update approach

Data must stay fresh after being persisted. Rather than rewriting everything each time, incremental appending is more efficient; the core logic is three steps:

Step Operation
Query the latest date SELECT MAX(Date) FROM table_name
Download the gap Set the data source's start parameter to the day after the latest date
Append write df.to_sql(..., if_exists="append")

Wrap this flow into a scheduled task (e.g. crontab running after each daily close), and you get an auto-updating local market-data library - which is also the data foundation for later strategy research.