### Async Get Intraday K-lines (Full Service) Source: https://github.com/tickflow-org/tickflow/blob/main/README.md Shows how to asynchronously fetch intraday k-line data using the full `AsyncTickFlow` service with an API key. It also includes an example of concurrently fetching data for multiple symbols. ```python import asyncio from tickflow import AsyncTickFlow async def main(): async with AsyncTickFlow(api_key="your-api-key") as tf: df = await tf.klines.get("600000.SH", as_dataframe=True) print(df.tail()) # 并发获取多只股票(如需大量获取 K 线数据,请使用 tf.klines.batch) tasks = [ tf.klines.get(s, as_dataframe=True) for s in ["600000.SH", "000001.SZ"] ] results = await asyncio.gather(*tasks) asyncio.run(main()) ``` -------------------------------- ### Install TickFlow Python SDK Source: https://context7.com/tickflow-org/tickflow/llms.txt Install the TickFlow SDK using pip. The full version includes optional features like pandas, tqdm, and websockets. ```bash pip install "tickflow[all]" --upgrade ``` ```bash pip install tickflow ``` -------------------------------- ### Get Batch Historical K-lines for Multiple Symbols Source: https://context7.com/tickflow-org/tickflow/llms.txt Fetch K-line data for multiple symbols concurrently. The SDK automatically chunks large symbol lists (max 100 per chunk) and supports progress display and multi-threading. Examples show fetching daily K-lines for Shanghai stocks and weekly K-lines for a specific set of symbols. ```python from tickflow import TickFlow tf = TickFlow(api_key="your-api-key") # 获取沪市全部标的列表 sh_instruments = tf.exchanges.get_instruments("SH", instrument_type="stock") sh_symbols = [inst["symbol"] for inst in sh_instruments] # ~1700+ 只 # 批量拉取前复权日K,显示进度条,5 线程并发 dfs = tf.klines.batch( sh_symbols, period="1d", count=250, # 约一年交易日 adjust="forward", as_dataframe=True, show_progress=True, # 需安装 tqdm max_workers=5, ) print(f"成功获取 {len(dfs)} 只股票") print(dfs["600000.SH"].tail(3)) # 输出: # symbol name trade_date open high low close volume # 247 600000.SH 浦发银行 2025-05-28 7.98 8.03 7.95 8.01 48000000 # ... # 按时间范围批量拉取,返回原始 dict raw_batch = tf.klines.batch( ["000001.SZ", "600519.SH", "510300.SH"], period="1w", count=52, ) for symbol, data in raw_batch.items(): print(f"{symbol}: {len(data['timestamp'])} 根周K") ``` -------------------------------- ### Async Get 1-Day K-lines (Free Service) Source: https://github.com/tickflow-org/tickflow/blob/main/README.md Demonstrates asynchronous fetching of 1-day k-line data using `AsyncTickFlow.free()`. This is suitable for high-concurrency scenarios without requiring an API key. ```python import asyncio from tickflow import AsyncTickFlow async def main(): # 使用免费服务(无需 API key) async with AsyncTickFlow.free() as tf: df = await tf.klines.get("600000.SH", period="1d", as_dataframe=True) print(df.tail()) asyncio.run(main()) ``` -------------------------------- ### Get All US Instruments Source: https://context7.com/tickflow-org/tickflow/llms.txt Fetches all available instruments for the US market. Requires initialization of TickFlow. ```python us_all = tf.exchanges.get_instruments("US") print(f"美股: {len(us_all)} 只") ``` -------------------------------- ### Asynchronous Get K-lines (Free Service) Source: https://github.com/tickflow-org/tickflow/blob/main/README.md Fetches k-line data asynchronously using the free service, suitable for high concurrency scenarios. ```APIDOC ## Asynchronous Get K-lines (Free Service) ### Description Fetches k-line data asynchronously using the free service, suitable for high concurrency scenarios. No API key is required for the free service. ### Method `async with AsyncTickFlow.free() as tf: df = await tf.klines.get(symbol, period=None, as_dataframe=True)` ### Parameters #### Path Parameters - **symbol** (str) - Required - The trading symbol (e.g., "600000.SH"). - **period** (str) - Optional - The k-line period (e.g., "1d"). If not specified, defaults to daily k-lines. - **as_dataframe** (bool) - Optional - If True, returns data as a pandas DataFrame. ### Request Example ```python import asyncio from tickflow import AsyncTickFlow async def main(): async with AsyncTickFlow.free() as tf: df = await tf.klines.get("600000.SH", period="1d", as_dataframe=True) print(df.tail()) asyncio.run(main()) ``` ### Response - Returns a pandas DataFrame containing k-line data. ``` -------------------------------- ### Get Today's 1-Minute K-lines Source: https://github.com/tickflow-org/tickflow/blob/main/README.md Fetches intraday 1-minute k-line data for a given symbol. Use this to get the latest minute-by-minute price data for a stock. ```python df = tf.klines.intraday("600000.SH", as_dataframe=True) print(f"今日已有 {len(df)} 根分钟 K 线") print(df.tail()) ``` -------------------------------- ### Get All US Instruments Source: https://context7.com/tickflow-org/tickflow/llms.txt Retrieves a list of all available instruments for the US market. ```APIDOC ## Get All US Instruments ### Description Retrieves a list of all available instruments for the US market. ### Method `tf.exchanges.get_instruments(exchange: str)` ### Parameters #### Path Parameters - **exchange** (str) - Required - The exchange to retrieve instruments from (e.g., "US"). ### Response Example ```json [ { "symbol": "AAPL", "name": "Apple Inc.", "exchange": "US" } ] ``` ``` -------------------------------- ### Get Real-time Quotes by Universe Source: https://github.com/tickflow-org/tickflow/blob/main/README.md Retrieves real-time market quotes for an entire universe of stocks, such as all A-shares or ETFs. Use this to get quotes for a predefined market segment. ```python # 获取全部 A 股行情 quotes_a = tf.quotes.get(universes=["CN_Equity_A"], as_dataframe=True) print(quotes_a) # 获取全部沪深 ETF 行情 quotes_etf = tf.quotes.get(universes=["CN_ETF"], as_dataframe=True) print(quotes_etf) ``` -------------------------------- ### Get Real-time Quotes by Symbol Source: https://github.com/tickflow-org/tickflow/blob/main/README.md Retrieves real-time market quotes for specified symbols. Use this to get the latest trading information for one or more stocks. ```python quotes = tf.quotes.get(symbols=["600000.SH", "000001.SZ"], as_dataframe=True) print(quotes) ``` -------------------------------- ### Get Specific Universe Details Source: https://context7.com/tickflow-org/tickflow/llms.txt Retrieves details for a specific instrument universe, such as A-shares. This includes a list of all symbols within that universe. ```python # 获取 A 股全量标的列表 cn_a = tf.universes.get("CN_Equity_A") symbols = cn_a["symbols"] print(f"A 股共 {len(symbols)} 只,前5只: {symbols[:5]}") ``` -------------------------------- ### Batch Get Multiple Universes Source: https://context7.com/tickflow-org/tickflow/llms.txt Fetches details for multiple instrument universes in a single request. Useful for retrieving information about several markets or asset types simultaneously. ```python # 批量获取多个标的池 details = tf.universes.batch(["CN_Equity_A", "CN_ETF", "US_Equity"]) for uid, detail in details.items(): print(f"{uid}: {detail['symbol_count']} 只") ``` -------------------------------- ### Asynchronous Get K-lines (Full Service) Source: https://github.com/tickflow-org/tickflow/blob/main/README.md Fetches k-line data asynchronously using the full service with an API key, supporting concurrent requests. ```APIDOC ## Asynchronous Get K-lines (Full Service) ### Description Fetches k-line data asynchronously using the full service with an API key. Supports concurrent requests for multiple symbols. ### Method `async with AsyncTickFlow(api_key="your-api-key") as tf: df = await tf.klines.get(symbol, as_dataframe=True) # For multiple symbols, use asyncio.gather with tf.klines.get or tf.klines.batch` ### Parameters #### Path Parameters - **api_key** (str) - Required - Your TickFlow API key. - **symbol** (str) - Required - The trading symbol (e.g., "600000.SH"). - **as_dataframe** (bool) - Optional - If True, returns data as a pandas DataFrame. ### Request Example ```python import asyncio from tickflow import AsyncTickFlow async def main(): async with AsyncTickFlow(api_key="your-api-key") as tf: # Get daily k-lines for a single symbol df = await tf.klines.get("600000.SH", as_dataframe=True) print(df.tail()) # Concurrently get k-lines for multiple symbols tasks = [ tf.klines.get(s, as_dataframe=True) for s in ["600000.SH", "000001.SZ"] ] results = await asyncio.gather(*tasks) asyncio.run(main()) ``` ### Response - Returns a pandas DataFrame containing k-line data for each requested symbol. ``` -------------------------------- ### Initialize Asynchronous TickFlow Client Source: https://context7.com/tickflow-org/tickflow/llms.txt Initialize the asynchronous TickFlow client for high-concurrency scenarios. All data methods require `await`. The example demonstrates serial and concurrent data fetching using `asyncio.gather`. ```python import asyncio from tickflow import AsyncTickFlow async def main(): async with AsyncTickFlow(api_key="your-api-key") as tf: # 串行获取 df = await tf.klines.get("600519.SH", period="1d", count=200, as_dataframe=True) print(df.tail(3)) # 并发获取多只股票(推荐大量标的使用 batch 方法) tasks = [ tf.klines.get(s, period="1d", count=100, as_dataframe=True) for s in ["600000.SH", "000001.SZ", "600519.SH", "AAPL.US"] ] results = await asyncio.gather(*tasks) for df_item in results: print(df_item.iloc[-1][["symbol", "close"]]) asyncio.run(main()) ``` -------------------------------- ### Get Single Symbol Historical K-lines Source: https://context7.com/tickflow-org/tickflow/llms.txt Retrieve historical OHLCV K-line data for a single symbol. Supports various periods and adjustment types, with a maximum limit of 10,000 bars. Examples show forward, backward, and no adjustment, as well as time range queries and 60-minute periods. ```python from tickflow import TickFlow tf = TickFlow(api_key="your-api-key") # 前复权日K(默认) df_qfq = tf.klines.get("600519.SH", period="1d", count=500, as_dataframe=True) print(df_qfq[["trade_date", "open", "high", "low", "close", "volume"]].tail(5)) # 后复权日K df_hfq = tf.klines.get("600519.SH", adjust="backward", as_dataframe=True) # 不复权原始数据 df_raw = tf.klines.get("600519.SH", adjust="none", as_dataframe=True) # 按时间范围查询(毫秒时间戳) import time end_ts = int(time.time() * 1000) start_ts = end_ts - 30 * 24 * 3600 * 1000 # 最近 30 天 df_range = tf.klines.get("600519.SH", start_time=start_ts, end_time=end_ts, as_dataframe=True) # 60分钟K线(需完整服务) df_60m = tf.klines.get("000001.SZ", period="60m", count=100, as_dataframe=True) # 返回原始 dict 格式 raw = tf.klines.get("AAPL.US", period="1d", count=10) print(f"最新收盘价: {raw['close'][-1]} 时间戳: {raw['timestamp'][-1]}") # 输出: 最新收盘价: 189.84 时间戳: 1748476800000 ``` -------------------------------- ### Batch Get Intraday K-lines Source: https://github.com/tickflow-org/tickflow/blob/main/README.md Fetches intraday k-line data for multiple symbols in a batch. ```APIDOC ## Batch Get Intraday K-lines ### Description Fetches intraday k-line data for multiple symbols in a batch. ### Method `tf.klines.intraday_batch(symbols, as_dataframe=True, show_progress=False, ...)` ### Parameters #### Path Parameters - **symbols** (list[str]) - Required - A list of trading symbols (e.g., ["600000.SH", "000001.SZ"]) - **as_dataframe** (bool) - Optional - If True, returns data as a pandas DataFrame. - **show_progress** (bool) - Optional - If True, displays a progress bar. ### Request Example ```python symbols = ["600000.SH", "000001.SZ", "600519.SH"] dfs = tf.klines.intraday_batch(symbols, as_dataframe=True, show_progress=True) ``` ### Response - Returns a dictionary where keys are symbols and values are their respective k-line DataFrames if `as_dataframe` is True. ``` -------------------------------- ### Get Real-time Quotes Source: https://github.com/tickflow-org/tickflow/blob/main/README.md Fetches real-time market quotes for specified symbols or universes. ```APIDOC ## Get Real-time Quotes ### Description Fetches real-time market quotes for specified symbols or universes. ### Method `tf.quotes.get(symbols=None, universes=None, as_dataframe=True)` ### Parameters #### Path Parameters - **symbols** (list[str]) - Optional - A list of trading symbols (e.g., ["600000.SH"]). - **universes** (list[str]) - Optional - A list of predefined symbol universes (e.g., ["CN_Equity_A"]). - **as_dataframe** (bool) - Optional - If True, returns data as a pandas DataFrame. ### Request Example ```python # Get quotes by symbol quotes_by_symbol = tf.quotes.get(symbols=["600000.SH", "000001.SZ"], as_dataframe=True) # Get quotes by universe (all A shares) quotes_a_shares = tf.quotes.get(universes=["CN_Equity_A"], as_dataframe=True) # Get quotes by universe (all SSE ETF) quotes_etf = tf.quotes.get(universes=["CN_ETF"], as_dataframe=True) ``` ### Response - Returns a pandas DataFrame containing real-time quote data. ``` -------------------------------- ### Get Today's 5-Minute K-lines Source: https://github.com/tickflow-org/tickflow/blob/main/README.md Fetches intraday 5-minute k-line data for a symbol by setting the 'period' parameter. Use this for aggregated minute data. ```python df_5m = tf.klines.intraday("600000.SH", period="5m", as_dataframe=True) print(df_5m.tail()) ``` -------------------------------- ### Batch Get Today's Intraday K-lines Source: https://github.com/tickflow-org/tickflow/blob/main/README.md Fetches intraday k-line data for multiple symbols simultaneously using `intraday_batch`. This is efficient for retrieving data for several stocks at once. Requires a list of symbols and returns a dictionary of dataframes. ```python from tickflow import TickFlow tf = TickFlow(api_key="your-api-key") symbols = ["600000.SH", "000001.SZ", "600519.SH"] dfs = tf.klines.intraday_batch(symbols, as_dataframe=True, show_progress=True) print(f"成功获取 {len(dfs)} 只股票的日内数据") print(dfs["600000.SH"].tail()) ``` -------------------------------- ### Get Intraday K-lines Source: https://github.com/tickflow-org/tickflow/blob/main/README.md Fetches intraday k-line data for a given symbol. Supports specifying the period (e.g., '1m', '5m') and the number of k-lines to retrieve. ```APIDOC ## Get Intraday K-lines ### Description Fetches intraday k-line data for a given symbol. Supports specifying the period (e.g., '1m', '5m') and the number of k-lines to retrieve. ### Method `tf.klines.intraday(symbol, as_dataframe=True, count=None, period='1m')` ### Parameters #### Path Parameters - **symbol** (str) - Required - The trading symbol (e.g., "600000.SH"). - **as_dataframe** (bool) - Optional - If True, returns data as a pandas DataFrame. - **count** (int) - Optional - The number of k-lines to retrieve. - **period** (str) - Optional - The k-line period (default is '1m'). ### Request Example ```python # Get today's 1-minute k-lines df = tf.klines.intraday("600000.SH", as_dataframe=True) # Get the latest 1 k-line of today df_last = tf.klines.intraday("600000.SH", as_dataframe=True, count=1) # Get today's 5-minute k-lines df_5m = tf.klines.intraday("600000.SH", period="5m", as_dataframe=True) ``` ### Response - Returns a pandas DataFrame if `as_dataframe` is True, otherwise a list of k-line data. ``` -------------------------------- ### Get Latest 1-Minute K-line Source: https://github.com/tickflow-org/tickflow/blob/main/README.md Fetches only the latest 1-minute k-line for a symbol by specifying the 'count' parameter. Useful when only the most recent data point is needed. ```python df_last = tf.klines.intraday("600000.SH", as_dataframe=True, count=1) print(df_last.tail()) ``` -------------------------------- ### Fetch Income Statements within a Date Range Source: https://context7.com/tickflow-org/tickflow/llms.txt Retrieves income statement data for specified stock symbols within a given date range. Requires start and end dates. ```python # 按时间范围过滤 income_range = tf.financials.income( symbols, start_date="2020-01-01", end_date="2024-12-31", as_dataframe=True, ) ``` -------------------------------- ### TickFlow Client Initialization Source: https://context7.com/tickflow-org/tickflow/llms.txt Demonstrates how to initialize the synchronous TickFlow client using an API key, environment variables, or a context manager. Also shows how to catch common authentication and rate limit errors. ```APIDOC ## TickFlow Client Initialization ### `TickFlow(api_key, ...)` — Synchronous Client Synchronous client, suitable for scripts, Jupyter Notebooks, and single-threaded applications. Supports authentication information provided via direct parameters or the `TICKFLOW_API_KEY` environment variable. ```python import os from tickflow import TickFlow, AuthenticationError, RateLimitError # Method 1: Pass API Key directly tf = TickFlow(api_key="your-api-key") # Method 2: Read from environment variable TICKFLOW_API_KEY os.environ["TICKFLOW_API_KEY"] = "your-api-key" tf = TickFlow() # Method 3: Use context manager (automatically closes connections) with TickFlow(api_key="your-api-key", timeout=60.0, max_retries=5) as tf: quotes = tf.quotes.get(symbols=["600000.SH"]) print(quotes[0]["last_price"]) # Catch common exceptions try: tf = TickFlow(api_key="invalid-key") tf.quotes.get(symbols=["600000.SH"]) except AuthenticationError as e: print(f"Authentication failed: {e.message} HTTP {e.status_code}") except RateLimitError as e: print(f"Rate limit triggered: {e.message}") ``` ### `TickFlow.free()` — Free Service Client No registration or API Key required, provides historical daily K-line data and instrument information queries, with an IP rate limit of 60 times/minute by default. ```python from tickflow import TickFlow # Create a free service client (no API Key needed) tf = TickFlow.free() # Query historical daily K-line data, returns a DataFrame df = tf.klines.get("600000.SH", period="1d", count=100, as_dataframe=True) print(df.tail()) # Example output: # symbol name timestamp trade_date open high low close volume amount # 99 600000.SH 浦发银行 1748... 2025-05-30 7.98 8.02 7.96 8.00 52000000 4.1e+08 # Query instrument information instruments = tf.instruments.batch(["600000.SH", "000001.SZ", "510300.SH"]) for inst in instruments: print(f"{inst['symbol']}: {inst['name']} ({inst['instrument_type']})") ``` ### `AsyncTickFlow(api_key, ...)` — Asynchronous Client Asynchronous client, suitable for high-concurrency scenarios, all data methods require `await`. ```python import asyncio from tickflow import AsyncTickFlow async def main(): async with AsyncTickFlow(api_key="your-api-key") as tf: # Serial fetching df = await tf.klines.get("600519.SH", period="1d", count=200, as_dataframe=True) print(df.tail(3)) # Concurrent fetching of multiple stocks (recommended to use batch method for large symbol lists) tasks = [ tf.klines.get(s, period="1d", count=100, as_dataframe=True) for s in ["600000.SH", "000001.SZ", "600519.SH", "AAPL.US"] ] results = await asyncio.gather(*tasks) for df_item in results: print(df_item.iloc[-1][["symbol", "close"]]) asyncio.run(main()) ``` ``` -------------------------------- ### Initialize Free TickFlow Client Source: https://context7.com/tickflow-org/tickflow/llms.txt Create a client for the free TickFlow service, which provides historical daily K-lines and instrument information without requiring an API key. Note the IP rate limit of 60 requests per minute. ```python from tickflow import TickFlow # 创建免费服务客户端(无需 API Key) tf = TickFlow.free() # 查询历史日K线,返回 DataFrame df = tf.klines.get("600000.SH", period="1d", count=100, as_dataframe=True) print(df.tail()) # 输出示例: # symbol name timestamp trade_date open high low close volume amount # 99 600000.SH 浦发银行 1748... 2025-05-30 7.98 8.02 7.96 8.00 52000000 4.1e+08 # 查询标的信息 instruments = tf.instruments.batch(["600000.SH", "000001.SZ", "510300.SH"]) for inst in instruments: print(f"{inst['symbol']}: {inst['name']} ({inst['instrument_type']})") ``` -------------------------------- ### Real-time Market Data Stream (Asynchronous) Source: https://context7.com/tickflow-org/tickflow/llms.txt Connects to a real-time market data stream asynchronously using WebSockets. Supports dynamic subscription/unsubscription and non-blocking operation. Requires an asyncio event loop. ```python # 异步版本:非阻塞后台运行 import asyncio from tickflow import AsyncTickFlow async def main(): async with AsyncTickFlow(api_key="your-api-key") as tf: stream = tf.stream @stream.on_quotes def handle(quotes): for q in quotes: print(f"{q['symbol']}: {q['last_price']}") stream_task = asyncio.create_task(stream.connect()) # 先订阅行情 await stream.subscribe("quotes", ["600000.SH", "000001.SZ"]) await asyncio.sleep(10) # 动态追加订阅盘口 await stream.subscribe("depth", ["600000.SH"]) await asyncio.sleep(10) # 取消订阅 await stream.unsubscribe("quotes", ["000001.SZ"]) await stream.close() stream_task.cancel() asyncio.run(main()) ``` -------------------------------- ### Initialize Synchronous TickFlow Client Source: https://context7.com/tickflow-org/tickflow/llms.txt Initialize the synchronous TickFlow client. API key can be provided directly or via the TICKFLOW_API_KEY environment variable. Supports context manager for automatic connection closing and exception handling for common errors. ```python import os from tickflow import TickFlow, AuthenticationError, RateLimitError # 方式一:直接传入 API Key tf = TickFlow(api_key="your-api-key") # 方式二:读取环境变量 TICKFLOW_API_KEY os.environ["TICKFLOW_API_KEY"] = "your-api-key" tf = TickFlow() # 方式三:使用上下文管理器(自动关闭连接) with TickFlow(api_key="your-api-key", timeout=60.0, max_retries=5) as tf: quotes = tf.quotes.get(symbols=["600000.SH"]) print(quotes[0]["last_price"]) # 捕获常见异常 try: tf = TickFlow(api_key="invalid-key") tf.quotes.get(symbols=["600000.SH"]) except AuthenticationError as e: print(f"认证失败: {e.message} HTTP {e.status_code}") except RateLimitError as e: print(f"触发限速: {e.message}") ``` -------------------------------- ### Real-time Market Data Stream (Synchronous) Source: https://context7.com/tickflow-org/tickflow/llms.txt Connects to a real-time market data stream using WebSockets to receive quotes and order book (depth) updates. Supports automatic reconnection and subscription recovery. Uses decorator-based callbacks. ```python from tickflow import TickFlow tf = TickFlow(api_key="your-api-key") stream = tf.stream # 注册行情回调(装饰器方式) @stream.on_quotes def handle_quotes(quotes): for q in quotes: chg = (q["last_price"] - q["prev_close"]) / q["prev_close"] * 100 print(f"[行情] {q['symbol']}: {q['last_price']:.2f} {chg:+.2f}%") # 注册盘口回调 @stream.on_depth def handle_depth(depths): for d in depths: print(f"[盘口] {d['symbol']} 买一={d['bid_prices'][0]} 卖一={d['ask_prices'][0]}") # 注册错误回调 @stream.on_error def handle_error(msg): print(f"[错误] {msg}") # 订阅行情和盘口频道 stream.subscribe("quotes", ["600000.SH", "000001.SZ", "600519.SH", "AAPL.US"]) stream.subscribe("depth", ["600000.SH", "000001.SZ"]) # 阻塞运行(Ctrl+C 退出) stream.connect(block=True) ``` -------------------------------- ### Fetch Large Batch Financial Metrics with Progress Source: https://context7.com/tickflow-org/tickflow/llms.txt Fetches financial metrics for a large number of symbols (e.g., CSI 300 constituents) with a progress bar and configurable concurrency. Useful for bulk data retrieval. ```python # 大批量财务数据(带进度条) hs300_symbols = [i["symbol"] for i in tf.universes.get("CN_Equity_A")["symbols"][:300]] big_metrics = tf.financials.metrics( hs300_symbols, latest=True, as_dataframe=True, show_progress=True, max_workers=10, ) print(f"获取 {len(big_metrics)} 条指标记录") ``` -------------------------------- ### Fetch Latest Financial Metrics Source: https://context7.com/tickflow-org/tickflow/llms.txt Retrieves the latest core financial metrics, such as ROE, PE, and PB ratios, for specified stock symbols. Also includes dividend yield. ```python # 核心指标(ROE、PE、PB 等) metrics_df = tf.financials.metrics(symbols, latest=True, as_dataframe=True) print(metrics_df[["symbol", "roe", "pe", "pb", "dividend_yield"]]) ``` -------------------------------- ### List Available Universes Source: https://context7.com/tickflow-org/tickflow/llms.txt Lists all predefined instrument universes available in TickFlow. Each universe contains a collection of symbols for specific markets or asset types. ```python from tickflow import TickFlow tf = TickFlow(api_key="your-api-key") # 列出所有可用标的池 universes = tf.universes.list() for u in universes: print(f"{u['id']:20s} {u['name']:15s} {u['symbol_count']} 只") ``` -------------------------------- ### Fetch Real-time Quotes for an ETF Universe Source: https://context7.com/tickflow-org/tickflow/llms.txt Combines universe data with the quotes API to fetch real-time market data for all ETFs in a specified universe. Displays the top 5 ETFs by trading volume. ```python # 结合行情接口:获取全部 ETF 实时行情 etf_universe = tf.universes.get("CN_ETF") df_etf = tf.quotes.get(universes=["CN_ETF"], as_dataframe=True) print(df_etf.sort_values("amount", ascending=False).head(5)[["symbol", "last_price", "amount"]]) ``` -------------------------------- ### K-line Data Retrieval (`tf.klines`) Source: https://context7.com/tickflow-org/tickflow/llms.txt Covers methods for fetching historical K-line data, including single symbol retrieval with various periods and adjustments, and batch retrieval for multiple symbols. ```APIDOC ## K-line Data — `tf.klines` ### `klines.get(symbol, ...)` — Single Symbol Historical K-lines Retrieves historical OHLCV K-line data for a single symbol, supporting various periods and adjustment types, returning up to 10,000 bars. ```python from tickflow import TickFlow tf = TickFlow(api_key="your-api-key") # Forward-adjusted daily K-lines (default) df_qfq = tf.klines.get("600519.SH", period="1d", count=500, as_dataframe=True) print(df_qfq[["trade_date", "open", "high", "low", "close", "volume"]].tail(5)) # Backward-adjusted daily K-lines df_hfq = tf.klines.get("600519.SH", adjust="backward", as_dataframe=True) # Unadjusted raw data df_raw = tf.klines.get("600519.SH", adjust="none", as_dataframe=True) # Query by time range (milliseconds timestamp) import time end_ts = int(time.time() * 1000) start_ts = end_ts - 30 * 24 * 3600 * 1000 # Last 30 days df_range = tf.klines.get("600519.SH", start_time=start_ts, end_time=end_ts, as_dataframe=True) # 60-minute K-lines (requires full service) df_60m = tf.klines.get("000001.SZ", period="60m", count=100, as_dataframe=True) # Return raw dict format raw = tf.klines.get("AAPL.US", period="1d", count=10) print(f"Latest closing price: {raw['close'][-1]} Timestamp: {raw['timestamp'][-1]}") # Output: Latest closing price: 189.84 Timestamp: 1748476800000 ``` --- ### `klines.batch(symbols, ...)` — Batch Historical K-lines for Multiple Symbols Concurrently fetches K-line data for multiple symbols in batches, automatically chunking large lists (up to 100 symbols per chunk), suitable for full market data retrieval. ```python from tickflow import TickFlow tf = TickFlow(api_key="your-api-key") # Get the list of all Shanghai Stock Exchange instruments sh_instruments = tf.exchanges.get_instruments("SH", instrument_type="stock") sh_symbols = [inst["symbol"] for inst in sh_instruments] # ~1700+ stocks # Batch fetch forward-adjusted daily K-lines, show progress, 5 threads concurrent dfs = tf.klines.batch( sh_symbols, period="1d", count=250, # Approx. one year of trading days adjust="forward", as_dataframe=True, show_progress=True, # Requires tqdm installation max_workers=5, ) print(f"Successfully fetched {len(dfs)} stocks") print(dfs["600000.SH"].tail(3)) # Output: # symbol name trade_date open high low close volume # 247 600000.SH 浦发银行 2025-05-28 7.98 8.03 7.95 8.01 48000000 # ... # Batch fetch by time range, returns raw dict raw_batch = tf.klines.batch( ["000001.SZ", "600519.SH", "510300.SH"], period="1w", count=52, ) for symbol, data in raw_batch.items(): print(f"{symbol}: {len(data['timestamp'])} weekly K-lines") ``` ``` -------------------------------- ### Fetch Share Capital Data Source: https://context7.com/tickflow-org/tickflow/llms.txt Retrieves historical share capital data for specified stock symbols, including total shares and free float shares over different periods. ```python # 股本数据 shares_df = tf.financials.shares(symbols, as_dataframe=True) print(shares_df[["symbol", "period_end", "total_shares", "float_shares"]]) ``` -------------------------------- ### Market Data Stream Source: https://context7.com/tickflow-org/tickflow/llms.txt Subscribe to real-time market data (quotes and order book) via WebSocket. ```APIDOC ## Market Data Stream ### `MarketStream` / `AsyncMarketStream` #### Description Provides a unified WebSocket interface for subscribing to real-time market data, including quotes and order book depth. Supports automatic reconnection and subscription recovery. #### Methods - **`on_quotes(callback)`**: Decorator to register a callback for quote updates. - **`on_depth(callback)`**: Decorator to register a callback for order book depth updates. - **`on_error(callback)`**: Decorator to register a callback for error messages. - **`subscribe(channel, symbols)`**: Subscribes to a specified channel (e.g., "quotes", "depth") for a list of symbols. - **`unsubscribe(channel, symbols)`**: Unsubscribes from a specified channel for a list of symbols. - **`connect(block=False)`**: Connects to the WebSocket server. If `block` is True, the connection will block until interrupted. - **`close()`**: Closes the WebSocket connection. #### Parameters - **channel** (str) - The data channel to subscribe to (e.g., "quotes", "depth"). - **symbols** (list[str]) - A list of symbols to subscribe to. - **block** (bool) - Whether to block the execution thread after connecting. ### Request Example (Synchronous) ```python from tickflow import TickFlow tf = TickFlow(api_key="your-api-key") stream = tf.stream @stream.on_quotes def handle_quotes(quotes): for q in quotes: print(f"[Quote] {q['symbol']}: {q['last_price']}") stream.subscribe("quotes", ["600000.SH"]) stream.connect(block=True) ``` ### Request Example (Asynchronous) ```python import asyncio from tickflow import AsyncTickFlow async def main(): async with AsyncTickFlow(api_key="your-api-key") as tf: stream = tf.stream @stream.on_quotes def handle(quotes): for q in quotes: print(f"[Quote] {q['symbol']}: {q['last_price']}") await stream.subscribe("quotes", ["600000.SH"]) await stream.connect() await asyncio.sleep(10) await stream.close() asyncio.run(main()) ``` ### Response Example (Quote) ```json { "symbol": "600000.SH", "last_price": 10.50, "prev_close": 10.40, "volume": 100000, "timestamp": 1678886400 } ``` ### Response Example (Depth) ```json { "symbol": "600000.SH", "bid_prices": [10.49, 10.48, 10.47], "bid_volumes": [500, 600, 700], "ask_prices": [10.50, 10.51, 10.52], "ask_volumes": [400, 300, 200], "timestamp": 1678886401 } ``` ``` -------------------------------- ### Fetch Latest Balance Sheet Source: https://context7.com/tickflow-org/tickflow/llms.txt Retrieves the latest balance sheet data for specified stock symbols. Includes key figures like total assets, total liabilities, and equity. ```python # 资产负债表 bs_df = tf.financials.balance_sheet(symbols, latest=True, as_dataframe=True) print(bs_df[["symbol", "total_assets", "total_liabilities", "equity"]]) ``` -------------------------------- ### Universe Operations Source: https://context7.com/tickflow-org/tickflow/llms.txt Operations for querying predefined instrument collections (universes). ```APIDOC ## Universe Operations ### `universes.list()` #### Description Lists all available predefined instrument collections (universes). ### `universes.get(id)` #### Description Retrieves a specific instrument collection by its ID. #### Parameters - **id** (str) - Required - The ID of the universe to retrieve (e.g., "CN_Equity_A"). ### `universes.batch(ids)` #### Description Retrieves multiple instrument collections by their IDs in a batch. #### Parameters - **ids** (list[str]) - Required - A list of universe IDs to retrieve. ### Request Example (list) ```python universes = tf.universes.list() ``` ### Request Example (get) ```python cn_a = tf.universes.get("CN_Equity_A") ``` ### Request Example (batch) ```python details = tf.universes.batch(["CN_Equity_A", "CN_ETF", "US_Equity"]) ``` ### Response Example (list item) ```json { "id": "CN_Equity_A", "name": "A股全市场", "symbol_count": 5000 } ``` ### Response Example (get/batch item) ```json { "id": "CN_Equity_A", "name": "A股全市场", "symbol_count": 5000, "symbols": ["000001.SZ", "000002.SZ", ...] } ``` ``` -------------------------------- ### Financial Statements Source: https://context7.com/tickflow-org/tickflow/llms.txt Retrieve historical financial statement data for listed companies. ```APIDOC ## Financial Statements ### `financials.income()` #### Description Retrieves historical income statement data. #### Parameters - **symbols** (list[str]) - Required - List of stock symbols. - **latest** (bool) - Optional - If True, returns only the latest period. - **start_date** (str) - Optional - Start date for filtering (YYYY-MM-DD). - **end_date** (str) - Optional - End date for filtering (YYYY-MM-DD). - **as_dataframe** (bool) - Optional - If True, returns data as a pandas DataFrame. ### `financials.balance_sheet()` #### Description Retrieves historical balance sheet data. #### Parameters - **symbols** (list[str]) - Required - List of stock symbols. - **latest** (bool) - Optional - If True, returns only the latest period. - **as_dataframe** (bool) - Optional - If True, returns data as a pandas DataFrame. ### `financials.cash_flow()` #### Description Retrieves historical cash flow statement data. #### Parameters - **symbols** (list[str]) - Required - List of stock symbols. - **latest** (bool) - Optional - If True, returns only the latest period. - **as_dataframe** (bool) - Optional - If True, returns data as a pandas DataFrame. ### `financials.metrics()` #### Description Retrieves historical core financial metrics (ROE, PE, PB, etc.). #### Parameters - **symbols** (list[str]) - Required - List of stock symbols. - **latest** (bool) - Optional - If True, returns only the latest period. - **as_dataframe** (bool) - Optional - If True, returns data as a pandas DataFrame. - **show_progress** (bool) - Optional - If True, displays a progress bar for large requests. - **max_workers** (int) - Optional - Maximum number of workers for parallel processing. ### `financials.shares()` #### Description Retrieves historical share data (total shares, float shares). #### Parameters - **symbols** (list[str]) - Required - List of stock symbols. - **as_dataframe** (bool) - Optional - If True, returns data as a pandas DataFrame. ### Request Example (income) ```python income_df = tf.financials.income(symbols, latest=True, as_dataframe=True) ``` ### Response Example (income) ```json [ { "symbol": "600519.SH", "period_end": "2023-12-31", "revenue": 212000000000, "net_income": 62700000000, "eps": 4.91 } ] ``` ``` -------------------------------- ### Fetch Historical Income Statements Source: https://context7.com/tickflow-org/tickflow/llms.txt Retrieves historical income statement data for specified stock symbols. Supports fetching all historical periods or filtering by date range. ```python from tickflow import TickFlow tf = TickFlow(api_key="your-api-key") symbols = ["600519.SH", "000858.SZ", "600036.SH"] # 利润表(所有历史期次) income_df = tf.financials.income(symbols, as_dataframe=True) print(income_df[["symbol", "period_end", "revenue", "net_income"]].tail(6)) ``` -------------------------------- ### Fetch Latest Cash Flow Statement Source: https://context7.com/tickflow-org/tickflow/llms.txt Retrieves the latest cash flow statement for specified stock symbols, including operating cash flow and free cash flow. ```python # 现金流量表 cf_df = tf.financials.cash_flow(symbols, latest=True, as_dataframe=True) print(cf_df[["symbol", "operating_cashflow", "free_cashflow"]]) ``` -------------------------------- ### Fetch Latest Income Statement Source: https://context7.com/tickflow-org/tickflow/llms.txt Retrieves only the most recent income statement for given stock symbols. Includes net income and earnings per share (EPS). ```python # 只取最新一期 latest_income = tf.financials.income(symbols, latest=True, as_dataframe=True) print(latest_income[["symbol", "period_end", "net_income", "eps"]]) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.