### Initialize and Run Strategy Functions Source: https://www.joinquant.com/help/api/help?name=faq Example of a strategy structure including initialization, global variable setup, and scheduled daily functions. ```python # 初始化函数,设定基准等等 def initialize(context): # 设定沪深300作为基准 set_benchmark('000300.XSHG') # 开启动态复权模式(真实价格) set_option('use_real_price', True) # 将日志级别设置为error log.set_level('order', 'error') # 设置全局变量 g.day = 1 # 开盘时运行 run_daily(market_open, time='09:30', reference_security='000300.XSHG') # 快收盘时运行 run_daily(close_market_end, time='14:50', reference_security='000300.XSHG') ## 开盘时运行函数 def market_open(context): print(context.current_dt) print(g.day) print('='*50) ## 快收盘时运行 def close_market_end(context): print("注意注意,快收盘了") print(g.day) print('='*50) ########################### 上面为替换代码前原始代码,下面为替换代码添加 ########################### ``` -------------------------------- ### Scheduled Weekly Execution Example Source: https://www.joinquant.com/help/api/help#name:api This example shows how to schedule a function `market_open` to run on the second trading day of the week. It highlights that the first week's trading days are calculated from the strategy's start date. ```python def initialize(context): run_weekly(market_open, weekday=2, force=False) def market_open(context): print("今天是周内第二个交易日") #注意策略开始的那一周,第一个交易日是按策略开始的日期开始计算的 ``` -------------------------------- ### Fetch All Fund Securities and Filter Main Info Source: https://www.joinquant.com/help/api/doc?id=9933&name=JQDatadoc This example demonstrates how to first get all fund securities, then clean their codes, and finally use `run_offset_query` to fetch matching main information from the FUND_MAIN_INFO table. It's designed to retrieve up to 200,000 records in batches. ```python # 获取所有场内基金的证券信息; df = get_all_securities(types=['fund']) # 获取所有场外基金的证券信息; #df1 = get_all_securities(types=['open_fund']) a = df.index.tolist() # 创建一个新的列表,其中包含去除.OF后缀的基金代码 b = [code.rsplit('.', 1)[0] for code in a] # 筛选出main_code字段与b_cleaned列表中的值相匹配的记录 q = query(finance.FUND_MAIN_INFO).filter(finance.FUND_MAIN_INFO.main_code.in_(b)) df = finance.run_offset_query(q) print(df[:5]) ``` -------------------------------- ### Get Financing and Securities Lending Info for Multiple Funds Source: https://www.joinquant.com/help/api/doc?id=10343&name=JQDatadoc Fetches financing and securities lending data for multiple funds over a specified period. This example first retrieves a list of all fund securities and then queries the data. ```python fund=get_all_securities("fund",date='2023-02-01').index.tolist() df=get_mtss(fund,'2023-02-07','2023-02-09',fields=['date','sec_code','fin_value','fin_buy_value','fin_refund_value','sec_value','sec_sell_value','sec_refund_value','fin_sec_value']) print(df[:5]) ``` -------------------------------- ### Set Universe and Get Historical Data Source: https://www.joinquant.com/help/api/help?name=api Demonstrates setting a universe of stocks and then calling `history` without explicitly listing securities. Shows examples for daily and minute data, and different fields. ```python set_universe(['000001.XSHE']) # 设定universe history(5) # 获取universe中股票的过去5天(不包含今天)的每天的平均价 history(5, '1m') # 获取universe中股票的过去5分钟(不包含当前分钟)的每分钟的平均价 history(5, '1m', 'price') # 获取universe中股票的过去5分钟(不包含当前分钟)的每分钟的平均价 history(5, '1m', 'volume') # 获取universe中股票的过去5分钟(不包含当前分钟)的每分钟的交易额 history(5, '1m', 'price', ['000001.XSHE']) # 获取平安银行的过去5分钟(不包含当前分钟)的每分钟的平均价 ``` -------------------------------- ### Get Security Start Date Source: https://www.joinquant.com/help/api/doc?id=10244&name=JQDatadoc Example of how to retrieve the listing date for a security. The `date` parameter is optional; if omitted, it defaults to the current information. ```python #获取000001.XSHE的上市时间 start_date = get_security_info('000001.XSHE').start_date print(start_date) >>>1991-04-03 ``` -------------------------------- ### Initialize Portfolio Optimizer and Settings Source: https://www.joinquant.com/help/api/help?name=api Sets up the backtesting environment, including benchmark, real price option, order costs, and the optimization model to be used. It also schedules monthly rebalancing. ```python # 导入函数库 import pandas as pd from jqdata import * from jqfactor import Factor from jqlib.optimizer import * # 初始化函数,设定基准等等 def initialize(context): # 设定沪深300作为基准 set_benchmark('000300.XSHG') # 开启动态复权模式(真实价格) set_option('use_real_price', True) # 过滤掉order系列API产生的比error级别低的log # log.set_level('order', 'error') ### 股票相关设定 ### # 股票类每笔交易时的手续费是:买入时佣金万分之三,卖出时佣金万分之三加千分之一印花税, 每笔交易佣金最低扣5块钱 set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock') # 优化器设置 g.optimizer = 2 #设定使用的优化模型 optimize_model = { 1:"模型1:等权重配置", 2:"模型2:组合风险平价;股票的总权重限制为0到90%,ETF的总权重限制为0到10%;每只标的权重不超过10%", 3:"模型3:组合风险最小化(最小化组合方差);组合总权重限制为90%到100%;组合年化收益率目标下限为10%", 4:"模型4:'人气指标5日均值'最大化;组合年化收益率目标下限为10%;每只标的权重不超过20%", 5:"模型5:组合夏普比率最大化;每只标的权重不超过10%" } print("优化%s"%(optimize_model[g.optimizer])) ## 运行函数(reference_security为运行时间的参考标的;传入的标的只做种类区分,因此传入'000300.XSHG'或'510050.XSHG'是一样的) # 开盘前运行 run_monthly(before_market_open, monthday=1, time='9:00', reference_security='000300.XSHG') # 开盘运行 run_monthly(market_open, monthday=1, time='9:30', reference_security='000300.XSHG') ``` -------------------------------- ### Example: Get Daily Price Data Source: https://www.joinquant.com/help/api/index Fetches daily price data for a specific security. The default start date is '2015-01-01' and end date is '2015-12-31' if not specified. ```python get_price('000300.XSHG') ``` -------------------------------- ### Initialize Portfolio Optimizer and Settings Source: https://www.joinquant.com/help/api/help#name:api Sets up the backtesting environment, including benchmark, real price usage, order costs, and selects the optimization model. This function runs once at the beginning of the backtest. ```python # 导入函数库 import pandas as pd from jqdata import * from jqfactor import Factor from jqlib.optimizer import * # 初始化函数,设定基准等等 def initialize(context): # 设定沪深300作为基准 set_benchmark('000300.XSHG') # 开启动态复权模式(真实价格) set_option('use_real_price', True) # 过滤掉order系列API产生的比error级别低的log # log.set_level('order', 'error') ### 股票相关设定 ### # 股票类每笔交易时的手续费是:买入时佣金万分之三,卖出时佣金万分之三加千分之一印花税, 每笔交易佣金最低扣5块钱 set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock') # 优化器设置 g.optimizer = 2 #设定使用的优化模型 optimize_model = { 1:"模型1:等权重配置", 2:"模型2:组合风险平价;股票的总权重限制为0到90%,ETF的总权重限制为0到10%;每只标的权重不超过10%", 3:"模型3:组合风险最小化(最小化组合方差);组合总权重限制为90%到100%;组合年化收益率目标下限为10%", 4:"模型4:'人气指标5日均值'最大化;组合年化收益率目标下限为10%;每只标的权重不超过20%", 5:"模型5:组合夏普比率最大化;每只标的权重不超过10%" } print("优化%s"%(optimize_model[g.optimizer])) ## 运行函数(reference_security为运行时间的参考标的;传入的标的只做种类区分,因此传入'000300.XSHG'或'510300.XSHG'是一样的) # 开盘前运行 run_monthly(before_market_open, monthday=1, time='9:00', reference_security='000300.XSHG') # 开盘运行 run_monthly(market_open, monthday=1, time='9:30', reference_security='000300.XSHG') ``` -------------------------------- ### Example: Get Alpha002 Factor Value (Post-Adjustment) Source: https://www.joinquant.com/help/api/help?name=Alpha191 Example of how to get the Alpha002 factor value for a specific stock on a given date using post-adjusted prices. ```python from jqlib import alpha191 a = alpha191.alpha_002('000001.XSHE','2019-04-24',fq ='post') a ``` -------------------------------- ### Example: Get Alpha002 Factor Value (Pre-Adjustment) Source: https://www.joinquant.com/help/api/help?name=Alpha191 Example of how to get the Alpha002 factor value for a specific stock on a given date using pre-adjusted prices. ```python from jqlib import alpha191 a = alpha191.alpha_002('000001.XSHE','2019-04-24',fq ='pre') a ``` -------------------------------- ### Comprehensive Task Scheduling Example Source: https://www.joinquant.com/help/api/help?name=api This example demonstrates scheduling monthly, weekly, and daily tasks with various time specifications, including specific times, relative to market open/close, and using `every_bar` for minute-level frequency. It also shows how to set a `reference_security` for time synchronization. ```python def weekly(context): print('weekly %s %s' % (context.current_dt, context.current_dt.isoweekday())) def monthly(context): print('monthly %s %s' % (context.current_dt, context.current_dt.month)) def daily(context): print('daily %s' % context.current_dt) def initialize(context): # 指定每月第一个交易日, 在开盘后十分钟执行 # 注意策略开始的那一月,第一个交易日是按策略开始的日期开始计算的 run_monthly(monthly, 1, '09:40') # 指定每周倒数第一个交易日, 在开盘前执行 run_weekly(weekly, -1, '9:00') # 指定每天收盘前10分钟运行 run_daily(daily, '14:50') # 指定每天收盘后执行 run_daily(daily, '15:30') # 指定在每天的10:00运行 run_daily(daily, '10:00') # 指定在每天的01:00运行 run_daily(daily, '01:00') # 参照股指期货的时间每分钟运行一次, 必须选择分钟回测, 否则每天执行 run_daily(daily, 'every_bar', reference_security='IF9999.CCFX') ``` -------------------------------- ### Example: Get Alpha002 Factor Value (No Adjustment) Source: https://www.joinquant.com/help/api/help?name=Alpha191 Example of how to get the Alpha002 factor value for a specific stock on a given date using non-adjusted prices. ```python from jqlib import alpha191 a = alpha191.alpha_002('000001.XSHE','2019-04-24',fq = None) a ``` -------------------------------- ### Initialize Trading Environment Source: https://www.joinquant.com/help/api/help#name:api Sets up the trading environment by defining the benchmark, enabling real-time pricing, and configuring order costs. It also schedules daily functions to run at specific times. ```python def initialize(context): # 设定沪深300作为基准 set_benchmark('000300.XSHG') # 开启动态复权模式(真实价格) set_option('use_real_price', True) # 输出内容到日志 log.info() log.info('初始函数开始运行且全局只运行一次') # 过滤掉order系列API产生的比info级别低的log # log.set_level('order', 'info') ### 股票相关设定 ### # 股票类每笔交易时的手续费是:买入时佣金万分之三,卖出时佣金万分之三加千分之一印花税, 每笔交易佣金最低扣5块钱 set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock') ## 运行函数(reference_security为运行时间的参考标的;传入的标的只做种类区分,因此传入'000300.XSHG'或'510300.XSHG'是一样的) # 开盘前运行 run_daily(before_market_open, time='09:00', reference_security='000300.XSHG') # 开盘时运行 run_daily(market_open, time='09:30', reference_security='000300.XSHG') # 收盘后运行 run_daily(after_market_close, time='15:30', reference_security='000300.XSHG') ``` -------------------------------- ### Get Alpha 002 Factor Value Example Source: https://www.joinquant.com/help/api/help?name=JQData Example demonstrating how to fetch the Alpha 002 factor value for a specific stock and date using dynamic forward adjustment. ```python #获取平安银行2019年4月24日按照动态前复权价格计算的Alpha002的因子值 from jqdatasdk import alpha191 a = alpha191.alpha_002('000001.XSHE','2019-04-24') a 000001.XSHE -0.403162 Name: 2019-04-24 00:00:00, dtype: float64 ``` -------------------------------- ### Simple Strategy Example Source: https://www.joinquant.com/help/api/help#name:api A basic example demonstrating the structure of a JoinQuant strategy, including initialization and a simple trading function that buys or sells based on predefined conditions. ```APIDOC ## Simple Strategy Example ### Description This example shows a minimal, complete trading strategy. It initializes by setting a global variable for the stock to trade and schedules a daily function `market_open` to be called. The `market_open` function checks if the stock is held and either buys 1000 shares or sells 800 shares. ### Code ```python def initialize(context): # Define a global variable to store the stock to operate on g.security = '000001.XSHE' # Run function run_daily(market_open, time='every_bar') def market_open(context): if g.security not in context.portfolio.positions: order(g.security, 1000) else: order(g.security, -800) ``` ``` -------------------------------- ### Order Creation with Status Check and Type Check Source: https://www.joinquant.com/help/api/help?name=api Shows how to create an order, check if it was successful, and then inspect its properties like 'is_buy', 'price', and 'status'. It also demonstrates how to check the type of the status and compare it as a string. ```python def initialize(context): run_daily(market_open, time='every_bar') def market_open(context): orders = order('000001.XSHE', 100) print(orders) # 如果创建订单成功, 则返回Order对象, 失败则返回None if orders is None: print("创建订单成功失败...") else: print(orders.is_buy) print(orders.price) print(orders.status) # 注意返回的status数据类型为,enum 'OrderStatus' print(type(orders.status)) # 判断订单的状态是否指定的状态,需要先转换为str类型 print(str(orders.status) == 'open') print(str(orders.status) == 'held') ``` -------------------------------- ### Example: Get Hengrui Medicine Status Changes Source: https://www.joinquant.com/help/api/doc?id=10023&name=JQDatadoc This example demonstrates how to query the status change information for a specific stock, Hengrui Medicine (600276.XSHG), and prints the resulting DataFrame. ```python # 指定查询对象为恒瑞医药(600276.XSHG)的上市公司状态变动 q=query(finance.STK_STATUS_CHANGE).filter(finance.STK_STATUS_CHANGE.code=='600276.XSHG').limit(10) df=finance.run_query(q) print(df) ``` -------------------------------- ### Filter and Get REITs Funds Source: https://www.joinquant.com/help/api/doc?id=10029&name=JQDatadoc This example demonstrates how to filter the list of all funds to specifically retrieve REITs (Real Estate Investment Trusts). It first gets all 'fund' types and then filters the resulting DataFrame by the 'reits' type. ```python # 获取reits基金 df = get_all_securities(['fund']) print(df[df.type.str.contains("reits") ]) ``` ```text display_name name start_date end_date type 180101.XSHE 博时蛇口产园REIT SKCY 2021-06-21 2200-01-01 reits 180201.XSHE 平安广州广河REIT GZGH 2021-06-21 2200-01-01 reits 180202.XSHE 华夏越秀高速REIT HXYXGSREIT 2021-12-14 2200-01-01 reits 180301.XSHE 红土盐田港REIT YGREIT 2021-06-21 2200-01-01 reits 180801.XSHE 中航首钢绿能REIT SGLN 2021-06-21 2200-01-01 reits 508000.XSHG 张江REIT ZJREIT 2021-06-21 2200-01-01 reits 508001.XSHG 浙江杭徽 ZJHH 2021-06-21 2200-01-01 reits 508006.XSHG 首创水务 SCSW 2021-06-21 2200-01-01 reits 508008.XSHG 铁建REIT TJREIT 2022-07-08 2200-01-01 reits 508018.XSHG 中交REIT ZJREIT 2022-04-28 2200-01-01 reits 508027.XSHG 东吴苏园 DWSY 2021-06-21 2200-01-01 reits 508056.XSHG 普洛斯 PLS 2021-06-21 2200-01-01 reits 508099.XSHG 中关村 ZGC 2021-12-17 2200-01-01 reits ``` -------------------------------- ### Create Backtest with Initial Positions Source: https://www.joinquant.com/help/api/index This snippet demonstrates how to set up and initiate a backtest using the `create_backtest` function. It includes defining algorithm parameters, initial cash, and specific initial positions for securities. ```python algorithm_id = "xxxx" extra_vars = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} initial_positions = [ { 'security':'000001.XSHE', 'amount':'100', }, { 'security':'000063.XSHE', 'amount':'100', 'avg_cost': '1.0' }, ] params = { "algorithm_id": algorithm_id, "start_date": "2015-10-01", "end_date": "2016-07-31", "frequency": "day", "initial_cash": "1000000", "initial_positions": initial_positions, "extras": extra_vars, } created_bt_id = create_backtest(code=code, **params) ``` -------------------------------- ### Example: Fetching Per Share Financial Data Source: https://www.joinquant.com/help/api/doc?id=10437&name=JQDatadoc Demonstrates how to call `get_factor_values` to retrieve 'total_operating_revenue_per_share_ttm', 'cash_and_equivalents_per_share', and 'surplus_reserve_fund_per_share' for a specific stock between two dates. It then shows how to print the data for one of the requested factors. ```python from jqdatasdk import get_factor_values factor_data = get_factor_values(securities=['000001.XSHE'], factors=['total_operating_revenue_per_share_ttm','cash_and_equivalents_per_share','surplus_reserve_fund_per_share'], start_date='2022-01-01', end_date='2022-01-10') # 查看因子值 print(factor_data['cash_and_equivalents_per_share']) ``` -------------------------------- ### Get Listing Date of a Convertible Bond Source: https://www.joinquant.com/help/api/help?name=JQData Example demonstrating how to retrieve the listing date for a given convertible bond code. ```python # 获取128145.XSHE的上市时间 start_date = get_security_info('128145.XSHE').start_date print(start_date) ``` -------------------------------- ### Example: Query Over-the-Counter Fund Bond Holdings Source: https://www.joinquant.com/help/api/doc?id=9935&name=JQDatadoc This example shows how to query bond holdings for an over-the-counter fund by its code, ordering results by publication date in descending order and limiting to 5 entries. ```python #查询中海环保新能源主题灵活配置混合型证券投资基金("398051")基金持有的债券组合数据 df=finance.run_query(query(finance.FUND_PORTFOLIO_BOND).filter(finance.FUND_PORTFOLIO_BOND.code=='398051').order_by(finance.FUND_PORTFOLIO_BOND.pub_date.desc()).limit(5)) print(df) ``` -------------------------------- ### Get Display Name of a Convertible Bond Source: https://www.joinquant.com/help/api/help?name=JQData Example demonstrating how to retrieve the Chinese display name for a given convertible bond code. ```python # 获取110043.XSHG的中文名称 display_name = get_security_info('110043.XSHG').display_name print(display_name) ``` -------------------------------- ### Get Financial Data for a Specific Day Source: https://www.joinquant.com/help/api/doc?id=9885&name=JQDatadoc Example demonstrating how to retrieve all financial indicator data for a particular stock on a specific day. ```python get_fundamentals(query_object, date='2015-03-31') ``` -------------------------------- ### Install JQData SDK Source: https://www.joinquant.com/help/api/doc?id=10748&name=JQDatadoc Install the JQData Python package using pip. Ensure you have a Python environment set up. ```bash pip install jqdatasdk ``` -------------------------------- ### Example: Fetch Latest Option Contract Data Source: https://www.joinquant.com/help/api/doc?id=9918&name=JQDatadoc This example demonstrates how to query for the latest basic information of a specific option contract using its code. The result is printed as a pandas DataFrame. ```python from jqdatasdk import * q=query(opt.OPT_CONTRACT_INFO).filter(opt.OPT_CONTRACT_INFO.code=='10001313.XSHG') df=opt.run_query(q) print(df) ``` -------------------------------- ### Get All Convertible Bond Securities Source: https://www.joinquant.com/help/api/doc?id=10514&name=JQDatadoc Retrieves a list of all tradable convertible bonds. This is the starting point for accessing convertible bond market data. ```python get_all_securities ``` -------------------------------- ### Initialize Tick-Level Strategy with Sub-Portfolios Source: https://www.joinquant.com/help/api/index Example of initializing a tick-level strategy, setting up a futures sub-portfolio, and scheduling daily functions. It demonstrates subscribing to a specific futures contract. ```python # 回测时间段2019-06-03到2019-06-04,运行频率设置为tick # 初始化 def initialize(context): # 获取起始资金 init_cash = context.portfolio.starting_cash # 交易品种为期货 set_subportfolios([SubPortfolioConfig(cash=init_cash, type='futures')]) # 定义一个全局变量, 保存要操作的期货 g.code1 = 'RB1909.XSGE' # 08:30运行自定义开盘前运行函数 run_daily(before_market_open, time='08:30', reference_security='RB9999.XSGE') # 15:30运行自定义收盘后运行函数 run_daily(after_market_open, time='15:30', reference_security='RB9999.XSGE') # 开盘前运行函数 def before_market_open(context): # 订阅要操作的期货 subscribe(g.code1, 'tick') # 有tick事件时运行函数 def handle_tick(context, tick): # 获取最新的 tick 数据 tick_data = get_current_tick(g.code1) print(tick_data) # 收盘后运行函数 def after_market_close(context): # 取消今天订阅的标的 unsubscribe_all() ``` -------------------------------- ### Get and Rename Columns to Chinese Source: https://www.joinquant.com/help/api/doc?id=10745&name=JQDatadoc This snippet shows how to get field information for the option adjustment record table, create a mapping from English to Chinese column names, and then rename the DataFrame columns accordingly. It also includes an example of running a query and limiting the results. ```python # 获取期权合约调整记录表的字段信息 table=get_table_info(opt.OPT_ADJUSTMENT) # 对 OPT_ADJUSTMENT 表的name_en列建立索引,并清理该表中name_zh列的所有空值记录。 columns = jq.get_table_info(jq.opt.OPT_ADJUSTMENT).set_index("name_en").name_zh.dropna() # 获取期权合约调整记录表 df = jq.opt.run_query(jq.query(jq.opt.OPT_ADJUSTMENT ).limit(20)) # 重命名DataFrame中的列名为中文 df.rename(columns=columns) ``` -------------------------------- ### Example: Query Remaining Daily Data Calls Source: https://www.joinquant.com/help/api/help?name=JQData Example of how to query and print the remaining daily data calls. This helps in monitoring data usage. ```python #查询当日剩余可调用数据条数 count=get_query_count() print(count) ``` -------------------------------- ### Install JQData SDK Source: https://www.joinquant.com/help/api/doc?id=9832&name=logon Use pip to install the JQData package in your local Python environment. ```bash pip install jqdatasdk ``` -------------------------------- ### Get Security Display Name Source: https://www.joinquant.com/help/api/doc?id=10244&name=JQDatadoc Example of how to retrieve the Chinese display name for a security on a specific date. Ensure you have the correct security code format. ```python # 获取000001.XSHE某一日期的中文名称 display_name = get_security_info('000001.XSHE',date='2017-08-31').display_name print(display_name) >>>平安银行 ``` -------------------------------- ### Example: Fetching Index Valuation Fields Source: https://www.joinquant.com/help/api/doc?id=10716&name=JQDatadoc Demonstrates how to fetch multiple valuation fields for a specific index within a date range. The output shows the first two rows of the resulting DataFrame. ```python df=get_index_valuation('000001.XSHG', start_date='2024-05-02', end_date='2024-06-03', fields=['pe_ratio','turnover_ratio','pb_ratio','ps_ratio','pcf_ratio','capitalization','market_cap','circulating_cap','circulating_market_cap','pe_ratio_lyr','pcf_ratio2','dividend_ratio','free_cap','free_market_cap','a_cap','a_market_cap']) df[:2] ``` -------------------------------- ### Get Concept List Source: https://www.joinquant.com/help/api/index Retrieves a list of all concept板块 (concept boards) available on the platform. The output includes concept codes, names, and start dates. ```python from jqdata import * get_concepts() ``` -------------------------------- ### Get Multiple Futures Daily Data Source: https://www.joinquant.com/help/api/help?name=Future Example of retrieving daily K-line data for multiple futures contracts. This returns a pandas Panel object by default. ```python panel = get_price(['IC1505.CCFX', 'IC1506.CCFX'], start_date='2015-05-06', end_date='2015-05-08') ``` -------------------------------- ### Example: Displaying First 5 JQData Special Indices Source: https://www.joinquant.com/help/api/doc?id=10759&name=JQDatadoc Demonstrates how to display the first 5 entries from the result of get_all_securities when fetching JQData special indices. ```python get_all_securities(types=['spi'], date=None)[:5] ``` -------------------------------- ### Get Single Futures Daily Data Source: https://www.joinquant.com/help/api/help?name=Future Example of retrieving daily K-line data for a single futures contract. Ensure the date range is correctly specified. ```python df = get_price('IC1506.CCFX', start_date='2015-05-06', end_date='2015-05-08') ``` -------------------------------- ### Example: Query Market Calendar Data Source: https://www.joinquant.com/help/api/doc?id=9867&name=JQDatadoc Demonstrates how to query and print market calendar data for a specified date range. This example shows the structure of the returned DataFrame. ```python q=query(finance.STK_EXCHANGE_LINK_CALENDAR).filter(finance.STK_EXCHANGE_LINK_CALENDAR.day>='2015-01-04').limit(4) df=finance.run_query(q) print(df) ``` -------------------------------- ### Example: Fetching Skewness60 Factor Data Source: https://www.joinquant.com/help/api/help?name=JQData Demonstrates how to retrieve the 'Skewness60' factor for a specific stock ('000001.XSHE') between '2017-01-01' and '2017-03-04'. This example also fetches 'DEGM' and 'quick_ratio' factors. ```python # 导入函数库 from jqdatasdk import get_factor_values # 获取因子Skewness60(个股收益的60日偏度)从 2017-01-01 至 2017-03-04 的因子值 factor_data = get_factor_values(securities=['000001.XSHE'], factors=['Skewness60','DEGM','quick_ratio'], start_date='2017-01-01', end_date='2017-03-04') ``` -------------------------------- ### Get Security Start Date Source: https://www.joinquant.com/help/api/doc?id=10255&name=JQDatadoc Retrieves the listing date for a given security code. The date is returned as a datetime.date object. Ensure the security code is valid. ```python start_date = get_security_info('518860.XSHG').start_date print(start_date) ``` -------------------------------- ### Get Single Stock Daily Price Data Source: https://www.joinquant.com/help/api/help?name=api Retrieves daily price data for a specific stock. You can specify start and end dates, frequency, and desired fields. ```python df = get_price('000001.XSHE') # 获取000001.XSHE的2015年的按天数据 ``` ```python df = get_price('000001.XSHE', start_date='2015-01-01', end_date='2015-01-31 23:00:00', frequency='1m', fields=['open', 'close']) # 获得000001.XSHG的2015年01月的分钟数据, 只获取open+close字段 ``` ```python df = get_price('000001.XSHE', count = 2, end_date='2015-01-31', frequency='daily', fields=['open', 'close']) # 获取获得000001.XSHG在2015年01月31日前2个交易日的数据 ``` ```python df = get_price('000001.XSHE', start_date='2015-12-01 14:00:00', end_date='2015-12-02 12:00:00', frequency='1m') # 获得000001.XSHG的2015年12月1号14:00-2015年12月2日12:00的分钟数据 ```