""" AmazingData 数据源适配器 - 使用示例 本文件展示了如何使用 AmazingDataAdapter 获取各类金融数据 """ from amazing_data_adapter import ( AmazingDataAdapter, DataSourceConfig, SecurityType, Market, Period, create_adapter ) import pandas as pd def demo_basic_usage(): """基础使用示例""" # 方式1: 使用配置对象创建 config = DataSourceConfig( username='your_username', password='your_password', host='your_host', port=8080, local_path='./amazing_data_cache/', use_local_cache=True ) adapter = AmazingDataAdapter(config) # 方式2: 使用便捷函数创建 # adapter = create_adapter( # username='your_username', # password='your_password', # host='your_host', # port=8080 # ) # 连接数据源 if not adapter.connect(): print("连接失败") return try: # ============== 基础数据 ============== print("\n=== 基础数据 ===") # 获取沪深A股代码列表 stock_codes = adapter.get_code_list(SecurityType.STOCK_A) print(f"沪深A股数量: {len(stock_codes)}") # 获取ETF代码列表 etf_codes = adapter.get_code_list(SecurityType.ETF) print(f"ETF数量: {len(etf_codes)}") # 获取期货代码列表 future_codes = adapter.get_code_list(SecurityType.FUTURE) print(f"期货数量: {len(future_codes)}") # 获取证券基本信息 stock_info = adapter.get_code_info(SecurityType.STOCK_A) print(f"\n证券信息列: {stock_info.columns.tolist()}") print(stock_info.head()) # 获取交易日历 calendar = adapter.get_trading_calendar(Market.SH) print(f"\n交易日数量: {len(calendar)}") print(f"最近交易日: {calendar[-5:]}") # ============== 历史行情数据 ============== print("\n=== 历史行情数据 ===") # 获取日K线数据 sample_codes = stock_codes[:5] # 取前5只股票作为示例 kline_data = adapter.get_kline( codes=sample_codes, start_date='20240101', end_date='20241231', period=Period.DAILY ) for code, df in list(kline_data.items())[:2]: print(f"\n{code} K线数据:") print(df.head()) # 获取分钟K线 min_kline = adapter.get_kline( codes=['000001.SZ'], start_date='20241201', end_date='20241231', period=Period.MIN60 ) # ============== 复权因子 ============== print("\n=== 复权因子 ===") adj_factor = adapter.get_adj_factor( codes=['000001.SZ', '600000.SH'], is_local=False # 强制从服务器获取最新数据 ) print("单次复权因子:") print(adj_factor.head()) backward_factor = adapter.get_backward_factor( codes=['000001.SZ', '600000.SH'] ) print("\n后复权因子:") print(backward_factor.head()) # ============== 财务数据 ============== print("\n=== 财务数据 ===") # 获取资产负债表 balance_sheet = adapter.get_balance_sheet( codes=['000001.SZ', '600000.SH'], start_date=20240101, end_date=20241231 ) for code, df in balance_sheet.items(): print(f"\n{code} 资产负债表字段:") print(df.columns.tolist()[:10]) # 显示前10个字段 # 获取现金流量表 cash_flow = adapter.get_cash_flow( codes=['000001.SZ'], start_date=20240101, end_date=20241231 ) # 获取利润表 income = adapter.get_income_statement( codes=['000001.SZ'], start_date=20240101, end_date=20241231 ) # 获取业绩快报 profit_express = adapter.get_profit_express( codes=['000001.SZ', '600000.SH'] ) print(f"\n业绩快报:\n{profit_express.head()}") # ============== 股东股本数据 ============== print("\n=== 股东股本数据 ===") # 获取十大股东 top10_holders = adapter.get_top10_shareholders( codes=['000001.SZ'], start_date=20240101, end_date=20241231 ) print(f"十大股东:\n{top10_holders.head()}") # 获取股东户数 holder_count = adapter.get_shareholder_count( codes=['000001.SZ'], start_date=20240101, end_date=20241231 ) print(f"\n股东户数:\n{holder_count.head()}") # 获取股本结构 equity_structure = adapter.get_equity_structure( codes=['000001.SZ'] ) print(f"\n股本结构:\n{equity_structure.head()}") # ============== 融资融券数据 ============== print("\n=== 融资融券数据 ===") # 获取融资融券汇总 margin_summary = adapter.get_margin_summary( start_date=20240101, end_date=20241231 ) print(f"融资融券汇总:\n{margin_summary.head()}") # 获取个股融资融券明细 margin_detail = adapter.get_margin_detail( codes=['000001.SZ'], start_date=20241201, end_date=20241231 ) # ============== 交易异动数据 ============== print("\n=== 交易异动数据 ===") # 获取龙虎榜 longhu = adapter.get_longhu_bang( codes=['000001.SZ'], start_date=20241201, end_date=20241231 ) print(f"龙虎榜数据:\n{longhu.head()}") # 获取大宗交易 block_trade = adapter.get_block_trading( codes=['000001.SZ'], start_date=20241201, end_date=20241231 ) print(f"\n大宗交易:\n{block_trade.head()}") # ============== 指数数据 ============== print("\n=== 指数数据 ===") # 获取指数成分股 (沪深300) index_constituents = adapter.get_index_constituents(['000300.SH']) for code, df in index_constituents.items(): print(f"\n{code} 成分股数量: {len(df)}") print(df.head()) # 获取指数成分股权重 index_weights = adapter.get_index_weights( codes=['000300.SH', '000905.SH'], # 沪深300和中证500 start_date=20241201, end_date=20241231 ) # ============== ETF数据 ============== print("\n=== ETF数据 ===") # 获取ETF申赎数据 etf_info, etf_constituents = adapter.get_etf_pcf(['510050.SH']) print(f"ETF基本信息:\n{etf_info.head()}") # 获取基金份额 fund_share = adapter.get_fund_share( codes=['510050.SH'], start_date=20240101, end_date=20241231 ) # ============== 可转债数据 ============== print("\n=== 可转债数据 ===") # 获取可转债发行数据 kzz_codes = adapter.get_code_list(SecurityType.KZZ) print(f"可转债数量: {len(kzz_codes)}") if kzz_codes: kzz_issuance = adapter.get_kzz_issuance(kzz_codes[:3]) for code, df in list(kzz_issuance.items())[:1]: print(f"\n{code} 发行信息:\n{df.head()}") finally: # 断开连接 adapter.disconnect() def demo_data_processing(): """数据处理示例 - 展示如何加工获取的数据""" adapter = create_adapter( username='your_username', password='your_password', host='your_host', port=8080 ) if not adapter.connect(): return try: # 获取平安银行(000001.SZ)的日K线数据 kline_data = adapter.get_kline( codes=['000001.SZ'], start_date='20240101', end_date='20241231', period=Period.DAILY ) df = kline_data['000001.SZ'] # 计算技术指标 # 1. 移动平均线 df['MA5'] = df['close'].rolling(window=5).mean() df['MA10'] = df['close'].rolling(window=10).mean() df['MA20'] = df['close'].rolling(window=20).mean() # 2. 涨跌幅 df['return'] = df['close'].pct_change() # 3. 波动率 (20日) df['volatility'] = df['return'].rolling(window=20).std() * (252 ** 0.5) # 4. 成交量移动平均 df['volume_MA5'] = df['volume'].rolling(window=5).mean() print("加工后的数据:") print(df[['close', 'MA5', 'MA10', 'MA20', 'return', 'volatility']].tail(10)) # 获取复权因子并计算复权价格 adj_factor = adapter.get_backward_factor(['000001.SZ']) # 合并K线和复权因子 df['trade_date'] = df.index.strftime('%Y%m%d').astype(int) df = df.merge( adj_factor[['000001.SZ']].reset_index(), left_on='trade_date', right_on='index', how='left' ) df = df.rename(columns={'000001.SZ': 'adj_factor'}) # 计算后复权价格 df['adj_close'] = df['close'] * df['adj_factor'] print("\n复权后的价格:") print(df[['close', 'adj_factor', 'adj_close']].tail(10)) finally: adapter.disconnect() def demo_batch_processing(): """批量处理示例""" adapter = create_adapter( username='your_username', password='your_password', host='your_host', port=8080 ) if not adapter.connect(): return try: # 获取沪深300成分股 index_constituents = adapter.get_index_constituents(['000300.SH']) hs300_codes = index_constituents['000300.SH']['CON_CODE'].tolist() print(f"沪深300成分股数量: {len(hs300_codes)}") # 批量获取财务数据 (分批处理避免超时) batch_size = 50 all_balance_sheets = {} for i in range(0, len(hs300_codes), batch_size): batch_codes = hs300_codes[i:i+batch_size] print(f"处理第 {i//batch_size + 1} 批,共 {len(batch_codes)} 只股票") batch_data = adapter.get_balance_sheet( codes=batch_codes, start_date=20240930, end_date=20240930 ) all_balance_sheets.update(batch_data) # 合并所有数据 combined_data = [] for code, df in all_balance_sheets.items(): if not df.empty: df['code'] = code combined_data.append(df) if combined_data: result_df = pd.concat(combined_data, ignore_index=True) print(f"\n合并后的数据形状: {result_df.shape}") print(result_df[['code', 'REPORTING_PERIOD', 'TOTAL_ASSETS', 'TOTAL_CUR_ASSETS']].head()) finally: adapter.disconnect() if __name__ == "__main__": print("=" * 60) print("AmazingData 数据源适配器 - 使用示例") print("=" * 60) # 注:实际运行前请替换用户名、密码和服务器地址 print("\n提示: 请先在代码中替换 username, password, host, port 为实际值") # demo_basic_usage() # demo_data_processing() # demo_batch_processing()