Welcome to xalpha’s documentation!

快速开始

xalpha 可以用来对场外基金和指数进行方便的追踪和研究, 同时可以实现投资情况的汇总管理与数据分析,并且支持一些简单的基金购买策略回测。

本文仅简述最基本的模块使用的一小部分,关于更多的函数和用法尤其是可视化的部分,请参考具体示例 具体示例。 关于数据结构和内部的模块设计,请参考高级用法 高级用法

基金和指数的信息

使用 xalpha.info.fundinfo 来获取场外基金的基本信息和历史每日净值情况。 其中净值以 pandas.DataFrame 的格式存储。

Note

基金信息只支持按净值法结算的场外基金,也即货币基金不被支持。货币基金需额外使用 xalpha.info.mfundinfo 类。

代码示例:

    >>> import xalpha as xa
    >>> zzyl = xa.fundinfo('000968')
    >>> zzyl
    广发养老指数A
    >>> zzyl.info()
    fund name: 广发养老指数A
    fund code: 000968
    fund purchase fee: 0.12%
    fund redemption fee info: ['小于7天', '1.50%', '大于等于7天,小于1年', '0.50%', '大于等于1年,小于2年', '0.30%', '大于等于2年', '0.00%']
    >>> zzyl.price[zzyl.price['date']<='2015-02-27']
    comment date    netvalue        totvalue
    0       0       2015-02-13      1.0000  1.0000
    1       0       2015-02-17      1.0000  1.0000
    2       0       2015-02-27      1.0123  1.0123
    >>> zzyl.get_stock_holdings(2019, 4)
code  name  ratio   share    value
0   300773   拉卡拉   1.48   32.31  2535.37
1   600053  九鼎投资   1.44   97.15  2470.51
2   002624  完美世界   1.32   51.38  2268.08
3   300464  星徽精密   1.32  150.76  2259.92
4   300251  光线传媒   1.30  188.09  2219.43
..     ...   ...    ...     ...      ...
87  688389  普门科技   0.01    0.69     9.40
88  688081  兴图新科   0.01    0.32     8.89
89  002972   科安达   0.00    0.11     2.15
90  603109  神驰机电   0.00    0.07     1.81
91  002973  侨银环保   0.00    0.11     0.66
>>> zzyl.get_bond_holdings(2019, 4) # None returned

使用 xalpha.info.indexinfo 来获取相应指数的每日净值情况。

Note

indexinfo() 对应的指数代码为7位数,其中后六位是正常的指数代码,第一位用来标记市场,0是沪市,1是深市。也可以使用 SH 或 SZ 加6位代码的形式。

代码示例:

>>> zzyli = xa.indexinfo('SZ399812')
>>> zzyli
养老产业
>>> zzyli.price[zzyli.price['date']=='2018-08-01']
        comment date    netvalue        totvalue
1       0       2018-08-01      7.603842        7524.4807

Note

对应的 indexinfo().price 表中,netvalue 栏为以初始日归一化后的净值,而 totvalue 栏则是真实的指数值。

单一标的交易处理

使用 xalpha.trade.trade 来处理交易情况。 为了生成交易,需要提供标的类 xalpha.info 和交易账单 status table。 账单的具体的数据结构请参考高级用法 高级用法

代码示例:

>>> yyws = xa.fundinfo('001180') # 交易标的信息
>>> statb = xa.record(path).status # path位置的交易账单csv
>>> yyws_t = xa.trade(yyws, statb)
>>> yyws_t.dailyreport()
{'currentshare': 630.39,
 'currentvalue': 504.12,
 'date': datetime.datetime(2018, 8, 5, 0, 0),
 'originalvalue': 523.86,
 'returnrate': -3.7682,
 'unitcost': 0.831,
 'unitvalue': 0.79969999999999997}
>>> yyws_t.xirrrate('2018-08-01')
-0.01764033506484772

基金投资组合的管理分析

使用 xalpha.multiple.mul 可以将多个基金交易类归总,或者根据 status 表格上记录的基金代码自动汇总。 如果选择 xalpha.multiple.mulfix 归总交易情况的话,则所有交易视作封闭系统,资金进出由虚拟的货币基金调节。 代码示例:

>>> invclose = xa.mulfix(yyws_t, totmoney = 6000)
>>> invclose.combsummary()
        基金代码    基金名称                    基金成本    基金收益率   基金现值
0       001180  广发医药卫生联接A       523.86  -3.7682 504.12
1       mf              货币基金                    5476.15 7.3475  5878.51
2       xxxxxx  总计                              6000.01 6.3770  6382.63
>>> invopen = xa.mul(status=xa.record(path).status)
>>> invopen.combsummary('2018-07-01').iloc[-1]
基金代码      xxxxxx
基金名称          总计
基金成本     2379.52
基金收益率    -4.2559
基金现值     2278.25
Name: 5, dtype: object
>>> invopen.xirrrate('2018-07-01')
-0.05594572489624858

基金交易策略与回测

通过额外导入 policy 模块,使用 xalpha.policy.policy 的子类,进行按一定策略的模拟交易的 status 表格生成, 从而可以进行相关的交易分析,起到策略回测比较的作用。对应类的 self.status 属性即为相应策略的 status 交易表格, 可以用于上述的交易分析使用。 代码示例:

>>> st = xa.policy.buyandhold(yyws,'2016-01-01') # buy and hold from 2016-01-01, 且始终分红再投入
>>> st2 = xa.policy.scheduled(yyws, totmoney = 1000, times=pd.date_range('2016-01-01','2018-06-01',freq='W-THU')) # 定投 status 的生成:从2016-01-01 到 2018-06-01 每周四进行定额定投 1000 元。

交易策略的监视和定时提醒

使用 xalpha.realtime.review 可以实现策略的监测和邮件的发送,具体使用可以查看 示例

通用日线和实时数据获取器

使用 xalpha.universal.get_daily(),给定一个代码,直接返回日线数据的 DataFrame。覆盖范围包括沪深市场的股票,基金,ETF,LOF,可转债 债券;香港市场的股票,指数;美国市场的股票,指数,ETF;人民币兑外币的中间价数据;和其他在 investing.com 上可以访问的金融产品的日线数据。 以及可以从标普,ft 和彭博网站找到的标的数据。及以聚宽为数据源的指数估值数据,基金份额数据,指数总盈利总资产数据和宏观经济数据。

使用 xalpha.universal.get_rt(),给定一个代码,直接返回实时数据 json。覆盖范围包括沪深市场的股票,场内基金,ETF,LOF,可转债 债券;香港市场的股票,指数;美国市场的股票,指数,ETF;和其他在 investing.com 上可以访问的金融产品的日线数据。

使用 xalpha.universal.get_bar(),给定一个代码,直接返回相应标的的分钟线,5分钟线,小时线,周线等不同频率的近期分时数据。

代码示例:

>>> xa.get_daily("EUR/CNY", prev=5) # 人民币中间价数据
        date   close
4 2020-03-30  7.8288
3 2020-03-31  7.8088
2 2020-04-01  7.8090
1 2020-04-02  7.7678
0 2020-04-03  7.7081
>>> xa.get_daily("currencies/usd-cnh") # 英为离岸人民币
     date    open   close    high     low percent
260 2019-04-05  6.7167  6.7122  6.7194  6.7033  -0.07%
259 2019-04-08  6.7100  6.7173  6.7278  6.7082   0.08%
258 2019-04-09  6.7172  6.7195  6.7241  6.7127   0.03%
257 2019-04-10  6.7188  6.7187  6.7270  6.7164  -0.01%
..         ...     ...     ...     ...     ...     ...
3   2020-03-31  7.1133  7.0940  7.1177  7.0796  -0.29%
2   2020-04-01  7.0932  7.1230  7.1336  7.0772   0.41%
1   2020-04-02  7.1216  7.0929  7.1422  7.0846  -0.42%
0   2020-04-03  7.0919  7.1108  7.1197  7.0857   0.25%
>>> xa.get_daily("FT-ZGLD:SWX:CHF", start="2020-03-01") # ft.com 基金数据
         date    open   close    high     low
24 2020-03-02  470.10  465.30  472.05  463.75
23 2020-03-03  465.95  477.20  477.85  465.30
22 2020-03-04  477.05  478.00  480.85  475.35
21 2020-03-05  476.75  479.15  481.30  476.75
..         ...     ...     ...     ...     ...
3  2020-03-31  475.70  474.00  475.70  469.80
2  2020-04-01  466.90  468.10  470.80  464.10
1  2020-04-02  468.45  476.75  479.80  467.40
0  2020-04-03  477.80  481.00  483.00  477.55
>>> xa.get_daily("HK00700", prev=5, end="2018-08-08") # 雪球港股数据
          date      open     close      high       low  percent
198 2018-08-03  347.2475  348.8432  353.6300  345.6519     1.39
199 2018-08-06  356.8213  352.0344  356.8213  349.0426     0.91
200 2018-08-07  354.0289  356.0235  357.4196  347.6464     1.13
201 2018-08-08  365.5972  363.0043  365.5972  359.6136     1.96
>>> xa.get_daily("SH000050", prev=10) # 雪球A股指数数据
         date       open    close       high        low  percent
3  2020-03-25  2203.7900  2206.63  2216.0700  2188.3800     2.41
4  2020-03-26  2187.4600  2193.85  2208.5900  2179.9800    -0.58
5  2020-03-27  2219.5900  2203.25  2232.4400  2202.3000     0.43
6  2020-03-30  2172.8685  2188.88  2196.6724  2168.4372    -0.65
7  2020-03-31  2207.6900  2176.42  2208.7200  2173.4300    -0.57
8  2020-04-01  2170.1100  2171.34  2203.6400  2168.4400    -0.23
9  2020-04-02  2160.1300  2204.57  2204.5700  2159.0300     1.53
10 2020-04-03  2197.7113  2195.55  2210.2124  2188.8462    -0.41
>>> xa.get_bar("LK", interval=3600, prev=12) # 雪球美股小时线数据
                  date    open  high   low   close    volume  turnoverrate  percent
0  2020-04-03 00:30:00  7.3001  7.60  6.71  7.0497  30253047         12.58    -3.23
1  2020-04-03 01:30:00  7.0500  7.20  6.51  6.5450  17016394          7.09    -7.16
2  2020-04-03 02:30:00  6.5499  6.83  6.06  6.3700  16905661          7.03    -2.67
3  2020-04-03 03:30:00  6.3900  6.78  6.04  6.2750  13580987          5.65    -1.49
4  2020-04-03 04:00:00  6.2701  6.50  6.15  6.4000  14765141          6.08     1.99
5  2020-04-03 22:30:00  7.0500  7.35  6.10  6.2400  38361837         15.24    -2.50
6  2020-04-03 23:30:00  6.2388  6.24  5.42  5.5844  20746500          8.23   -10.51
7  2020-04-04 00:30:00  5.5898  5.75  5.52  5.7200   9299638          3.70     2.43
8  2020-04-04 01:30:00  5.7200  5.93  5.55  5.6150   6926332          2.75    -1.84
9  2020-04-04 02:30:00  5.6200  5.72  5.52  5.6250   4374535          1.74     0.18
10 2020-04-04 03:30:00  5.6300  5.84  5.54  5.6550   5066923          2.01     0.53
11 2020-04-04 04:00:00  5.6599  5.69  5.28  5.3800  10524216          4.15    -4.86
>>> xa.get_bar("commodities/brent-oil", interval=60) # 英为油价分钟线
                  date  close
0  2020-04-04 04:36:00  34.87
1  2020-04-04 04:37:00  34.87
2  2020-04-04 04:38:00  34.92
3  2020-04-04 04:39:00  34.93
4  2020-04-04 04:40:00  34.95
5  2020-04-04 04:41:00  34.98
6  2020-04-04 04:42:00  34.96
7  2020-04-04 04:43:00  34.96
8  2020-04-04 04:44:00  34.93
9  2020-04-04 04:45:00  34.96
10 2020-04-04 04:46:00  34.98
11 2020-04-04 04:47:00  34.91
12 2020-04-04 04:48:00  34.95
13 2020-04-04 04:49:00  34.94
14 2020-04-04 04:50:00  34.98
15 2020-04-04 04:51:00  34.95
16 2020-04-04 04:52:00  34.87
17 2020-04-04 04:53:00  34.83
18 2020-04-04 04:54:00  34.78
19 2020-04-04 04:55:00  34.84
20 2020-04-04 04:56:00  34.80
21 2020-04-04 04:57:00  34.77
22 2020-04-04 04:58:00  34.83
23 2020-04-04 04:59:00  34.83
>>> xa.get_rt("SH501018") # 实时行情数据
{'name': '南方原油LOF', 'current': 0.826, 'percent': -0.48, 'current_ext': None, 'currency': 'CNY', 'market': 'CN'}
>>> xa.get_rt("indices/germany-30") # 海外指数实时数据
{'name': '德国DAX30指数 (GDAXI)', 'current': 9525.77, 'current_ext': None, 'currency': 'EUR', 'percent': -0.47, 'market': 'DE'}

更有趣的是,任何 get_daily 获取的标的,都可以套壳成上边的 info 类,从而进行模拟交易和组合分析,而不管其底层是原油,汇率甚至是 AH 比价。

>>> oil = xa.vinfo("commodities/brent-oil", start="20180101")
>>> oil.info()
fund name: 伦敦布伦特原油期货 - 2020年6月 (LCOM0)
fund code: commodities/brent-oil
fund purchase fee: 0%
# 如上的 oil info 对象也可以进行 trade 交易和 mul 组合分析
>>> oil.max_drawdown()
(Timestamp('2018-10-03 00:00:00'), Timestamp('2020-03-31 00:00:00'), -0.736470042878665)

功能综述

鉴于此页仅涵盖了非常小一部分功能的展示,除了参考其他部分学习外,这里整理出了该模块的基本功能。

  1. 全部基金(包括货币基金)的信息获取:指定一个代码,你就能了解的基金名称,历史单位净值,历史分红送转情况,基金的折扣申购费,基金的不同持仓时长的赎回费等多样的信息。

  2. 全部 A 股指数的信息获取:同样是一个代码,获取指数名称和每日净值。

  3. 所有基金指数数据支持增量更新,csv 文件和数据库 io 的无缝支持

  4. 可以对多只基金和指数同时进行量化分析,给出走势分布和相关性分析。

  5. 虚拟可调的货币基金类型:除了前述的真实货币基金类外,还可以建立虚拟的货币基金类,来模拟理财等的行为,或单纯作为量化的基准,可以实现更灵活的仓位管理。

  6. 只需最简的账单外加一个代码就可以精确模拟一只基金用户的全部交易行为,并可以输出各种量化数据和可视化。

  7. 大量基于回测的量化数据和基于趋势交易的技术面指标工具箱。

  8. 只需一个最简的账单,就可实现多基金投资系统的投资精确模拟,同时提供总金额固定和总金额变动两个选项,可以显示全部基金投资的总结表和多样的持仓与交易量化,包括折线图,河流图,饼图,柱形图等。所有可视化均为可交互的 web 级可视化方案。

  9. 可以非常简便的制定各种基于日期和点数的定投策略,包括变额定投和复杂的网格策略均可以一行完成,并进行详细的回测分析与可视化展示。

  10. 可以基于净值或各种技术指标的交叉,点位设计复杂的交易策略,并回测效果进行定量分析。

  11. 可以根据自定义的策略,建立邮件按时提醒脚本,从此实现按计划买入和对市场的实时监控,尤其适合复杂网格策略的执行,不需要自己再去看盘和计算执行条件和金额。

  12. 使用通用的金融数据日线 API,轻松获取不同数据进行交叉分析, 数据包括但不限于 A 股市场,港股市场和美股市场的指数,基金,股票等标的,A 股的债券和可转债,所有 investing.com, bloomberg.com, spindices.com 上的标的数据,人民币中间价数据,场内基金份额数据。

  13. 获取实时的各地市场股票,基金数据,包括计价货币和实时盘外价格。

  14. 基于指数权重和企业财报,得到的最靠谱的 A 股各指数历史估值情况和实时估值位置总结。

  15. 获取宏观经济数据和计算相应指数的总净资产与总盈利。

  16. QDII 基金的 T-1 日净值预测和 T 日净值实时预测的基础设施。

  17. 获取雪球和英为支持标的的,不同频率的近期分时数据。和聚宽源的 A 股任意时间段的分时数据。

  18. 获取基金的股票和债券持仓数据,不止十大权重,可以覆盖全部持仓。

  19. 获取整个基金组合的底层股票持仓细节统计和不同类型的仓位,用于更底层的审视基金组合或追踪机构持仓。

  20. 可转债全自动定价与估值,自动分析可转债内在价值。

具体示例

这里将列举一些通过 Jupyter Notebook,使用 xalpha 进行研究管理和可视化的具体例子。请按照下边的连接浏览。

基本用法

  • 基金和指数信息的获取与分析: 示例

  • 多只基金和指数的数据比较与综合: 示例

  • 单只基金交易的分析: 示例

  • 多只基金投资组合的管理分析: 示例

  • 基金交易策略生成与回测: 示例

  • 2020 新用法新范式整理 (推荐): 示例

  • 基金投资模拟回测简明教程(以一揽子主动基组合回测为例):示例

研究案例

  • 基金A类C类份额对比: 示例

  • 基金指数增强效果研究: 示例

  • 定投策略的研究: 示例

  • ETF拯救世界投资计划的分析与可视化: 示例

  • 石油相关基金的分析和研究: 示例

  • QDII 基金T-1日净值预估研究 (deprecated): 示例

  • 和基金净值预测与折溢价套利相关的独立项目 LOF-BOT

  • 直接基于 xalpha 的关于场内基金折溢价的最佳实践 示例

  • 可转债价格估计的研究和比较(xalpha 可转债价格计算器教学) 示例

高级用法

数据缓存

xalpha 有两部分可以提供数据缓存和本地化。

基金交易部分数据

第一部分是本地化与增量更新 info 系列的对象,比如 fundinfo, indexinfo, mfundinfo 等,这样就不需要每次再去爬取处理以前的净值,费率等等。 其本地化的不只是净值数据,也包括基金名称,基金费率等元信息。

其使用方法是,直接将 fetch=True (首先尝试从本地读取数据), save=True (更新的数据存回本地), form="csv"/"sql" (本地后端是 csv 文件还是 sql 数据库) 和 path="path"/engine (对应 csv 的本地存储路径或对应 sql 的 SQLAlchemy.engine 类. 作为参数传入 fundinfo 等。 如果是基金组合,也可以直接将这些参数传入 mulmulfix 类。 格式为 sql 时, path 示例:

import xalpha as xa
from sqlalchemy import create_engine
engine = create_engine('mysql://root:password@127.0.0.1/database?charset=utf8')
io = {"save": True, "fetch": True, "format": "sql", "path": engine}
xa.fundinfo("510018", **io)

get_daily 数据透明缓存

第二部分本地化和缓存是专门针对 get_daily 界面的,用于存储对应的日期-价格表。这一部分的缓存和本地化更加透明。不需要任何设置,get_daily 就自带内存缓存, 不会去爬取重复数据。如果想要把数据本地化存储,只需要 xa.set_backend(backend=, path=, prefix=, precached=) 即可。

其中 backend 同样可以是 csv 和 sql,也可以是默认的 memory。 path 与第一部分相同为 csv 存储的文件夹或 sql 的 engine 对象。prefix 是每个表单会添加的前缀,否则默认是用 code 做键值。 precached 可以不设,若设置为 %Y%m%d 的时间字符串格式,则代表第一次爬取就”预热”从 precached 到昨日的数据缓存。 注意到即使选取了数据库或文件作为后端,内存作为二级缓存依旧发挥作用,只要数据不改变,仍会直接读取内存数据,因此提升读写数据速度。

如果担忧内存中数据被”污染”,可以通过 xa.universal.check_cache(code, start, end) 来校验对应数据的准确性。也可用 xa.universal.reset_cache() 来清空现有的内存数据缓存。

最后为了可以在运行时动态改变 xalpha 函数的缓存行为,也即任何时刻 xa.set_backend 都可以生效,xalpha 强烈推荐所有函数,都以 xa.meth 的形式使用, 强烈不建议 from xalpha import meth 这种导入方式。

Note

若不设定第一部分基金交易的缓存,则 xa.set_backend() 的设定会默认决定第一部分基金元数据的缓存位置,一旦后端是 csv 或 sql,基金信息类的缓存将默认打开, 默认 fetch=True, svae=True. 因此 xa.set_backend() 事实上成为了设置 xalpha 数据缓存的统一接口。

对于部分数据,由于程序升级的不兼容或者缓存数据损坏造成希望重新获取而刷新掉缓存的话,可以在 get_daily 添加 refresh 选项,也即 xa.get_daily(code, refresh=True), 这会重新刷新关于 code 的本地缓存。

而对于另一些数据,我们不希望去更新,只希望使用缓存的数据,即使其日期不全(可能是由于节假日造成的错觉),这时可以添加 fetchonly 选项,也即 xa.get_daily(code, fetchonly=True).

get_daily 不指定起止时间的时候,默认采用 end=today, prev=365, 这两个的行为也可以通过 defaultend=defaultprev=xa.set_backend 设置。其中 defaultend 可以是日期字符串或日期对象或返回日期对象的函数。

数据本地化

数据缓存部分提供的方法已经足够满足绝大多数数据本地化的要求,可以透明地将数据落地到本地文件系统或关系型数据库。

如果需要更复杂的本地化需求,考虑到 xalpha 中所有数据都是以 pandas.DataFrame 格式存在,那么只需参考 DataFrame 的 IO 功能即可 IOTools 。 数据可以一键落地到 csv, excel, hdf5, json,html, 数据库表格等格式。

数据可视化

xalpha 提供两部分的可视化。对于基金管理部分,相关类所有以 v_ 开始的方法,均是 pyecharts 支持的可视化封装。 对于 toolbox 部分,v() 方法,是 matplotlib 支持的可视化。

此外,考虑到所有数据均是 DataFrame 格式,用户也可以对任何数据,轻松可视化,参考代码 df.plot(x="date", y=["open", "close"]). 更多关于对 DataFrame 的可视化,请参考 Pandas 文档, Visualization

xalpha 也直接 hack 了些 dataframe 的方法用来链式调用提供更丰富的可视化。最典型的,对于有 date,open,close,high,low 和 volume(可选)列的 dataframe, 可以直接 df.v_kline() 绘制出标准的 web 级上 K 线图下交易量的行情图。

数据提供商

xalpha 的数据来自天天基金,英为财情,雪球,彭博,标普,新浪财经,网易财经,雅虎财经等多个源头,xalpha 的哲学是尽量利用免费的透明数据源。 但有些数据还是会依赖需要鉴权的数据 API,这些被抽象成数据提供商。

比如 xalpha 的历史估值系统,依赖聚宽的数据,那么就有两种方案。

本地调用聚宽数据

第一种是本地 pip install jqdatasdk 并且申请聚宽的本地数据试用权限(免费), 之后通过 xa.provider.set_jq_data(user, password) 即可。

如果希望不需要每次使用 xalpha 都重新鉴权,也可以在 set_jq_data 添加 persistent=True 的选项,这样聚宽账户密码会简单编码后存在本地(无加密保护,请自行衡量安全性),以后每次 import xalpha 聚宽的数据源都会自动激活。

云端使用 xalpha

第二种方案不需要聚宽本地数据,而是直接在聚宽云平台的研究环境来使用 xalpha,此时的初始化配置为:

>>> !pip3 install xalpha --user
>>> import sys
>>> sys.path.insert(0, "/home/jquser/.local/lib/python3.6/site-packages")
>>> import xalpha as xa
>>> xa.provider.set_jq_data(debug=True)

主要模块的关系和逻辑

xalpha.cons 模块主要提供一些基础的函数和常量, xalpha.remain 则专门提供了一些处理分时持仓表 remtable 的函数。

xalpha.record 用于统一的处理 status 记账单,同时自身实例化可以读取 csv 文件的原有账单。且可被其他具有 status 属性的类继承,作为广泛的 status 账单处理的工具箱。 而 xalpha.policy 则用于制定虚拟的 status 记账单,来进行不同策略投资的回测,其也继承了 xalpha.record.record 中一般的记账单处理函数。

xalpha.indicator 被具有净值表或可生成净值表的类继承,提供了一揽子净值量化分析和可视化的工具箱。其被 xalpha.info.basicinfoxalpha.multiple.mulfix 继承和使用,后者需要通过设定 benchmark 的函数来初始化净值表。

xalpha.realtime 则是围绕基金的实时净值获取,策略集成和监视提醒为主的模块,可以用于每日按照多样的策略自动提醒投资情况。

其他四个系统的核心模块,所具有的核心数据表(都是 pandas.DataFrame 的形式),以及相互之间的关系,如下图所示。

https://user-images.githubusercontent.com/35157286/43990032-fd6f8a3a-9d87-11e8-95c4-206b13734b40.png

在新版本的 xalpha 中提供了更丰富的数据抓取系统:

xalpha.universal 模块维护了不同的数据抓取,并对外提供统一的接口 xalpha.universal.get_daily()xalpha.universal.get_rt()

xalpha.provider 模块维护了需要注册的数据提供方的信息及验权接口。

xalpha.toolbox 模块维护了面向对象,封装数据的一些工具箱。

以下对象内部封装的数据结构均基于 pandas.DataFrame

  • 记账单 status

  • 净值表 price

  • 现金流量表 cftable

  • 仓位分时表 remtable

记账单格式说明

如果用户想一览自己的交易分析,那么记账单总是用户需要提供的,一般可以通过读取 csv 的方式导入 xalpha, 也即 xa.record(path) 即可,对于场内交易的账单,则需要 xa.irecord(path)。 记账单的具体合法格式可以参考 xalpha.record.record() 的说明。

场外账单格式

首先记账单分为场外和场内,需要提供单独的记账单。场外记账单无需提供每次申赎时的净值,因为这些值被时间唯一确定,可以智能抓取。 那么场外基金的账单,只需要时间,基金代码和数字三要素。对于数字,正数时代表申购金额,负数代表赎回份额,这与基金的申赎逻辑相符。 场外账单的默认格式是 matrix,也即每列的列头是一个不同的六位基金代码,每行的行头是一个独立的日期 (格式 20200202),对于对应日期和基金有交易的,则在相应单元格记录数额即可 (请注意下午三点之后的申赎应算作下个交易日)。 其他单元格可为空即可。 通常可以 Excel 等记录,导出成 csv 格式即可。这一格式账单的例子可以参考 tests/demo.csv, 和 tests/demo2.csv.

场外账单的一些进阶说明:

1. 在基金代码的下一行可以额外增加 property,用于控制基金的默认交易行为。每个代码可以填写一个0到7的数字,空默认为0。其对应的交易行为是: 基金份额确认是四舍五入0 还是舍弃尾数 1, 基金是默认现金分红 0 还是分红再投 2, 基金是赎回数目对应份额 0 还是金额 4 (只支持货币基金), property 数字为三者之和。

2. 关于交易数字的一些特别约定,交易数字小数点一位之后的非零位有特别约定,不代表交易的部分。 小数点后第二位如果是5,且当日恰好为对应基金分红日,标志着选择了分红再投入的方式,否则默认分红拿现金。(该默认行为 property 含 2 时可翻转)比如 100.05 的意思是当日分红再投入且又申购了 500 元。 对于赎回的负数,如果是一个绝对值小于 0.005 的数,标记了赎回的份额占当时总份额的比例而非赎回的份额数目, 其中-0.005对应全部赎回,线性类推。eg. -0.001对应赎回20%。

Note

如果不适应这种矩阵型的记账单,场外记账单也可以采用流水式的,也即每行记录一笔交易,列头分别是 fund,date,和 trade。这一格式的例子可以参考 tests/demo1.csv。 此时的日期格式是 2020/2/2. 这种形式的账单,通过 xa.record(path, format="list") 来读取,不过这种账单不支持在账单层面设置基金的交易行为参数 property, 但该参数仍可在基金投资组合 xa.mul(status=xa.record(path, formath="list"), property=Dict[fundcode, property_number]) 的时候传入。对于这种格式的场外账单, 不保证之后会维持和矩阵型场外账单同样的功能,因此请优先考虑矩阵型的场外账单格式。

场内账单格式

场内账单则统一采用流水形式,每一笔需要记录交易净值和交易份额,此时由于买卖都是份额,因此数字全部代表份额,正买负卖,若有分红折算等,需自己手动维护,额外添加交易记录实现。 场内账单的例子请参考 tests/demo3.csv. 其列头分别是 date,code,value,share,fee。date 格式为20200202。code 对应场内代码,开头需包含 SH 或 SZ。value 是成交的净值单价。 share 代表成交的份数。fee 代表手续费,也可以不计,则默认为0,建议记录以得到交易盈利的更好全景。

场内账单的读入使用 ist=xa.irecord(path). 其既可以传入专门的场内投资组合类 xa.imul(status=ist), 也可以和场内记账单一起传入投资组合类 xa.mul(status=st, istatus=ist) 进行场内外投资结果的汇总。

场内账单的分红派息拆合送股的处理。对于分红或派息,直接计 share 栏为 0,value 栏为全部返还的现金,正数。 对于拆合送股,造成的份额改变(无任何现金流变化),直接计 value 栏为 0,share 栏表示总的份额的增量,正数为增加,负数为减少。 对于申购新债等情况,可能统计时还有代码未上市,此时处理可能造成错误,需要在代码前加``#``表示省略该行记录,不予处理。待新股上市后,去掉代码前井号即可。

Note

场内账单处理逻辑为了保持和场外一致,也只处理到截止昨天的交易,因此可能出现和现时实盘不符的情形。

QDII 净值预测

净值预测接口请参考 xalpha.toolbox.QDIIPredict.

基本使用说明,在提供了 holdings.py 的前提下(置于 xalpha 源代码文件夹,开源 xalpha 暂时默认不提供该文件,则预测需手动提供相应基金的持仓信息和基金交易市场,计价货币,休市时间,期货现货对应等元信息)

import xalpha as xa
xa.set_backend(backend="csv", path="./data") # 设置合适的本地化方案,也可不设,则数据仅会缓存在内存中
nfyy = xa.QDIIPredict("SH501018", positions=True) # 初始化南方原油的净值预测,采取浮动仓位预测
print(nfyy.t1_type) # 未计算
print(nfyy.get_t1()) # 返回上个交易日的净值预测
print(nfyy.t1_type) # 已计算
print(nfyy.get_position()) # 返回基于前天和更早净值数据判断而得出的昨日仓位估计
print(nfyy.get_t0()) # 实时净值预测
print(nfyy.get_t1_rate()) # 实时市价相对昨日净值预测的溢价率
print(nfyy.get_t0_rate()) # 实时市价相对实时估值的溢价率
nfyy.benchmark_test("2020-01-01", "2020-03-01") # 回测一段时间内的预测效果
nfyy.analyse() # 打印出回测的定量分析

导入外部 holdings.py 数据文件

可将 holdings.py 文件与运行脚本置于同一文件夹,或任何在 PYTHONPATH 的文件夹

import holdings  # 导入外部的 holdings.py
import xalpha as xa
xa.set_holdings(holdings) # 设置 xalpha 使用该数据文件
# 之后的操作与之前相同

日志系统

xalpha 引入了 python logger 的日志系统,尤其是用来记录网络链接和爬虫等详细的 debug 信息。

Jupyter 中的使用

import xalpha as xa
import logging
logger = logging.getLogger('xalpha')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
logger.addHandler(ch)

以上配置,日志将打印在 jupyter notebook 前端

脚本程序中使用

import xalpha as xa
import logging
logger = logging.getLogger('xalpha')
logger.setLevel(logging.DEBUG)
fhandler = logging.FileHandler(filename='debug.log', mode='a')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fhandler.setFormatter(formatter)
logger.addHandler(fhandler)

以上配置,日志将输入文件 debug.log

get 方法钩子

有时候可能用户自己维护了一部分数据或数据库,也可能用户有其他更好的数据 API 可用。为了将这些无缝的融合进 xalpha,我们引入了 handler 来处理。

举例来说,我的数据库里有 A 股股票的日线数据,而且我觉得这个数据质量比网上爬虫要好,那么我希望 xa.get_daily("SH600000") 的时候, xalpha 不要去雪球爬取数据,而是直接从我的数据库里来拿,这样又快又稳。这样所有基于 xa.get_daily 构建的 xalpha 的工具箱就也可以继续无缝的使用了。

为了实现这点,可以按如下示例:

import xalpha as xa

def fetch_from_database(code, start, end, **kws): # **kws 是声明钩子函数所必须的,即使你用不到
    if code.startswith("SH"): # 请只过滤符合要求的代码,其他代码仍然用 get_daily 方法
        # 这里定义连接数据库和拿数据
        return df # 最终返回符合约定的 pd.DataFrame, 比如必须有 date 列,type 是 pd.Timestamp
    else:
        return None # 对于不满足的代码,返回 None 即可,程序将自动按照原来的 get_daily 处理

xa.set_handler(method="daily", f=fetch_from_database) # 设定好钩子
xa.get_daily("SH600000") # 此时程序将从数据库获取日线数据

同样的方法,也可以应用到 get_rtget_bar, 对应的 method=”rt”, “bar”.

应用举例,有时候你可能不希望抓取实时数据那么实时,每分钟更新一次实时数据就好,那你可以通过下面的方式实现 get_rt 的”迟滞化”。

import xalpha as xa

@xa.universal.lru_cache_time(ttl=60)
def cached_get_rt(code, **kws):
    return xa.get_rt(code, handler=False)

xa.set_handler(method="rt", f=cached_get_rt)

set 方法总结

xalpha 激进地利用了 python 的 reflection 机制,很多设定可以运行时动态改变,这些往往被抽象成一些 set_ 接口。

爬虫与反爬虫

xalpha 本身不维护任何数据,所有数据都来自从不同数据源的即时爬虫。但由于 xalpha 设计巧妙的本地缓存策略,大部分数据都不需要重复爬取,使用和分析因此不需要过多的时间延迟。 xalpha 维护了极其丰富的数据源,横跨十几个不同的网站,其默认设置可以顺利的爬取这些网站的数据,不需要额外的配置。但部分数据源如彭博,可能需要 xa.set_proxy 设定代理才能链接。

xalpha 设计的尽量对数据源网站友好,通过丰富而合理的本地和内存缓存策略,可以极大的减少网络连接和下载数目,从而提升反应速度和减少对数据源服务器的冲击。 xalpha 也不建议被用作高频交易的组件,不提倡任何高强度爬取数据的行为。

如果对同一数据源链接强度过大,很有可能被限制 ip 从而无法获取数据。此时唯一的 workaround 就是设置代理 xa.set_proxy(),从而改变 ip。 根据个人经验,最容易封禁 ip 从而无法爬取的数据源包括人民币中间价官方网站,彭博网站。

set_proxy 传入字符串可以是 http 或 socks5 代理地址,注意, socks5:// 格式的输入,不会改变使用本地的 DNS,如果想 DNS 查询也通过代理服务器的话,需使用 socks5h:// , 这一约定与 curl 和 requests 同步。

开发者文档

欢迎直接在 GitHub 提交 issue 或发起 PR。

工作流

git部分:fork 仓库,clone 到本地修改,push 回 forked 仓库,提交 PR 到 master 分支。关于中间涉及的 git 操作,如在本地保持和原始库更新同步等,这里不再赘述。

测试部分:测试基于 pytest, cd tests && pytest 即可,请注意测试时 pwd 需为 tests 文件夹。单独测试可用 pytest test_file.py::test_func

linter 部分:使用 black 及其默认设置,提交代码前请运行 black .

文档部分:使用 sphnix 工作流,本地预览可以 cd doc && make html, 生成的网页在 doc/build/html 中。

如果添加新功能请注意添加对应的测试案例到 tests 中,新函数请保证必要的 docstring,如有必要,请相应修改 CHANGELOG.md 的内容。 也可添加文档介绍新功能到 doc/source 中或新的案例分析 jupyter notebook 到 doc/sample 中。

欢迎的贡献方向

任何 PR 和讨论都是欢迎的,但以下方向可能在优先级上靠前。

  1. 找到并修正现存的明显的 bug。

  2. 代码,文档,repo 任何位置的中英文 typo。

  3. 可以测试 corner case 或增加代码覆盖的更多新测试案例。

  4. xa.cons.droplist 元素添加,也即找到更多份额舍掉零头而非四舍五入的基金。

  5. 完善已有函数的 docstring,完善和增加文档及案例。

  6. 增加有趣的基于 xalpha 的案例分析,作为独立的 jupyter notebook。

  7. 保证对外接口不变情况下的,冗余代码小幅重构。

  8. 依赖库跨版本更新造成的 broken API 的发现和修复。

  9. xa.universal.get_daily 增加更多的数据源爬虫后端。

  10. 将更多聚宽的数据,合理的设计和封装到 xa.universal.get_daily

  11. xa.indicator.indicator 增加更多的技术指标计算。

  12. pyecharts 可视化部分的效果优化和选项调整。

对于更激进的新功能大幅增加或代码重构,需鉴权数据提供方的添加,API调整等,建议先开 issue 进行讨论,防止重复或无效工作。

常见问题

  • 运行 pytest 时,如果报错 AttributeError: ‘Function’ object has no attribute ‘get_marker’,可以参考 链接,对pytest-cov做个升级.

xalpha API

xalpha package

xalpha.cons module

basic constants and utility functions

xalpha.cons._date_check(dtobj, check=False)[source]
xalpha.cons._float(n)[source]
xalpha.cons.convert_date(date)[source]

convert date into datetime object

Parameters

date – string of form ‘2017-01-01’ or datetime object

Returns

corresponding datetime object

xalpha.cons.last_onday(dtobj)[source]
xalpha.cons.myround(num, label=1)[source]

correct implementation of round with round half up, round to 2 decimals

Parameters
  • num – the floating number, to be rounded

  • label – integer 1 or 2, 1 for round half up while 2 for always round down

Returns

the float number after rounding, with two decimals

xalpha.cons.next_onday(dtobj)[source]
xalpha.cons.reconnect(tries=5, timeout=12)[source]
xalpha.cons.rget_json(*args, **kws)[source]
xalpha.cons.rpost_json(*args, **kws)[source]
xalpha.cons.scale_dict(d, scale=1, ulimit=100, dlimit=50, aim=None)[source]
xalpha.cons.today_obj()[source]

today obj in beijing timezone with no tzinfo

Returns

datetime.datetime

xalpha.cons.xirr(cashflows, guess=0.1)[source]

calculate the Internal Rate of Return of a series of cashflows at irregular intervals.

Parameters
  • cashflows – a list, in which each element is a tuple of the form (date, amount), where date is a datetime object and amount is an integer or floating number. Cash outflows (investments) are represented with negative amounts, and cash inflows (returns) are positive amounts.

  • guess – floating number, a guess at the xirr rate solution to be used as a starting point for the numerical solution

Returns

the IRR as a single floating number

xalpha.cons.xnpv(rate, cashflows)[source]

give the current cash value based on future cashflows

Parameters
  • rate – float, the preset year rate

  • cashflows – a list, in which each element is a tuple of the form (date, amount), where date is a datetime object and amount is an integer or floating number. Cash outflows (investments) are represented with negative amounts, and cash inflows (returns) are positive amounts.

Returns

a single float value which is the NPV of the given cash flows

xalpha.cons.yesterday()
xalpha.cons.yesterdaydash()
xalpha.cons.yesterdayobj()

xalpha.evaluate module

modules for evaluation and comparison on multiple object with price dataframe

class xalpha.evaluate.evaluate(*fundobjs, start=None)[source]

Bases: object

多个 info 对象的比较类,比较的对象只要实现了 price 属性,该属性为具有 date 和 netvalue 列的 pandas.DataFrame 即可。 更进一步,也可讲做过 bcmkset 的 xalpha.multiple.mulfix 类作为输入,只不过此时需要提前额外指定以下该对象的 name 和 code 两个属性。 由于该类需要各基金净值表可以严格对齐,因此需要对节假日和国内不同的 QDII 基金进行补齐,由于第一个基金为基准,因此第一个输入不建议是 QDII 基金

Parameters
  • fundobjs – info object,或者如前所述一切具有 price 表的对象

  • start – date string or object, 比较的起始时间,默认使用所有 price 表中最近的起始时间。 但需要注意,由于拉取的基金净值表,往往在开始几天缺失净值数据,即使使用默认时间也可能无法对齐所有净值数据。 因此建议手动设置起始时间到最近的起始时间一周后左右。

__init__(*fundobjs, start=None)[source]

Initialize self. See help(type(self)) for accurate signature.

correlation_table(end=datetime.datetime(2020, 6, 2, 13, 39, 4, 50828))[source]

give the correlation coefficient amongst referenced funds and indexes

Parameters

end – string or object of date, the end date of the line

Returns

pandas DataFrame, with correlation coefficient as elements

v_correlation(end=datetime.datetime(2020, 6, 2, 13, 39, 4, 50836), vopts=None)[source]

各基金净值的相关程度热力图可视化

Parameters

end – string or object of date, the end date of the line

Returns

pyecharts.charts.Heatmap.render_notebook object

v_netvalue(end=datetime.datetime(2020, 6, 2, 13, 39, 4, 50811), vopts=None)[source]

起点对齐归一的,各参考基金或指数的净值比较可视化

Parameters
  • end – string or object of date, the end date of the line

  • vkwds – pyechart line.add() options

  • vopts – dict, options for pyecharts instead of builtin settings

Returns

pyecharts.charts.Line.render_notebook()

xalpha.indicator module

module for implementation of indicator class, which is designed as MinIn for systems with netvalues

xalpha.indicator._upcount(ls)[source]

count the ratio of upmove days by given a list

class xalpha.indicator.indicator[source]

Bases: object

MixIn class provide quant indicator tool box which is desinged as interface for mulfix class as well as info class, who are both treated as a single fund with price table of net value. Most of the quant indexes, their name conventions, definitions and calculations are from joinquant. Make sure first run obj.bcmkset() before you want to use functions in this class.

_pricegenerate(name)[source]

generate price table for mulfix class, the cinfo class has this attr by default

algorithm_volatility(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 48446))[source]
alpha(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 48361))[source]
static annualized_returns(price, start, date=datetime.datetime(2020, 6, 2, 13, 39, 4, 48334))[source]
Parameters
  • price – price table of info().price

  • start – datetime obj for starting date of calculation

  • date – datetime obj for ending date of calculation

Returns

float, annualized returns of the price table

bbi(col='netvalue')[source]

多空指标 give bull and bear line in column BBI in price table

Parameters

col – string, column name in dataframe you want to calculate

bcmkset(infoobj, start=None, riskfree=0.0371724, name='基金组合')[source]

Once you want to utilize the indicator tool box for analysis, first run bcmkset function to set the benchmark, otherwise most of the functions would raise error.

Parameters
  • infoobj – info obj, whose netvalue are used as benchmark

  • start – datetime obj, indicating the starting date of all analysis. Note if use default start, there may be problems for some fundinfo obj, as lots of funds lack netvalues of several days from our API, resulting unequal length between benchmarks and fund net values.

  • riskfree – float, annual rate in the unit of 100%, strongly suggest make this value consistent with the interest parameter when instanciate cashinfo() class

benchmark_annualized_returns(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 48348))[source]
benchmark_volatility(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 48453))[source]
beta(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 48355))[source]
bias(window=10, col='netvalue')[source]

乖离率 give the bias as BIAS column in price table

Parameters
  • window – int, MA_window

  • col – string, column name in dataframe you want to calculate

boll(window=10, deviation=2, col='netvalue')[source]

布林线上下轨计算 give the bolling upper and lower band in the price table, the middle line is just ma line

Parameters
  • window – int, the date window for ma and md

  • deviation – int or float, how many times deviation of sigma

  • col – string, column name in dataframe you want to calculate

comparison(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 48304))[source]
Returns

tuple of two pd.Dataframe, the first is for aim and the second if for the benchmark index all netvalues are normalized and set equal 1.00 on the self.start date

correlation_coefficient(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 48366))[source]
correlation coefficient between aim and benchmark values,

可以很好地衡量指数基金的追踪效果

Returns

float between -1 and 1

dma(fast_window=10, slow_window=50, ama_window=10, col='netvalue')[source]

平行线差指标 give different of moving average as columns DMA and AMA in price table

Parameters
  • fast_window – int

  • slow_window – int

  • ama_window – int

  • col – string, column name in dataframe you want to calculate

ema(window=5, col='netvalue')[source]

指数平均数指标 give the exponential moving average as a new column ‘EMA’ in the price table, return None

Parameters
  • window – the span of date, where the decay factor alpha=2/(1+window)

  • col – string, column name in dataframe you want to calculate

information_ratio(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 48464))[source]
kdj(rsv_window=9, k_window=3, d_window=3, col='netvalue')[source]

KDJ 随机指标 由于该模块不涉及日内高低价的信息,因此区间最高价最低价都由极值收盘价代替,因此和其他软件计算的 kdj 指标可能存在出入。 give k,d,j indexes as three columns KDJ_K/D/J in price table

Parameters
  • rsv_window – int

  • k_window – int

  • d_window – int

  • col – string, column name in dataframe you want to calculate

ma(window=5, col='netvalue')[source]

移动平均线指标 give the moving average as a new column ‘MA’ in the price table, return None

Parameters
  • window – the date window of the MA calculation

  • col – string, column name in dataframe you want to calculate

macd(fast_window=12, slow_window=26, signal_window=9, col='netvalue')[source]

指数平滑异同移动平均线 give the MACD index as three new columns ‘MACD_DIFF/DEM/OSC’ in the price table, return None

Parameters
  • fast_window – int,

  • slow_window – int,

  • signal_window – int, the ema window of the signal line

  • col – string, column name in dataframe you want to calculate

max_drawdown(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 48470))[source]

回测时间段的最大回撤

Parameters

date – date obj or string

Returns

three elements tuple, the first two are the date obj of start and end of the time window, the third one is the drawdown amplitude in unit 1.

md(window=5, col='netvalue')[source]

移动标准差指标 give the moving standard deviation as a new column ‘MD’ in the price table, return None

Parameters
  • window – the date window of the MD calculation

  • col – string, column name in dataframe you want to calculate

mtm(window=10, col='netvalue')[source]

动量指标,并未附加动量的平均线指标,如需计算动量平均线指标,使用ma或emca函数,col参数选择MTM列即可 give the MTM as a new column ‘MTM’ in the price table, return None

Parameters
  • window – int, the difference between price now and window days ago

  • col – string, column name in dataframe you want to calculate

pct_chg(freq='Y', benchmark=True)[source]

年度,月,周涨幅统计

Parameters

freq – str, default Y, could be M or W or anything pd.date_range accepts

Returns

pd.DataFrame with columns date and pct_chg

psy(count_window=12, ma_window=6, col='netvalue')[source]

心理线指标(衡量过去 count_window 天涨幅天数) give psy and psyma as column PSY and PSYMA in price table

Parameters
  • count_window – int

  • ma_window – int

  • col – string, column name in dataframe you want to calculate

static ratedaily(price, date=datetime.datetime(2020, 6, 2, 13, 39, 4, 48372))[source]
roc(window=10, col='netvalue')[source]

变动率指标 give the ROC as a new column ‘ROC’ in the price table, return None, the ROC is in the unit of 1 instead of 1%

Parameters
  • window – int, the change rate between price now and window days ago

  • col – string, column name in dataframe you want to calculate

rsi(window=14, col='netvalue')[source]

相对强弱指标 give the rsi as RSI column in price table

Parameters
  • window – int, MA_window

  • col – string, column name in dataframe you want to calculate

sharpe(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 48459))[source]
total_annualized_returns(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 48341))[source]
total_return(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 48326))[source]
trix(window=10, ma_window=10, col='netvalue')[source]

三重指数平滑平均线 give the trix index in column TRIX, TRMA

Parameters
  • window – int

  • col – string, column name in dataframe you want to calculate

v_netvalue(end=datetime.datetime(2020, 6, 2, 13, 39, 4, 48481), benchmark=True, rendered=True, vopts=None)[source]

visulaization on netvalue curve

Parameters
  • end – dateobject for indicating the end date in the figure, default to yesterday

  • benchmark – bool, whether include benchmark’s netvalue curve, default true

  • vopts – dict, options for pyecharts instead of builtin settings

v_techindex(end=datetime.datetime(2020, 6, 2, 13, 39, 4, 48487), col=None, rendered=True, vopts=None)[source]

visualization on netvalue curve and specified indicators

Parameters
  • end – date string or obj, the end date of the figure

  • col – list, list of strings for price col name, eg.[‘MA5’,’BBI’] remember generate these indicators before the visualization, these cols don’t automatically generate for visualization

  • vopts – dict, options for pyecharts instead of builtin settings

static volatility(price, date=datetime.datetime(2020, 6, 2, 13, 39, 4, 48416))[source]
wnr(window=14, col='netvalue')[source]

威廉指标,这里取超卖结果接近0的约定(wnr*-1),事实上就是 rsv, 同样的区间极值价用极值收盘价替代 give williams %R in WNR column in price table

Parameters
  • window – int

  • col – string, column name in dataframe you want to calculate

xalpha.indicator.plot_kline(df, rendered=True, col='')[source]

针对 dataframe 直接画出标准看盘软件的上k线图下成交量图的形式

Parameters
  • df

  • rendered

  • col

Returns

xalpha.info module

modules of info class, including cashinfo, indexinfo and fundinfo class

xalpha.info.CashInfo

alias of xalpha.info.cashinfo

xalpha.info.FundInfo

alias of xalpha.info.fundinfo

class xalpha.info.FundReport(code)[source]

Bases: object

提供查看各种基金报告的接口

__init__(code)[source]

Initialize self. See help(type(self)) for accurate signature.

analyse_report(no=0)[source]
get_report(no=0, id_=None)[source]
Parameters
  • no – int。在type_=3 中的第no个报告。

  • id – id 可由 show_report_list() 中条目的对应 ID 得到

Returns

show_report_list(type_=3)[source]
Parameters

type – int。第0栏,第1栏,每栏的含义,请参照天天基金基金报告的页面。

Returns

xalpha.info.IndexInfo

alias of xalpha.info.indexinfo

xalpha.info.MFundInfo

alias of xalpha.info.mfundinfo

xalpha.info._nfloat(string)[source]

deal with comment column in fundinfo price table, positive value for fenhong and negative value for chaifen, keep other unrocognized pattern as original string

Parameters

string – string of input from original data

Returns

make fenhong and songpei as float number

xalpha.info._shengoucal(sg, sgf, value, label)[source]
Infer the share of buying fund by money input, the rate of fee in the unit of %,

and netvalue of fund

Parameters
  • sg – positive float, 申购金额

  • sgf – positive float, 申购费,以%为单位,如 0.15 表示 0.15%

  • value – positive float, 对应产品的单位净值

  • label – integer, 1 代表份额正常进行四舍五入, 2 代表份额直接舍去小数点两位之后。金额部分都是四舍五入

Returns

tuple of two positive float, 净申购金额和申购份额

class xalpha.info.basicinfo(code, fetch=False, save=False, path='', form='csv', round_label=0, dividend_label=0, value_label=0)[source]

Bases: xalpha.indicator.indicator

Base class for info of fund, index or even cash, which cannot be directly instantiate, the basic implementation consider redemption fee as zero when shuhui() function is implemented

Parameters
  • code – string of code for specific product

  • fetch – boolean, when open the fetch option, the class will try fetching from local files first in the init

  • save – boolean, when open the save option, automatically save the class to files

  • path – string, the file path prefix of IO. Or in sql case, path is the engine from sqlalchemy.

  • form – string, the format of IO, options including: ‘csv’,’sql’

  • round_label – int, default 0 or 1, label to the different round scheme of shares, reserved for fundinfo class. 1 代表全舍而非四舍五入。

  • dividend_label – int, default 0 or 1. 0 代表默认现金分红,1代表红利再投。两者均可通过记账单上的 0.05 来改变单次的默认。

  • value_label – int, default 0 or 1. 1 代表记账单上的赎回数目是按金额而非份额的,只能完美支持货币基金。其他净值型基金本质上无法精确到分支持这一选项,因此不开放支持。

__init__(code, fetch=False, save=False, path='', form='csv', round_label=0, dividend_label=0, value_label=0)[source]

Initialize self. See help(type(self)) for accurate signature.

_basic_init()[source]

set self. name rate and price (dataframe) as well as other necessary attr of info()

_save_csv_a(path, df)[source]
_save_sql_a(path, df)[source]
_shuhui_by_share(share, date, rem)[source]
fetch(path, form=None)[source]

fetch info from files

Parameters
  • path – string of the folder path prefix! end with / in csv case; engine from sqlalchemy.create_engine() in sql case.

  • form – string, option:’csv’ or ‘sql

info()[source]

print basic info on the class

save(path, form=None, option='r', delta=None)[source]

save info to files, this function is designed to redirect to more specific functions

Parameters
  • path – string of the folder path prefix! or engine obj from sqlalchemy

  • form – string, option:’csv’

  • option – string, r for replace and a for append output

  • delta – if option is a, you have to specify the delta which is the incremental part of price table

shengou(value, date)[source]

give the realdate deltacash deltashare tuple based on purchase date and purchase amount if the date is not a trade date, then the purchase would happen on the next trade day, if the date is in the furture, then the trade date is taken as yesterday.

Parameters
  • value – the money for purchase

  • date – string or object of date

Returns

three elements tuple, the first is the actual dateobj of commit the second is a negative float for cashin, the third is a positive float for share increase

shuhui(share, date, rem, value_label=None)[source]

give the cashout considering redemption rates as zero. if the date is not a trade date, then the purchase would happen on the next trade day, if the date is in the furture, then the trade date is taken as yesterday.

Parameters
  • share – float or int, number of shares to be sold. if value_label=1, its cash to be sold.

  • date – string or object of date

Returns

three elements tuple, the first is dateobj the second is a positive float for cashout, the third is a negative float for share decrease

update()[source]

对类的价格表进行增量更新,并进行增量存储,适合 fetch 打开的情形

Returns

the incremental part of price table or None if no incremental part exsits

class xalpha.info.cashinfo(interest=0.0001, start='2012-01-01', value_label=0)[source]

Bases: xalpha.info.basicinfo

A virtual class for remaining cash manage: behave like monetary fund

Parameters
  • interest – float, daily rate in the unit of 100%, note this is not a year return rate!

  • start – str of date or dateobj, the virtual starting date of the cash fund

  • value_label – int, default 0 or 1. If set to 1, 记账单数字按金额赎回。

__init__(interest=0.0001, start='2012-01-01', value_label=0)[source]

Initialize self. See help(type(self)) for accurate signature.

_basic_init()[source]

set self. name rate and price (dataframe) as well as other necessary attr of info()

class xalpha.info.fundinfo(code, round_label=0, dividend_label=0, fetch=False, save=False, path='', form='csv', priceonly=False)[source]

Bases: xalpha.info.basicinfo

class for specific fund with basic info and every day values 所获得的基金净值数据一般截止到昨日。但注意QDII基金的净值数据会截止的更早,因此部分时间默认昨日的函数可能出现问题, 处理QDII基金时,需要额外注意。

Parameters
  • code – str, 基金六位代码字符

  • round_label – integer 0 or 1, 取1表示基金申购时份额直接舍掉小数点两位之后。当基金处于 cons.droplist 名单中时, label 总会被自动设置为1。非名单内基金可以显式令 round_label=1.

  • dividend_label – int, default 0 or 1. 0 代表默认现金分红,1代表红利再投。两者均可通过记账单上的 0.05 来改变单次的默认。

  • fetch – boolean, when open the fetch option, the class will try fetching from local files first in the init

  • save – boolean, when open the save option, automatically save the class to files

  • path – string, the file path prefix of IO

  • form – string, the format of IO, options including: ‘csv’

__init__(code, round_label=0, dividend_label=0, fetch=False, save=False, path='', form='csv', priceonly=False)[source]

Initialize self. See help(type(self)) for accurate signature.

_basic_init()[source]

set self. name rate and price (dataframe) as well as other necessary attr of info()

_feepreprocess()[source]

Preprocess to add self.feeinfo and self.segment attr according to redemption fee info

_fetch_csv(path)[source]

fetch the information and pricetable from path+code.csv, not recommend to use manually, just set the fetch label to be true when init the object

Parameters

path – string of folder path

_fetch_sql(path)[source]

fetch the information and pricetable from sql, not recommend to use manually, just set the fetch label to be true when init the object

Parameters

path – engine object from sqlalchemy

static _piecewise(a)[source]

Transform the words list into a pure number segment list for redemption fee, eg. [[0,7],[7,365],[365]]

_save_csv(path)[source]

save the information and pricetable into path+code.csv, not recommend to use manually, just set the save label to be true when init the object

Parameters

path – string of folder path

_save_sql(path)[source]

save the information and pricetable into sql, not recommend to use manually, just set the save label to be true when init the object

Parameters

path – engine object from sqlalchemy

feedecision(day)[source]

give the redemption rate in percent unit based on the days difference between purchase and redemption

Parameters

day – integer, 赎回与申购时间之差的自然日数

Returns

float,赎回费率,以%为单位

get_bond_holdings(year='', season='', month='')[source]
get_holdings(year='', season='', month='', category='stock')[source]
get_stock_holdings(year='', season='', month='')[source]
info()[source]

print basic info on the class

shuhui(share, date, rem, value_label=None)[source]

give the cashout based on rem term considering redemption rates

Returns

three elements tuple, the first is dateobj the second is a positive float for cashout, the third is a negative float for share decrease

update()[source]

function to incrementally update the pricetable after fetch the old one

xalpha.info.get_fund_holdings[source]

获取基金详细的底层持仓信息

Parameters
  • code – str. 6 位基金代码

  • year – int. eg. 2019

  • season – int, 1,2,3,4

  • month – Optional[int]. 指定 season 即可,一般不需理会

  • category – str. stock 股票持仓, bond 债券持仓,天天基金无法自动处理海外基金持仓,暂未兼容 FOF 的国内基金持仓

Returns

pd.DataFrame or None. 没有对应持仓时返回 None。

class xalpha.info.indexinfo(code, value_label=0, fetch=False, save=False, path='', form='csv')[source]

Bases: xalpha.info.basicinfo

Get everyday close price of specific index. In self.price table, totvalue column is the real index while netvalue comlumn is normalized to 1 for the start date. In principle, this class can also be used to save stock prices but the price is without adjusted.

Parameters
  • code – string with seven digitals! note the code here has an extra digit at the beginning, 0 for sh and 1 for sz.

  • value_label – int, default 0 or 1. If set to 1, 记账单数字按金额赎回。

  • fetch – boolean, when open the fetch option, the class will try fetching from local files first in the init

  • save – boolean, when open the save option, automatically save the class to files

  • path – string, the file path prefix of IO

  • form – string, the format of IO, options including: ‘csv’

__init__(code, value_label=0, fetch=False, save=False, path='', form='csv')[source]

Initialize self. See help(type(self)) for accurate signature.

_basic_init()[source]

set self. name rate and price (dataframe) as well as other necessary attr of info()

_fetch_csv(path)[source]

fetch the information and pricetable from path+code.csv, not recommend to use manually, just set the fetch label to be true when init the object

Parameters

path – string of folder path

_fetch_sql(path)[source]

fetch the information and pricetable from sql, not recommend to use manually, just set the fetch label to be true when init the object

Parameters

path – engine object from sqlalchemy

_save_csv(path)[source]

save the information and pricetable into path+code.csv, not recommend to use manually, just set the save label to be true when init the object

Parameters

path – string of folder path

_save_sql(path)[source]

save the information and pricetable into sql, not recommend to use manually, just set the save label to be true when init the object

Parameters

path – engine object from sqlalchemy

update()[source]

对类的价格表进行增量更新,并进行增量存储,适合 fetch 打开的情形

Returns

the incremental part of price table or None if no incremental part exsits

class xalpha.info.mfundinfo(code, round_label=0, value_label=0, fetch=False, save=False, path='', form='csv')[source]

Bases: xalpha.info.basicinfo

真实的货币基金类,可以通过货币基金六位代码,来获取真实的货币基金业绩,并进行交易回测等

Parameters
  • code – string of six digitals, code of real monetnary fund

  • round_label – int, default 0 or 1, label to the different round scheme of shares, reserved for fundinfo class. 1 代表全舍而非四舍五入。

  • value_label – int, default 0 or 1. 1 代表记账单上的赎回数目是按金额而非份额的,只能完美支持货币基金。

  • fetch – boolean, when open the fetch option, the class will try fetching from local files first in the init

  • save – boolean, when open the save option, automatically save the class to files

  • path – string, the file path prefix of IO

  • form – string, the format of IO, options including: ‘csv’

__init__(code, round_label=0, value_label=0, fetch=False, save=False, path='', form='csv')[source]

Initialize self. See help(type(self)) for accurate signature.

_basic_init()[source]

set self. name rate and price (dataframe) as well as other necessary attr of info()

_fetch_csv(path)[source]

fetch the information and pricetable from path+code.csv, not recommend to use manually, just set the fetch label to be true when init the object

Parameters

path – string of folder path

_fetch_sql(path)[source]

fetch the information and pricetable from sql, not recommend to use manually, just set the fetch label to be true when init the object

Parameters

path – engine object from sqlalchemy

_save_csv(path)[source]

save the information and pricetable into path+code.csv, not recommend to use manually, just set the save label to be true when init the object

Parameters

path – string of folder path

_save_sql(path)[source]

save the information and pricetable into sql, not recommend to use manually, just set the save label to be true when init the object

Parameters

path – engine object from sqlalchemy

update()[source]

function to incrementally update the pricetable after fetch the old one

xalpha.multiple module

module for mul and mulfix class: fund combination management

xalpha.multiple.IMul

alias of xalpha.multiple.imul

xalpha.multiple.Mul

alias of xalpha.multiple.mul

xalpha.multiple.MulFix

alias of xalpha.multiple.mulfix

class xalpha.multiple.imul(*fundtradeobj, status=None, istatus=None)[source]

Bases: xalpha.multiple.mul

__init__(*fundtradeobj, status=None, istatus=None)[source]

对场内投资组合进行分析的类

Parameters
  • fundtradeobj – itrade objects.

  • status – 场内格式记账单,或 irecord 对象。

class xalpha.multiple.mul(*fundtradeobj, status=None, istatus=None, property=None, fetch=False, save=False, path='', form='csv')[source]

Bases: object

multiple fund positions manage class

Parameters
  • fundtradeobj – list of trade obj which you want to analyse together

  • status – the status table of trade, all code in this table would be considered. one must provide one of the two paramters, if both are offered, status will be overlooked 可以是场内记账单 DataFrame,也可以是 record 对象。

  • istatus – 场内交易账单,也可以是 irecord 对象。 若提供,则场内外交易联合统计展示。该选项只保证 combsummary 方法可正常使用,不保证 mul 类的其他方法可用。

  • property – Dict[fundcode, property_number]. property number 的解释: int. 1: 基金申购采取分位以后全舍而非四舍五入(这种基金是真实存在的==)。2:基金默认分红再投入(0 则是默认现金分红)。4:基金赎回按净值处理(暂时只支持货币基金,事实上无法精确支持按份额赎回的净值型基金)。将想要的性质数值相加即可,类似 *nix 上的 xwr 系统。

  • fetch – boolean, when open the fetch option, info class will try fetching from local files first in the init

  • save – boolean, when open the save option, info classes automatically save the class to files

  • path – string, the file path prefix of IO, or object or engine from sqlalchemy to connect sql database

  • form – string, the format of IO, options including: ‘csv’,’sql’

__init__(*fundtradeobj, status=None, istatus=None, property=None, fetch=False, save=False, path='', form='csv')[source]

Initialize self. See help(type(self)) for accurate signature.

_mergecftb()[source]

merge the different cftable for different funds into one table

combsummary(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 53473))[source]

brief report table of every funds and the combination investment

Parameters

date – string or obj of date, show info of the date given

Returns

empty dict if nothing is remaining that date dict of various data on the trade positions

evaluation(start=None)[source]

give the evaluation object to analysis funds properties themselves instead of trades

Returns

xalpha.evaluate.evaluate object, with referenced funds the same as funds we invested

get_portfolio(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 53510))[source]

获取基金组合底层资产大类配置的具体值

Parameters

date

Returns

Dict[str, float]. stock,bond,cash 对应总值的字典

get_stock_holdings(year=None, season=None, date=datetime.datetime(2020, 6, 2, 13, 39, 4, 53504), threhold=100)[source]

获取整个基金组合的底层股票持仓总和和细节,组合穿透

Parameters
  • year – 基于的基金季报年份

  • season – 基于的基金季报季度

  • date – 默认昨天

  • threhold – 默认100。小于100元的底层股票将不在最后的结果中展示

Returns

pd.DataFrame column: name, code, value, ratio

summary(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 53473))

brief report table of every funds and the combination investment

Parameters

date – string or obj of date, show info of the date given

Returns

empty dict if nothing is remaining that date dict of various data on the trade positions

tot(prop='基金现值', date=datetime.datetime(2020, 6, 2, 13, 39, 4, 53464))[source]

sum of all the values from one prop of fund daily report, of coures many of the props make no sense to sum

Parameters

prop – string defined in the daily report dict, typical one is ‘currentvalue’ or ‘originalpurchase’

v_category_positions(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 53523), rendered=True)[source]

资产分类扇形图,按大类资产求和绘制

Parameters
  • date

  • rendered – bool. default true for notebook, for plain pyechart obj to return, set rendered=False

Returns

v_positions(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 53517), rendered=True)[source]

pie chart visualization of positions ratio in combination

v_positions_history(end='2020-06-02', rendered=True)[source]

river chart visulization of positions ratio history use text size to avoid legend overlap in some sense, eg. legend_text_size=8

v_tradevolume(freq='D', rendered=True)[source]

visualization on trade summary of the funds combination

Parameters

freq – one character string, frequency label, now supporting D for date, W for week and M for month, namely the trade volume is shown based on the time unit

Returns

pyecharts.Bar()

xirrrate(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 53481), startdate=None, guess=0.01)[source]

xirr rate evauation of the whole invest combination

Parameters
  • date – string or obj of datetime, the virtually sell-all date

  • startdate – string or obj of datetime, the beginning date of calculation, default from first buy

class xalpha.multiple.mulfix(*fundtradeobj, status=None, istatus=None, property=None, fetch=False, save=False, path='', form='csv', totmoney=100000, cashobj=None)[source]

Bases: xalpha.multiple.mul, xalpha.indicator.indicator

introduce cash to make a closed investment system, where netvalue analysis can be applied namely the totcftable only has one row at the very beginning

Parameters
  • fundtradeobj – trade obj to be include

  • status – status table, if no trade obj is provided, it will include all fund based on code in status table

  • property – Dict[fundcode, property_number]. property number 的解释: int. 1: 基金申购采取分位以后全舍而非四舍五入(这种基金是真实存在的==)。2:基金默认分红再投入(0 则是默认现金分红)。4:基金赎回按净值

  • fetch – boolean, when open the fetch option, info class will try fetching from local files first in the init

  • save – boolean, when open the save option, info classes automatically save the class to files

  • path – string, the file path prefix of IO, or object or engine from sqlalchemy to connect sql database

  • form – string, the format of IO, options including: ‘csv’,’sql’

  • totmoney – positive float, the total money as the input at the beginning

  • cashobj – cashinfo object, which is designed to balance the cash in and out

__init__(*fundtradeobj, status=None, istatus=None, property=None, fetch=False, save=False, path='', form='csv', totmoney=100000, cashobj=None)[source]

Initialize self. See help(type(self)) for accurate signature.

static _vcash(totmoney, totcftable, cashobj)[source]

return a virtue status table with a mf(cash) column based on the given tot money and cftable

unitvalue(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 53627))[source]
Returns

float at unitvalue of the whole investment combination

xalpha.policy module

modules for policy making: generate status table for backtesting

class xalpha.policy.buyandhold(infoobj, start, end='2020-06-02', totmoney=100000)[source]

Bases: xalpha.policy.policy

simple policy class where buy at the start day and hold forever, 始终选择分红再投入

status_gen(date)[source]

give policy decision based on given date

Parameters

date – date object

Returns

float, positive for buying money, negative for selling shares

class xalpha.policy.grid(infoobj, buypercent, sellpercent, start, end='2020-06-02', totmoney=100000)[source]

Bases: xalpha.policy.policy

网格投资类,用于指导网格投资策略的生成和模拟。这一简单的网格,买入仓位基于均分总金额,每次的卖出仓位基于均分总份额。 因此实际上每次卖出的份额都不到对应原来档位买入的份额,从而可能实现更多的收益。

Parameters
  • infoobj – info object, trading aim of the grid policy

  • buypercent – list of positive int or float, the grid of points when purchasing, in the unit of percent 比如 [5,5,5,5] 表示以 start 这天的价格为基准,每跌5%,就加一次仓,总共加四次仓

  • sellpercent – list of positive int or float, the grid of points for selling 比如 [8,8,8,8] 分别对应上面各买入仓位应该涨到的百分比从而决定卖出的点位,两个列表都是靠前的是高价位仓,两列表长度需一致

  • start – date str of policy starting

  • end – date str of policy ending

  • totmoney – 总钱数,平均分给各个网格买入仓位

__init__(infoobj, buypercent, sellpercent, start, end='2020-06-02', totmoney=100000)[source]

Initialize self. See help(type(self)) for accurate signature.

status_gen(date)[source]

give policy decision based on given date

Parameters

date – date object

Returns

float, positive for buying money, negative for selling shares

class xalpha.policy.indicator_cross(infoobj, col, start, end='2020-06-02', totmoney=100000)[source]

Bases: xalpha.policy.policy

制定两个任意技术指标之间(或和净值之间)交叉时买入卖出的策略。若收盘时恰好交叉,不操作,等第二日趋势确认。

Parameters
  • info – info object, trading aim of the policy

  • col – a tuple with two strings, eg (‘netvalue’,’MA10’), when the left one is over the right one, we buy and otherwise we sell, that is the core of cross policy, you can choose any two columns as you like, as long as you generate them on the info object before input 也即左栏数据从下向上穿过右栏数据时,买入;反之亦然

  • start – date str of policy starting

  • end – date str of policy ending

  • totmoney – float or int, total money, in the cross policy, we dont have position division, instead we buy all or sell all on the given cross

__init__(infoobj, col, start, end='2020-06-02', totmoney=100000)[source]

Initialize self. See help(type(self)) for accurate signature.

status_gen(date)[source]

give policy decision based on given date

Parameters

date – date object

Returns

float, positive for buying money, negative for selling shares

class xalpha.policy.indicator_points(infoobj, start, col, buy, sell=None, buylow=True, end='2020-06-02', totmoney=100000)[source]

Bases: xalpha.policy.policy

基于技术指标的策略生成类之一,给出技术指标的多个阈值,基于这些点数值进行交易

Parameters
  • infoobj – info object, trading aim of the policy

  • col – str, stands for the tracking column of price table, eg. ‘netvalue’ or ‘PSY’

  • buy – list of tuple, eg [(0.1,1),(0.2,2),(0.3,5)]. buy 1/(1+2+5) of totmoney, when the col value approach 0.1 and so on.

  • sell – similar list of tuple as buy input. the difference is you can omit setting of sell list, this implies you don’t want to sell. 初始化不设置sell参数,在col设为netvalue时,用于进行金字塔底仓购买特别有效. 注意不论是 sell 还是 buy 列表,都要将更难实现(离中间值更远)的点位列在后边。比如如果现在是低买模式, 那么 buy 列表越考后的点数就越小。此外,不建议设置的买点卖点有重叠区域,可能会出现策略逻辑错误。

  • buylow – Bool, Ture 代表,对应点位是跌破买,涨破卖,如果是 False 则反之,默认是 True

  • start – date str of policy starting

  • end – date str of policy ending

  • totmoney – float or int, total money, in the points policy, we share them as different positions, based on the instruction of sell and buy list

__init__(infoobj, start, col, buy, sell=None, buylow=True, end='2020-06-02', totmoney=100000)[source]

Initialize self. See help(type(self)) for accurate signature.

status_gen(date)[source]

give policy decision based on given date

Parameters

date – date object

Returns

float, positive for buying money, negative for selling shares

class xalpha.policy.policy(infoobj, start, end='2020-06-02', totmoney=100000)[source]

Bases: xalpha.record.record

base class for policy making, self.status to get the generating status table

Parameters
  • infoobj – info object as evidence for policy making

  • start – string or object of date, the starting date for policy running

  • end – string or object of date, the ending date for policy running

  • totmoney – float or int, characteristic money value, not necessary to be the total amount of money

__init__(infoobj, start, end='2020-06-02', totmoney=100000)[source]

Initialize self. See help(type(self)) for accurate signature.

status_gen(date)[source]

give policy decision based on given date

Parameters

date – date object

Returns

float, positive for buying money, negative for selling shares

class xalpha.policy.scheduled(infoobj, totmoney, times)[source]

Bases: xalpha.policy.policy

fixed schduled purchase for given date list

Parameters
  • infoobj – info obj

  • totmoney – float, money value for purchase every time

  • times – datelist of datetime object for purchase date, eg [‘2017-01-01’,‘2017-07-07’,…] we recommend you use pd.date_range() to generate the schduled list

__init__(infoobj, totmoney, times)[source]

Initialize self. See help(type(self)) for accurate signature.

status_gen(date)[source]

give policy decision based on given date

Parameters

date – date object

Returns

float, positive for buying money, negative for selling shares

class xalpha.policy.scheduled_tune(infoobj, totmoney, times, piece)[source]

Bases: xalpha.policy.scheduled

定期不定额的方式进行投资,基于净值点数分段进行投资

__init__(infoobj, totmoney, times, piece)[source]
Parameters

piece – list of tuples, eg.[(1000,2),(2000,1.5)]. It means when the fund netvalue is small than some value, we choose to buy multiple times the totmoney. In this example, if the netvalue is larger than 2000, then no purchase happen at all.

status_gen(date)[source]

give policy decision based on given date

Parameters

date – date object

Returns

float, positive for buying money, negative for selling shares

xalpha.provider module

codebase related to data API provider which require further authetications

xalpha.provider.b64decode_s(s)
xalpha.provider.b64encode_s(s)
xalpha.provider.data_source(s)[source]

用以强制要求某些数据源已注册的装饰器。

Parameters

s – 数据源,现在仅支持 “jq”

Returns

xalpha.provider.initialization()[source]
xalpha.provider.set_jq_data(user=None, pswd=None, persistent=False, debug=False)[source]

设置聚宽数据源,需申请聚宽的 jqdata 试用权限。

Parameters
  • user – str。聚宽用户注册手机号。

  • pswd – str。聚宽用户密码。

  • persistent – Optional[bool]. Default False. 如果是 True,则意味着聚宽用户名和密码将进行本地存储, 以后再使用 xalpha 则无须在输入密码调用该函数。请注意,如果这样做,你的聚宽账户和密码将保存在你的本地电脑, 仅有简单编码,无加密保护。请谨慎权衡本地保存的使用便利性和聚宽账户的安全性。 (如果你能保证使用 xalpha 的电脑不被黑,那么就没啥其他安全问题)

  • debug – Optional[bool]. Default False, if True, 那么不去真实验证聚宽数据源,而直接视为注册,用于测试或者直接在聚宽研究环境运行时。

Returns

xalpha.provider.set_proxy(proxy=None)[source]

设置代理,部分数据源可能国内网络环境不稳定。比如标普指数官网。 还有一些数据源很快就会封 IP,需要设置代理,比如人民币中间价官网,建议直接把中间价数据缓存到本地,防止反复爬取。

Parameters

proxy – str. format as “http://user:passwd@host:port” user passwd part can be omitted if not set. None 代表取消代理

Returns

xalpha.provider.show_providers()[source]

展示所有已注册的数据源。

Returns

xalpha.realtime module

module for realtime watch and notfication

xalpha.realtime._format_addr(s)[source]

parse the email sender and receiver, Chinese encode and support

Parameters

s – eg. ‘name <email@website.com>, name2 <email2@web2.com>’

xalpha.realtime.mail(title, content, sender=None, receiver=None, password=None, server=None, port=None, sender_name='sender', receiver_name=None)[source]

send email

Parameters
  • title – str, title of the email

  • content – str, content of the email, plain text only

  • conf – all other paramters can be import as a dictionay, eg.conf = {‘sender’: ‘aaa@bb.com’, ‘sender_name’:’name’, ‘receiver’:[‘aaa@bb.com’,’ccc@dd.com’], ‘password’:‘123456’, ‘server’:’smtp.bb.com’,’port’:123, ‘receiver_name’:[‘me’,’guest’]}. The receiver_name and sender_name options can be omitted.

class xalpha.realtime.review(policylist, namelist=None, date=datetime.datetime(2020, 6, 3, 0, 0))[source]

Bases: object

review policys and give the realtime purchase suggestions

Parameters
  • policylist – list of policy object

  • namelist – list of names of corresponding policy, default as 0 to n-1

  • date – object of datetime, check date, today is prefered, date other than is not guaranteed

__init__(policylist, namelist=None, date=datetime.datetime(2020, 6, 3, 0, 0))[source]

Initialize self. See help(type(self)) for accurate signature.

notification(conf)[source]

send email of self.content, at least support for qq email sender

Parameters

conf – the configuration dictionary for email send settings, no ** before the dict in needed. eg.conf = {‘sender’: ‘aaa@bb.com’, ‘sender_name’:’name’, ‘receiver’:[‘aaa@bb.com’,’ccc@dd.com’], ‘password’:‘123456’, ‘server’:’smtp.bb.com’,’port’:123, ‘receiver_name’:[‘me’,’guest’]}. The receiver_name and sender_name options can be omitted.

xalpha.realtime.rfundinfo(code, round_label=0, dividend_label=0, fetch=False, save=False, path='', form='csv')[source]

give a fundinfo object with todays estimate netvalue at running time

Parameters
  • code – string of six digitals for funds

  • fetch – boolean, when open the fetch option, info class will try fetching from local files first in the init

  • save – boolean, when open the save option, info classes automatically save the class to files

  • path – string, the file path prefix of IO

  • form – string, the format of IO, options including: ‘csv’

Returns

the fundinfo object

class xalpha.realtime.rtdata(code)[source]

Bases: object

get real time data of specific funds

Parameters

code – string of six digitals for funds

__init__(code)[source]

Initialize self. See help(type(self)) for accurate signature.

xalpha.record module

module for status table IO

xalpha.record.IRecord

alias of xalpha.record.irecord

xalpha.record.Record

alias of xalpha.record.record

class xalpha.record.irecord(path='input.csv', **readkwds)[source]

Bases: xalpha.record.record

场内记账单抽象。对于场内交易,记账单毫无疑问需要记录净值,而无法依赖自动查询(因为净值实时变化)。 记账单的格式为5列,分别为 date,code,value,share,fee。日期格式为%Y%m%d, 例 20200202。 代码格式与 xalpha.universal.get_daily() 要求相同。对于常见的 A 股标的,格式为 SH501018。 value 列记录买入卖出或场内申购赎回对应的成交净值单价。share 记录实际上份额的增减,正数代表买入。 fee 栏对应了每笔交易实际的佣金,也可不记录,则默认均为0。记账单不要求严格按时间排序。 该类处理的记账单可以提供给 xalpha.trade.itradexalpha.multiple.imul 使用,进行场内交易的整合分析。

__init__(path='input.csv', **readkwds)[source]

Initialize self. See help(type(self)) for accurate signature.

filter(code, start=None, end=None)[source]
sellout(date=datetime.datetime(2020, 6, 2, 13, 39, 3, 760040), ratio=1)[source]

Sell all the funds in the same ratio on certain day, it is a virtual process, so it can happen before the last action exsiting in the cftable, by sell out earlier, it means all actions behind vanish. The status table in self.status would be directly changed.

Parameters
  • date – string or datetime obj of the selling date

  • ratio – float between 0 to 1, the ratio of selling for each funds

totfee()[source]

累计交给券商的过路费总额

Returns

class xalpha.record.record(path='input.csv', format='matrix', fund_property=False, **readkwds)[source]

Bases: object

basic class for status table read in from csv file. staus table 是关于对应基金的申赎寄账单,不同的行代表不同日期,不同的列代表不同基金, 第一行各单元格分别为 date, 及基金代码。第一列各单元格分别为 date 及各个交易日期,形式 eg. 20170129 表格内容中无交易可以直接为空或0,申购为正数,对应申购金额(申购费扣费前状态),赎回为负数,对应赎回份额, 注意两者不同,恰好对应基金的金额申购份额赎回原则,记录精度均只完美支持一位小数。 几个更具体的特殊标记:

  1. 小数点后第二位如果是5,且当日恰好为对应基金分红日,标志着选择了分红再投入的方式,否则默认分红拿现金。(该默认行为可反转)

2. 对于赎回的负数,如果是一个绝对值小于 0.005 的数,标记了赎回的份额占当时总份额的比例而非赎回的份额数目, 其中0.005对应全部赎回,线性类推。eg. 0.001对应赎回20%。

关于基金行为的设定,基金份额是四舍五入0 还是全部舍弃 1, 基金是默认现金分红 0 还是分红再投 2, 基金是赎回数目对应份额 0 还是金额 4 (只支持货币基金), 将三个选项加起来得到 0-7 的数字,代表了基金的交易性质,默认全部为0。该性质即可以记录在 matrix 形式记账单紧贴基金代码行头的下一行,同时 record 读取时, record(path, fund_property=True) 设定 fund_property 参数, 或直接在记账单第二行日期栏写上 property 即可。每个基金代码对应一个 0 到 7 的数字。 也可为空,默认为 0。

此外如不改变记账单,也可在 xalpha.multiple.mul 类初始化时,传入 property=dict, 字典内容为 {“基金代码”:0-7 数字}。默认为0的代码可不添加。

对于不同格式的记账单的例子,可在 github repo 中 tests 文件夹内的 demo*.csv 参考。

Parameters
  • path – string for the csv file path

  • format – str. Default is “matrix”. Can also be “list”。list 形式的账单更类似流水单。总共三列,每行由日期基金号和金额组成。 三栏标题分别为 date,fund 和 trade。其中日期的形式是 %Y/%m/%d. 该形式与默认的 matrix 不包含 “/” 不同。

  • fund_property – bool. Default False. If True, 基金号下第一行的数字标记对应基金参数(暂时只支持 matrix 形式账单)。

  • readkwds – keywords options for pandas.read_csv() function. eg. skiprows=1, skipfooter=2, see more on pandas doc.

__init__(path='input.csv', format='matrix', fund_property=False, **readkwds)[source]

Initialize self. See help(type(self)) for accurate signature.

save_csv(path=None, index=False, **tocsvkwds)[source]

save the status table to csv file in path, no returns

Parameters
  • path – string of file path

  • index – boolean, whether save the index to the csv file, default False

  • tocsvkwds

    keywords options for pandas.to_csv() function, see pandas doc.

sellout(date=datetime.datetime(2020, 6, 2, 13, 39, 3, 759966), ratio=1)[source]

Sell all the funds in the same ratio on certain day, it is a virtual process, so it can happen before the last action exsiting in the cftable, by sell out earlier, it means all actions behind vanish. The status table in self.status would be directly changed.

Parameters
  • date – string or datetime obj of the selling date

  • ratio – float between 0 to 1, the ratio of selling for each funds

xalpha.remain module

provide class functions to adjust rem form data based on old rem form data such datastructure is useful when first-in-first-out mechanism considered in selling funds and it is also useful when converting the shares of funds.

as the nested list structure is very fragile and tend to induce unpredicatble behaviors, we strongly recommended anytime when rem data serves as function paramters, only utilize functions from this module

xalpha.remain.buy(remc, share, date)[source]
Parameters
  • remc – array of two-elements arrays, eg [[pd.Timestamp(), 50],[pd.Timestamp(), 30] the first element in tuple is pandas.Timestamp object for date while the second element is positive float for remaining shares, tuples in rem MUST be time ordered.

  • share – positive float, only 2 decimal is meaningful.

  • date – string in the date form or datetime object

Returns

new rem after the buying

xalpha.remain.copy(remc)[source]

copy the rem form data so that the return is independent of the input

xalpha.remain.sell(remc, share, date)[source]
Returns

tuple, (sold rem, new rem) sold rem is the positions being sold while new rem is the positions being held

xalpha.remain.trans(remc, coef, date)[source]

在基金份额折算时,将之前持有的仓位按现值折算,相当于前复权

Parameters
  • coef – the factor shown in comment column of fundinfo().price, but with positive value

  • date – string in date form or datetime obj

Returns

new rem after converting

xalpha.toolbox module

modules for Object oriented toolbox which wrappers get_daily and some more

xalpha.toolbox.BlackScholes(S, K, t, v, r=0.02, CallPutFlag='C')[source]

BS option pricing calculator

Parameters
  • S – current stock price

  • K – stricking price

  • t – Time until option exercise (years to maturity)

  • r – risk-free interest rate (by year)

  • v – Variance(volitility) of annual increase

  • CallPutFlag – “C” or “P”, default call option

Returns

class xalpha.toolbox.CBCalculator(code, bondrate=None, riskfreerate=None, volatility=None, name=None, zgj=None)[source]

Bases: object

可转债内在价值,简单计算器,期权价值与债券价值估算

__init__(code, bondrate=None, riskfreerate=None, volatility=None, name=None, zgj=None)[source]
Parameters
  • code – str. 转债代码,包含 SH 或 SZ 字头

  • bondrate – Optional[float]. 评估所用的债券折现率,默认使用中证企业债对应信用评级对应久期的利率

  • riskfreerate – Optioal[float]. 评估期权价值所用的无风险利率,默认使用国债对应久期的年利率。

  • volatility – Optional[float]. 正股波动性百分点,默认在一个范围浮动加上历史波动率的小幅修正。

  • name – str. 对于历史回测,可以直接提供 str,免得多次 get_rt 获取 name

  • zgj – float. 手动设置转股价,适用于想要考虑转股价调整因素进行历史估值的高阶用户

analyse(date=None)[source]
process_byday(date=None)[source]
class xalpha.toolbox.Compare(*codes, start='20200101', end='20200602', col='close', normalize=True)[source]

Bases: object

将不同金融产品同起点归一化比较

__init__(*codes, start='20200101', end='20200602', col='close', normalize=True)[source]
Parameters
  • codes – Union[str, tuple], 格式与 xalpha.universal.get_daily() 相同,若需要汇率转换,需要用 tuple,第二个元素形如 “USD”

  • start – %Y%m%d

  • end – %Y%m%d, default yesterday

  • col – str, default close. The column to be compared.

  • normalize – bool, default True. 是否将对比价格按起点时间归一。

corr()[source]

打印相关系数矩阵

Returns

pd.DataFrame

v()[source]

显示日线可视化

Returns

class xalpha.toolbox.FundPEBHistory(code, start=None, end=None)[source]

Bases: xalpha.toolbox.IndexPEBHistory

基金历史估值封装

__init__(code, start=None, end=None)[source]
Parameters
  • code – str. 形式可以是 399971.XSHE 或者 SH000931

  • start – Optional[str]. %Y-%m-%d, 估值历史计算的起始日。

  • end – Dont use, only for debug

class xalpha.toolbox.IndexPEBHistory(code, start=None, end=None)[source]

Bases: object

对于指数历史 PE PB 的封装类

__init__(code, start=None, end=None)[source]
Parameters
  • code – str. 形式可以是 399971.XSHE 或者 SH000931

  • start – Optional[str]. %Y-%m-%d, 估值历史计算的起始日。

  • end – Dont use, only for debug

_gen_percentile()[source]
current(y='pe')[source]

返回实时的 pe 或 pb 绝对值估计。

Parameters

y – Optional[str]. “pe” (defualt) or “pb”

Returns

float.

current_percentile(y='pe')[source]

返回实时的 pe 或 pb 历史百分位估计

Parameters

y – Optional[str]. “pe” (defualt) or “pb”

Returns

float.

fluctuation()[source]
indexs = {'000016.XSHG': ('上证50', '2012-01-01'), '000300.XSHG': ('沪深300', '2012-01-01'), '000807.XSHG': ('食品饮料', '2013-01-01'), '000827.XSHG': ('中证环保', '2013-01-01'), '000831.XSHG': ('500低波', '2013-01-01'), '000852.XSHG': ('中证1000', '2015-01-01'), '000905.XSHG': ('中证500', '2012-01-01'), '000922.XSHG': ('中证红利', '2012-01-01'), '000925.XSHG': ('基本面50', '2012-01-01'), '000931.XSHG': ('中证可选', '2012-01-01'), '000978.XSHG': ('医药100', '2012-01-01'), '000991.XSHG': ('全指医药', '2012-01-01'), '000992.XSHG': ('全指金融', '2012-01-01'), '399006.XSHE': ('创业板指', '2012-01-01'), '399324.XSHE': ('深证红利', '2012-01-01'), '399812.XSHE': ('养老产业', '2016-01-01'), '399932.XSHE': ('中证消费', '2012-01-01'), '399971.XSHE': ('中证传媒', '2014-07-01')}
percentile()[source]

打印 PE PB 的历史十分位对应值

Returns

summary(return_tuple=False)[source]

打印现在估值的全部分析信息。

Returns

v(y='pe')[source]

pe 或 pb 历史可视化

Parameters

y – Optional[str]. “pe” (defualt) or “pb”

Returns

class xalpha.toolbox.OverPriced(code, start=None, end=None, prev=None)[source]

Bases: object

ETF 或 LOF 历史折溢价情况分析

__init__(code, start=None, end=None, prev=None)[source]
Parameters
  • code – str. eg SH501018, SZ160416

  • start – date range format is the same as xa.get_daily

  • end

  • prev

v(hline=None)[source]
Parameters

hline – Union[float, List[float]], several horizental lines for assistance

Returns

xalpha.toolbox.PEBHistory(code, start=None, end=None)[source]

历史估值分析工具箱

Parameters
  • code – str. 1. SH000***, SZ399***, 指数历史估值情况,第一原理计算,需要聚宽数据源 2. F******, 基金历史估值情况,根据股票持仓,第一原理计算 3. 8*****, 申万行业估值数据,需要聚宽数据源 4. 沪深港美股票代码,个股历史估值数据

  • start – str, %Y%m%d, 默认起点随着标的类型不同而不同

  • end – str, 仅限于 debug,强烈不建议设定,默认到昨天

Returns

some object of PEBHistory class

class xalpha.toolbox.QDIIPredict(code, t1dict=None, t0dict=None, positions=False, fetch=False, save=False)[source]

Bases: object

T+2 确认份额的 QDII 型基金净值预测类

Warning

由于该类与现实时间的强烈耦合和激进的缓存利用,该类的对象不能”过夜”使用,每天需声明新的对象

__init__(code, t1dict=None, t0dict=None, positions=False, fetch=False, save=False)[source]
Parameters
  • code – str, 场内基金代码,eg SH501018

  • t1dict – Dict[str, float]. 用来预测 T-1 净值的基金组合持仓,若为空自动去 holdings 中寻找。

  • t0ict – Dict[str, float]. 用来预测 T 实时净值的基金组合持仓,若为空自动去 holdings 中寻找。

  • positions – bool. 仓位是否浮动,默认固定仓位。

  • fetch – bool, default True. 优先从 backend fetch t1。

  • save – bool, default True. 将 t1 缓存到 backend。

_base_value(code, shift)[source]
analyse()[source]

打印出回测结果的定量分析。

Returns

None

static analyse_deviate(cpdf, col)[source]
static analyse_percentile(cpdf, col)[source]
static analyse_ud(cpdf, col1, col2)[source]
Parameters
  • cpdf – pd.DataFrame, with col1 as real netvalue and col2 as prediction difference

  • col1 – str.

  • col2 – str.

Returns

benchmark_test(start, end, **kws)[source]

对该净值预测模型回测

Parameters
  • start – str. 起始日期

  • end – str. 终止日期

  • kws – 可选仓位估计的超参。

Returns

pd.DataFrame. real 列为真实涨跌幅,est 列为估计涨跌幅,diff 列为两者之差。

get_position(date=None, refresh=False, return_date=True, **kws)[source]

基于 date 日之前的净值数据,对 date 预估需要的仓位进行计算。

Parameters
  • date – str. %Y-%m-%d

  • refresh – bool, default False. 若为 True,则刷新缓存,重新计算仓位。

  • return_date – bool, default True. return tuple, the second one is date in the format %Y%m%d

  • kws – 一些预估仓位可能的超参。包括 window,预估所需的时间窗口,decay 加权平均的权重衰减,smooth 每日仓位处理的平滑函数。以上参数均可保持默认即可获得较好效果。

Returns

float. 0-100. 100 代表满仓。

get_t0(percent=False, return_date=True)[source]

获取当日实时净值估计, 该接口每日凌晨到美股收盘(早晨),不保证自洽和可用

Parameters
  • percent – bool, default False。现在有两种实时的预测处理逻辑。若 percent 是 True,则将 t0dict 的 每个持仓标的的今日涨跌幅进行估算,若为 False,则将标的现价和标的对应指数昨日收盘价的比例作为涨跌幅估算。不推荐使用 percent=True.

  • return_date – bool, default True. return tuple, the second one is date in the format %Y%m%d

Returns

float

get_t0_rate(percent=False, return_date=True)[source]
get_t1(date=None, return_date=True)[source]

预测 date 日的净值,基于 date-1 日的净值和 date 日的外盘数据,数据自动缓存,不会重复计算

Parameters
  • date – str. %Y-%m-%d. 注意若是 date 日为昨天,即今日预测昨日的净值,date 取默认值 None。

  • return_date – bool, default True. return tuple, the second one is date in the format %Y%m%d

Returns

float, (str).

Raises

NonAccurate – 由于外盘数据还未及时更新,而 raise,可在调用程序中用 except 捕获再处理。

get_t1_rate(date=None, return_date=True)[source]
get_t2(return_date=True)[source]

返回最新的已公布基金净值,注意这里严格按照最新公布,不一定是前两个交易日,可以更新,但更老会报错 DateMismatch

Parameters

return_date

Returns

if return_date is True, tuple (value, %Y-%m-%d)

hot_replace(code)[source]
set_position(value, date=None)[source]
set_t1(value, date=None)[source]

设定 T-1 的基金净值,有时我们只想计算实时净值,这就不需要重复计算 t1,可以先行设定

Parameters
  • value

  • date

Returns

set_t2(value, date=None)[source]

手动设定 t2 净值

Parameters

value

Returns

class xalpha.toolbox.RTPredict(code, t0dict=None)[source]

Bases: object

场内 ETF LOF 实时溢价,非 QDII 类

__init__(code, t0dict=None)[source]
Parameters
  • code

  • t0dict

get_t0(return_date=True, percent=False)[source]
get_t0_rate(percent=False, return_date=True)[source]
get_t1(return_date=True)[source]

获取昨日基金净值

Returns

class xalpha.toolbox.SWPEBHistory(code, start=None, end=None)[source]

Bases: xalpha.toolbox.IndexPEBHistory

申万行业历史估值封装。 申万一级行业指数列表: https://www.hysec.com/hyzq/hy/detail/detail.jsp?menu=4&classid=00000003001200130002&firClassid=000300120013&twoClassid=0003001200130002&threeClassid=0003001200130002&infoId=3046547 二三级行业指数也支持

__init__(code, start=None, end=None)[source]
Parameters
  • code – 801180 申万行业指数

  • start

  • end

index1 = ['801740', '801020', '801110', '801200', '801160', '801010', '801120', '801230', '801750', '801050', '801890', '801170', '801710', '801130', '801180', '801760', '801040', '801780', '801880', '801140', '801720', '801080', '801790', '801030', '801730', '801210', '801770', '801150']
class xalpha.toolbox.StockPEBHistory(code, start=None, end=None)[source]

Bases: xalpha.toolbox.IndexPEBHistory

个股历史估值封装

__init__(code, start=None, end=None)[source]
Parameters
  • code – 801180 申万行业指数

  • start

  • end

class xalpha.toolbox.TEBHistory(code, start=None, end=None)[source]

Bases: object

指数总盈利和总净资产变化的分析工具箱

__init__(code, start=None, end=None)[source]
Parameters
  • code – str. 指数代码,eg. SH000016

  • start

  • end

fit(verbose=True)[source]

fit exponential trying find annualized increase

Parameters

verbose – if True (default), print debug info of linear regression

Returns

result()[source]
Returns

Dict[str, float]. 返回指数总净资产和净利润的年均增速

(拟合平滑意义,而非期末除以期初再开方,更好减少时间段两端极端情形的干扰)

v(y='lne')[source]

总资产或总利润与拟合曲线的可视化

Parameters

y – str. one of lne, lnb, e, b, roe

Returns

xalpha.toolbox._get_currency_code(c)[source]
xalpha.toolbox._is_on(code, date)[source]
xalpha.toolbox._set_display_notebook()[source]

Initialize DataTable mode for pandas DataFrame represenation.

xalpha.toolbox._set_holdings(module)[source]
xalpha.toolbox._smooth_pos(r, e, o)[source]

单日仓位估计的平滑函数

Parameters
  • r – 实际涨幅

  • e – 满仓估计涨幅

  • o – 昨日仓位估计

Returns

xalpha.toolbox.cb_bond_value(issue_date, rlist, rate=0.03, date=None, tax=1.0)[source]

可转债债券价值计算器

Parameters
  • issue_date – str. 发行日期

  • rlist – List[float], 每年度的利息百分点,比如 0.4,0.6等,最后加上最后返回的值(不含最后一年利息),比如 104

  • rate – float,现金流折算利率,应取同久期同信用等级的企业债利率,参考 https://yield.chinabond.com.cn/

  • date – 默认今天,计算债券价值基于的时间

  • tax – float,税率,1.0 表示不算税后,0.8 为计算税后利息,一般不需要设置成0.8,因为区别不大

Returns

xalpha.toolbox.cb_ytm(issue_date, rlist, cp, date=None, tax=1.0, guess=0.01)[source]

可转债到期收益率计算器

Parameters
  • issue_date – 发行日期

  • rlist – 计息及赎回列表

  • cp – 可转债现价

  • date – 参考日期

  • tax – 计税 1 vs 0.8 税后 YTM

  • guess – YTM 估计初始值

Returns

xalpha.toolbox.daily_increment(code, date, lastday=None, _check=False, warning_threhold=None)[source]

单一标的 date 日(若 date 日无数据则取之前的最晚有数据日,但该日必须大于 _check 对应的日期)较上一日或 lastday 的倍数, lastday 支持不完整,且不能离 date 太远

Parameters
  • code

  • date

  • lastday – 如果用默认 None,则表示和前一日的涨跌, 不是一个支持任意日期涨幅的通用类,只有最接近的几天才保证逻辑没有问题

  • _check – 数据必须已更新到 date 日,除非之前每天都是节假日

Returns

xalpha.toolbox.error_catcher(f)[source]

装饰器,透明捕获 DateMismatch

Parameters

f

Returns

xalpha.toolbox.evaluate_fluctuation(hdict, date, lastday=None, _check=None, warning_threhold=None)[source]

分析资产组合 hdict 的涨跌幅,全部兑换成人民币考虑

Parameters
  • hdict

  • date

  • lastday

  • _check – bool, ensure date source has been updated, otherwise throw DataMismatch error

  • warning_threhold – float>1, 异常检查阈值,若为 2, 则代表单日涨到2或跌倒1/2以外被舍弃

Returns

xalpha.toolbox.get_alt[source]

抓取失败后寻找替代对等标的

Parameters

code

Returns

xalpha.toolbox.get_currency[source]

通过代码获取计价货币的函数

Parameters

code

Returns

xalpha.toolbox.get_currency_code[source]
xalpha.toolbox.get_holdings_dict(code, aim=95)[source]

通过天天基金的股票持仓数据来生成实时预测所需的持仓字典,不保证稳定性和可靠性以及 API 的连续性,慎用

Parameters
  • code

  • aim

Returns

xalpha.toolbox.get_market[source]

非常粗糙的通过代码获取交易市场的函数

Parameters

code

Returns

xalpha.toolbox.is_on(date, market='CN', no_trading_days=None)[source]

粗略鉴定 date 日是否是指定 market 的开市日,对于当日鉴定,仍有数据未及时更新的风险。也存在历史数据被 investing 补全的风险。

Parameters
  • date

  • market – str. CN, JP, HK, US, UK, CH, HK, DE

Returns

bool.

xalpha.toolbox.set_display(env='')[source]

开关 DataFrame 的显示模式,仅 Jupyter Notebook 有效。

Parameters

env – str, default “”. If env=”notebook”, pd.DataFrame will be shown in fantastic web language

Returns

xalpha.toolbox.set_holdings(module=None)[source]

导入外部 holdings.py 数据文件用来预测基金净值

Parameters

module – mod. import holdings

Returns

None.

xalpha.trade module

module for trade class

xalpha.trade.ITrade

alias of xalpha.trade.itrade

xalpha.trade.Trade

alias of xalpha.trade.trade

xalpha.trade.bottleneck(cftable)[source]

find the max total input in the history given cftable with cash column

Parameters

cftable – pd.DataFrame of cftable

class xalpha.trade.itrade(code, status, name=None)[source]

Bases: xalpha.trade.trade

场内交易,只包含 cftable 现金流表

__init__(code, status, name=None)[source]
Parameters
  • code – str. 代码格式与 xalpha.universal.get_daily() 要求相同

  • status – 记账单或 irecord 类。

  • name – Optional[str]. 可提供标的名称。

_arrange()[source]
get_netvalue(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 53357))[source]
get_type()[source]
class xalpha.trade.trade(infoobj, status)[source]

Bases: object

Trade class with fundinfo obj as input and its main attrs are cftable and remtable:

1. cftable: pd.Dataframe, 现金流量表,每行为不同变更日期,三列分别为 date,cash, share,标记对于某个投资标的 现金的进出和份额的变化情况,所有的份额数据为交易当时的不复权数据。基金份额折算通过流量表中一次性的份额增减体现。

2. remtable:pd.Dataframe, 持仓情况表,每行为不同变更日期,两列分别为 date 和 rem, rem 数据结构是一个嵌套的列表, 包含了不同时间买入仓位的剩余情况,详情参见 remain 模块。这一表格如非必需,避免任何直接调用。

Parameters
  • infoobj – info object as the trading aim

  • status – status table, obtained from record class

__init__(infoobj, status)[source]

Initialize self. See help(type(self)) for accurate signature.

_addrow()[source]

Return cashflow table with one more line or raise an exception if there is no more line to add The same logic also applies to rem table 关于对于一个基金多个操作存在于同一交易日的说明:无法处理历史买入第一笔同时是分红日的情形, 事实上也不存在这种情形。无法处理一日多笔买卖的情形。 同一日既有卖也有买不现实,多笔买入只能在 csv 上合并记录,由此可能引起份额计算 0.01 的误差。可以处理分红日买入卖出的情形。 分级份额折算日封闭无法买入,所以程序直接忽略当天的买卖。因此不会出现多个操作共存的情形。

_arrange()[source]
briefdailyreport(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 53291))[source]

quick summary of highly used attrs for trade

Parameters

date – string or object of datetime

Returns

dict with several attrs: date, unitvalue, currentshare, currentvalue

dailyreport(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 53278))[source]
get_netvalue(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 53285))[source]
unitcost(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 53297))[source]

give the unitcost of fund positions

Parameters

date – string or object of datetime

Returns

float number of unitcost

v_totvalue(end=datetime.datetime(2020, 6, 2, 13, 39, 4, 53311), rendered=True, vopts=None)[source]

visualization on the total values daily change of the aim

v_tradecost(start=None, end=datetime.datetime(2020, 6, 2, 13, 39, 4, 53305), rendered=True)[source]

visualization giving the average cost line together with netvalue line

Returns

pyecharts.line

v_tradevolume(freq='D', rendered=True)[source]

visualization on trade summary

Parameters

freq – string, “D”, “W” and “M” are supported

Returns

pyecharts.charts.bar.render_notebook()

xirrrate(date=datetime.datetime(2020, 6, 2, 13, 39, 4, 53269), startdate=None, guess=0.01)[source]

give the xirr rate for all the trade of the aim before date (virtually sold out on date)

Parameters
  • date – string or obj of datetime, the virtually sell-all date

  • startdate – string or obj of datetime, the beginning date of calculation, default from first buy

xalpha.trade.turnoverrate(cftable, end=datetime.datetime(2020, 6, 2, 13, 39, 4, 53246))[source]

calculate the annualized turnoverrate

Parameters
  • cftable – pd.DataFrame of cftable

  • end – str or obj of datetime for the end date of the estimation

xalpha.trade.vtradevolume(cftable, freq='D', rendered=True)[source]

aid function on visualization of trade summary

Parameters
  • cftable – cftable (pandas.DataFrame) with at least date and cash columns

  • freq – one character string, frequency label, now supporting D for date, W for week and M for month, namely the trade volume is shown based on the time unit

Returns

the Bar object

xalpha.trade.xirrcal(cftable, trades, date, startdate=None, guess=0.01)[source]

calculate the xirr rate

Parameters
  • cftable – cftable (pd.Dateframe) with date and cash column

  • trades – list [trade1, …], every item is an trade object, whose shares would be sold out virtually

  • date – string of date or datetime object, the date when virtually all holding positions being sold

  • guess – floating number, a guess at the xirr rate solution to be used as a starting point for the numerical solution

Returns

the IRR as a single floating number

xalpha.universal module

modules for universal fetcher that gives historical daily data and realtime data for almost everything in the market

xalpha.universal.VInfo

alias of xalpha.universal.vinfo

xalpha.universal._convert_code(code)[source]

将聚宽形式的代码转化为 xalpha 形式

Parameters

code

Returns

xalpha.universal._get_daily(code, start=None, end=None, prev=365, _from=None, wrapper=True, handler=True, **kws)[source]

universal fetcher for daily historical data of literally everything has a value in market. 数据来源包括但不限于天天基金,雪球,英为财情,外汇局官网,聚宽,标普官网,bloomberg,雅虎财经,ycharts等。

Parameters
  • code

    str.

    1. 对于沪深市场的股票,指数,ETF,LOF 场内基金,可转债和债券,直接使用其代码,主要开头需要包括 SH 或者 SZ。如果数字代码之后接 .A .B .N 分别代表后复权,前复权和不复权数据,不加后缀默认前复权。港股美股同理。

    2. 对于香港市场的股票,指数,使用其数字代码,同时开头要添加 HK。

    3. 对于美国市场的股票,指数,ETF 等,直接使用其字母缩写代码即可。

    4. 对于人民币中间价数据,使用 “USD/CNY” 的形式,具体可能的值可在 http://www.chinamoney.com.cn/chinese/bkccpr/ 历史数据的横栏查询,注意日元需要用 100JPY/CNY.

    5. 对于所有可以在 cn.investing.com 网站查到的金融产品,其代码可以是该网站对应的统一代码,或者是网址部分,比如 DAX 30 的概览页面为 https://cn.investing.com/indices/germany-30,那么对应代码即为 “indices/germany-30”。也可去网页 inspect 手动查找其内部代码(一般不需要自己做,推荐直接使用网页url作为 code 变量值),手动 inspect 加粗的实时价格,其对应的网页 span class 中的 pid 的数值即为内部代码。

    6. 对于国内发行的基金,使用基金代码,同时开头添加 F。若想考虑分红使用累计净值,则开头添加 T。

    7. 对于国内发行的货币基金,使用基金代码,同时开头添加 M。(全部按照净值数据处理)

    8. 形如 peb-000807.XSHG 或 peb-SH000807 格式的数据,可以返回每周的指数估值情况,需要 enable 聚宽数据源方可查看。

    9. 形如 iw-000807.XSHG 或 iw-SH000807 格式的数据,可以返回每月的指数成分股和实时权重,需要 enable 聚宽数据源方可查看。

    10. 形如 fs-SH501018 格式的数据,可以返回指定场内基金每日份额,需要 enable 聚宽数据源方可查看。

    11. 形如 SP5475707.2 格式的数据,可以返回标普官网相关指数的日线数据(最近十年),id 5475707 部分可以从相关指数 export 按钮获取的链接中得到,小数点后的部分代表保存的列数。参考链接:https://us.spindices.com/indices/equity/sp-global-oil-index. 若SPC开头,则从中国网站获取。

    12. 形如 BB-FGERBIU:ID 格式的数据,对应网页 https://www.bloomberg.com/quote/FGERBIU:ID,可以返回彭博的数据(最近五年)

    13. 形如 sw-801720 格式的数据,可以返回对应申万行业的历史数据情况,需要 enable 聚宽数据源方可查看。

    14. 形如 teb-SH000300 格式的数据,返回每周指数盈利和净资产总值数据(单位:亿人民币元),需要 enbale 聚宽数据方可查看。

    15. 形如 YH-CSGOLD.SW 格式的数据,返回雅虎财经标的日线数据(最近十年)。代码来自标的网页 url:https://finance.yahoo.com/quote/CSGOLD.SW

    16. 形如 FT-22065529 格式的数据或 FT-INX:IOM,可以返回 financial times 的数据,推荐直接用后者。前者数字代码来源,打开浏览器 network 监视,切换图标时间轴时,会新增到 https://markets.ft.com/data/chartapi/series 的 XHR 请求,其 request payload 里的 [elements][symbol] 即为该指数对应数字。

    17. 形如 FTC-WTI+Crude+Oil 格式的数据,开头可以是 FTC, FTE, FTX, FTF, FTB, FTI 对应 ft.com 子栏目 commdities,equities,currencies,funds,bonds,indicies。其中 FTI 和 FT 相同。

    18. 形如 mcy-MAC_AREA_UNEMPLOY 格式的数据,返回相应的宏观数据,需要聚宽数据源。mcy,mcq,mcm 代表年度,季度和月度的数据,code 为表名,可以参考 https://www.joinquant.com/help/api/help?name=macroData

    19. 形如 ZZ000905,ZZH30533 的代码,代表中证官网的指数,ZZ 之后接指数代码,注意有些指数代码里可能包含 H,历史数据最大到近五年。

    20. 形如 GZB30018, GZ399299 格式的数据,代表国证系列指数, GZ 之后接指数代码,代码可能包含更多字母。

    21. 形如 ESCI000201 格式的数据,易盛商品指数系列,参考 http://www.esunny.com.cn/index.php?a=lists&catid=60

    22. 形如 pt-F100032 格式的数据,返回指定基金每季度股票债券和现金的持仓比例

    23. 形如 yc-companies/DBP,yc-companies/DBP/price 格式的数据,返回ycharts股票、ETF数据,对应网页 https://ycharts.com/companies/DBP/price,最后部分为数据含义,默认price,可选:net_asset_value(仅ETF可用)、total_return_price、total_return_forward_adjusted_price、average_volume_30,历史数据限制五年内。

    24. 形如 yc-indices/^SPGSCICO,yc-indices/^SPGSCICO/level 格式的数据,返回ycharts指数数据,对应网页 https://ycharts.com/indices/%5ESPGSCICO/level,最后部分为数据含义,默认level,可选:total_return_forward_adjusted_price,历史数据限制五年内。

    25. 形如 HZ999001 HZ999005 格式的数据,代表了华证系列指数 http://www.chindices.com/indicator.html#

    26. 形如 B-AA+.3 格式的数据,代表了 AA+ 企业债三年久期利率数据 (每周)

  • start – str. “20200101”, “2020/01/01”, “2020-01-01” are all legal. The starting date of daily data.

  • end – str. format is the same as start. The ending date of daily data.

  • prev – Optional[int], default 365. If start is not specified, start = end-prev.

  • _from – Optional[str]. 一般用户不需设定该选项。can be one of “xueqiu”, “zjj”, “investing”, “tiantianjijin”. Only used for debug to enforce data source. For common use, _from can be chosed automatically based on code in the run time.

  • wrapper – bool. 一般用户不需设定该选项。

  • handler – bool. Default True. 若为 False,则 handler 钩子失效,用于钩子函数中的原函数嵌套调用。

Returns

pd.Dataframe. must include cols: date[pd.Timestamp],close[float64]。

xalpha.universal._get_index_weight_range(code, start, end)[source]
xalpha.universal._get_peb_range(code, start, end)[source]

获取指定指数一段时间内的 pe pb 值。

Parameters
  • code – 聚宽形式指数代码。

  • start

  • end

Returns

pd.DataFrame

xalpha.universal._inverse_convert_code(code)[source]

将 xalpha 形式的代码转化为聚宽形式

Parameters

code

Returns

xalpha.universal._variate_ua()[source]
xalpha.universal.cached(s)[source]

Deprecated, use cachedio() instead, where backend="memory".

Usage as follows:

@cached("20170101")
def get_daily(*args, **kws):
   return xa.get_daily(*args, **kws)

Automatically cache the result in memory and avoid refetching :param s: str. eg. “20160101”, the starting date of cached table. :return: wrapped function.

xalpha.universal.cachedio(**ioconf)[source]

用法类似:func:cached,通用透明缓存器,用来作为 (code, start, end …) -> pd.DataFrame 形式函数的缓存层, 避免重复爬取已有数据。

Parameters

**ioconf

可选关键字参数 backend: csv or sql or memory, path: csv 文件夹或 sql engine, refresh True 会刷新结果,重新爬取, default False, prefix 是 key 前统一部分, 缓存 hash 标志

Returns

xalpha.universal.check_cache(*args, omit_lines=0, **kws)[source]
xalpha.universal.decouple_code(code)[source]

decompose SH600000.A into SH600000, after

Parameters

code

Returns

Tuple

xalpha.universal.dstr2dobj(dstr)[source]
xalpha.universal.fetch_backend(key)[source]
xalpha.universal.get_bar(code, prev=24, interval=3600, _from=None, handler=True, start=None, end=None)[source]
Parameters
  • code – str. 支持雪球和英为的代码

  • prev – points of data from now to back, often limited by API around several hundreds

  • interval – float, seconds. need to match the corresponding API, typical values include 60, 300, 3600, 86400, 86400*7

  • handler – bool. Default True. 若为 False,则 handler 钩子失效,用于钩子函数中的嵌套。

Returns

pd.DataFrame

xalpha.universal.get_bar_frominvesting(code, prev=120, interval=3600)[source]

get bar data beyond daily bar

Parameters
  • code – str. investing id or url

  • prev – int, data points from now, max might be around 500, if exceed, only None is returnd

  • interval – default 3600. optional 60, 300, 900, 1800, 18000, 86400, “week”, “month”

Returns

pd.DataFrame or None if prev and interval unmatch the API

xalpha.universal.get_bar_fromjq(code, start, end, interval, fq='pre')[source]
xalpha.universal.get_bar_fromwsj(code, token=None, interval=3600)[source]
xalpha.universal.get_bar_fromxq(code, prev, interval=3600)[source]
Parameters
  • code

  • prev

  • interval – 1m, 5m, 15m, 30m, 60m, 120m, month, quarter, year, week, day

Returns

xalpha.universal.get_bar_ttl
xalpha.universal.get_bond_rates[source]

获取各评级企业债的不同久期的预期利率

Parameters
  • rating – str. eg AAA, AA-, N for 中国国债

  • date – %Y-%m-%d

Returns

xalpha.universal.get_bond_rates_range(rating, duration=3, freq='W-FRI', start=None, end=None)[source]
xalpha.universal.get_cninvesting_rt(suburl, app=False)[source]
xalpha.universal.get_daily(code, start=None, end=None, prev=365, _from=None, wrapper=True, handler=True, **kws)

universal fetcher for daily historical data of literally everything has a value in market. 数据来源包括但不限于天天基金,雪球,英为财情,外汇局官网,聚宽,标普官网,bloomberg,雅虎财经,ycharts等。

Parameters
  • code

    str.

    1. 对于沪深市场的股票,指数,ETF,LOF 场内基金,可转债和债券,直接使用其代码,主要开头需要包括 SH 或者 SZ。如果数字代码之后接 .A .B .N 分别代表后复权,前复权和不复权数据,不加后缀默认前复权。港股美股同理。

    2. 对于香港市场的股票,指数,使用其数字代码,同时开头要添加 HK。

    3. 对于美国市场的股票,指数,ETF 等,直接使用其字母缩写代码即可。

    4. 对于人民币中间价数据,使用 “USD/CNY” 的形式,具体可能的值可在 http://www.chinamoney.com.cn/chinese/bkccpr/ 历史数据的横栏查询,注意日元需要用 100JPY/CNY.

    5. 对于所有可以在 cn.investing.com 网站查到的金融产品,其代码可以是该网站对应的统一代码,或者是网址部分,比如 DAX 30 的概览页面为 https://cn.investing.com/indices/germany-30,那么对应代码即为 “indices/germany-30”。也可去网页 inspect 手动查找其内部代码(一般不需要自己做,推荐直接使用网页url作为 code 变量值),手动 inspect 加粗的实时价格,其对应的网页 span class 中的 pid 的数值即为内部代码。

    6. 对于国内发行的基金,使用基金代码,同时开头添加 F。若想考虑分红使用累计净值,则开头添加 T。

    7. 对于国内发行的货币基金,使用基金代码,同时开头添加 M。(全部按照净值数据处理)

    8. 形如 peb-000807.XSHG 或 peb-SH000807 格式的数据,可以返回每周的指数估值情况,需要 enable 聚宽数据源方可查看。

    9. 形如 iw-000807.XSHG 或 iw-SH000807 格式的数据,可以返回每月的指数成分股和实时权重,需要 enable 聚宽数据源方可查看。

    10. 形如 fs-SH501018 格式的数据,可以返回指定场内基金每日份额,需要 enable 聚宽数据源方可查看。

    11. 形如 SP5475707.2 格式的数据,可以返回标普官网相关指数的日线数据(最近十年),id 5475707 部分可以从相关指数 export 按钮获取的链接中得到,小数点后的部分代表保存的列数。参考链接:https://us.spindices.com/indices/equity/sp-global-oil-index. 若SPC开头,则从中国网站获取。

    12. 形如 BB-FGERBIU:ID 格式的数据,对应网页 https://www.bloomberg.com/quote/FGERBIU:ID,可以返回彭博的数据(最近五年)

    13. 形如 sw-801720 格式的数据,可以返回对应申万行业的历史数据情况,需要 enable 聚宽数据源方可查看。

    14. 形如 teb-SH000300 格式的数据,返回每周指数盈利和净资产总值数据(单位:亿人民币元),需要 enbale 聚宽数据方可查看。

    15. 形如 YH-CSGOLD.SW 格式的数据,返回雅虎财经标的日线数据(最近十年)。代码来自标的网页 url:https://finance.yahoo.com/quote/CSGOLD.SW

    16. 形如 FT-22065529 格式的数据或 FT-INX:IOM,可以返回 financial times 的数据,推荐直接用后者。前者数字代码来源,打开浏览器 network 监视,切换图标时间轴时,会新增到 https://markets.ft.com/data/chartapi/series 的 XHR 请求,其 request payload 里的 [elements][symbol] 即为该指数对应数字。

    17. 形如 FTC-WTI+Crude+Oil 格式的数据,开头可以是 FTC, FTE, FTX, FTF, FTB, FTI 对应 ft.com 子栏目 commdities,equities,currencies,funds,bonds,indicies。其中 FTI 和 FT 相同。

    18. 形如 mcy-MAC_AREA_UNEMPLOY 格式的数据,返回相应的宏观数据,需要聚宽数据源。mcy,mcq,mcm 代表年度,季度和月度的数据,code 为表名,可以参考 https://www.joinquant.com/help/api/help?name=macroData

    19. 形如 ZZ000905,ZZH30533 的代码,代表中证官网的指数,ZZ 之后接指数代码,注意有些指数代码里可能包含 H,历史数据最大到近五年。

    20. 形如 GZB30018, GZ399299 格式的数据,代表国证系列指数, GZ 之后接指数代码,代码可能包含更多字母。

    21. 形如 ESCI000201 格式的数据,易盛商品指数系列,参考 http://www.esunny.com.cn/index.php?a=lists&catid=60

    22. 形如 pt-F100032 格式的数据,返回指定基金每季度股票债券和现金的持仓比例

    23. 形如 yc-companies/DBP,yc-companies/DBP/price 格式的数据,返回ycharts股票、ETF数据,对应网页 https://ycharts.com/companies/DBP/price,最后部分为数据含义,默认price,可选:net_asset_value(仅ETF可用)、total_return_price、total_return_forward_adjusted_price、average_volume_30,历史数据限制五年内。

    24. 形如 yc-indices/^SPGSCICO,yc-indices/^SPGSCICO/level 格式的数据,返回ycharts指数数据,对应网页 https://ycharts.com/indices/%5ESPGSCICO/level,最后部分为数据含义,默认level,可选:total_return_forward_adjusted_price,历史数据限制五年内。

    25. 形如 HZ999001 HZ999005 格式的数据,代表了华证系列指数 http://www.chindices.com/indicator.html#

    26. 形如 B-AA+.3 格式的数据,代表了 AA+ 企业债三年久期利率数据 (每周)

  • start – str. “20200101”, “2020/01/01”, “2020-01-01” are all legal. The starting date of daily data.

  • end – str. format is the same as start. The ending date of daily data.

  • prev – Optional[int], default 365. If start is not specified, start = end-prev.

  • _from – Optional[str]. 一般用户不需设定该选项。can be one of “xueqiu”, “zjj”, “investing”, “tiantianjijin”. Only used for debug to enforce data source. For common use, _from can be chosed automatically based on code in the run time.

  • wrapper – bool. 一般用户不需设定该选项。

  • handler – bool. Default True. 若为 False,则 handler 钩子失效,用于钩子函数中的原函数嵌套调用。

Returns

pd.Dataframe. must include cols: date[pd.Timestamp],close[float64]。

xalpha.universal.get_ft_id[source]
xalpha.universal.get_fund(code)[source]
xalpha.universal.get_fund_peb(code, date, threhold=0.3)[source]

根据基金的股票持仓,获取对应日期的 pe,pb 估值

Parameters
  • code – str. 基金代码

  • date

  • threhold – float, default 0.3. 为了计算快速,占比小于千分之三的股票将舍弃

Returns

xalpha.universal.get_fund_peb_range(code, start, end)[source]

获取一段时间的基金历史估值,每周五为频率

Parameters
  • code

  • start

  • end

Returns

xalpha.universal.get_fund_type[source]

given fund code, return unified fund category which is extracted from get_rt(code)[“type”]

Parameters

code

Returns

str.

xalpha.universal.get_fundshare_byjq(code, **kws)[source]
xalpha.universal.get_historical_frombb(code, start=None, end=None, **kws)[source]

https://www.bloomberg.com/ 数据源, 试验性支持。 似乎有很严格的 IP 封禁措施, 且最新数据更新滞后,且国内会被 reset,似乎难以支持 T-1 净值预测。强烈建议从英为或雅虎能找到的标的,不要用彭博源,该 API 只能作为 last resort。

Parameters
  • code

  • start

  • end

  • kws

Returns

xalpha.universal.get_historical_fromcninvesting(curr_id, st_date, end_date, app=False)[source]
xalpha.universal.get_historical_fromesunny(code, start=None, end=None)[source]

易盛商品指数

Parameters
  • code – eg. ESCI000201

  • start – just placeholder

  • end – just placeholder

Returns

xalpha.universal.get_historical_fromft(code, start, end, _type='indices')[source]

finance times 数据

Parameters
  • code

  • start

  • end

Returns

xalpha.universal.get_historical_fromgzindex(code, start, end)[source]

国证指数源

Parameters
  • code

  • start

  • end

Returns

xalpha.universal.get_historical_fromhzindex(code, start, end)[source]

华证指数源

Parameters
  • code

  • start

  • end

Returns

xalpha.universal.get_historical_fromsp(code, start=None, end=None, region='us', **kws)[source]

标普官网数据源

Parameters
  • code

  • start

  • end

  • kws

Returns

xalpha.universal.get_historical_fromxq(code, count, type_='before', full=False)[source]
Parameters
  • code

  • count

  • type – str. normal, before, after

  • full

Returns

xalpha.universal.get_historical_fromycharts(code, start, end, category, metric)[source]
xalpha.universal.get_historical_fromyh(code, start=None, end=None)[source]

雅虎财经数据源,支持数据丰富,不限于美股。但存在部分历史数据缺失 NAN 或者周末进入交易日的现象,可能数据需要进一步清洗和处理。

Parameters
  • code

  • start

  • end

Returns

xalpha.universal.get_historical_fromzzindex(code, start, end=None)[source]

中证指数源

Parameters
  • code

  • start

  • end

Returns

xalpha.universal.get_index_weight_range(code, start, end)
xalpha.universal.get_investing_id[source]
xalpha.universal.get_macro(table, start, end, datecol='stat_year')[source]
xalpha.universal.get_newest_netvalue(code)[source]

防止天天基金总量 API 最新净值更新不及时,获取基金最新公布净值及对应日期, depracated, use get_rt(“F501018”) instead

Parameters

code – six digits string for fund.

Returns

netvalue, %Y-%m-%d

xalpha.universal.get_newest_netvalue_ttl
xalpha.universal.get_now(code, _from=None, double_check=False, double_check_threhold=0.005, handler=True)

universal fetcher for realtime price of literally everything.

Parameters
  • code – str. 规则同 get_daily(). 需要注意场外基金和外汇中间价是不支持实时行情的,因为其每日只有一个报价。对于 investing 的数据源,只支持网址格式代码。

  • _from – Optional[str]. can be one of “xueqiu”, “investing”. Only used for debug to enfore data source. For common use, _from can be chosed automatically based on code in the run time.

  • double_check – Optional[bool], default False. 如果设为 True,只适用于 A 股,美股,港股实时行情,会通过至少两个不同的数据源交叉验证,确保正确。 适用于需要自动交易等情形,防止实时数据异常。

  • handler – bool. Default True. 若为 False,则 handler 钩子失效,用于钩子函数中的嵌套。

Returns

Dict[str, Any]. 包括 “name”, “current”, “percent” 三个必有项和 “current_ext”(盘后价格), “currency” (计价货币), “market” (发行市场), “time”(记录时间) 可能为 None 的选项。

xalpha.universal.get_peb(index, date=None, table=False)[source]

获取指数在指定日期的 pe 和 pb。采用当时各公司的最新财报和当时的指数成分股权重加权计算。

Parameters
  • index – str. 聚宽形式的指数代码。

  • date – str. %Y-%m-%d

  • table – Optioanl[bool], default False. True 时返回整个计算的 DataFrame,用于 debug。

Returns

Dict[str, float]. 包含 pe 和 pb 值的字典。

xalpha.universal.get_peb_range(code, start, end)

获取指定指数一段时间内的 pe pb 值。

Parameters
  • code – 聚宽形式指数代码。

  • start

  • end

Returns

pd.DataFrame

xalpha.universal.get_portfolio_fromttjj(code, start=None, end=None)[source]
xalpha.universal.get_realtime(code, _from=None, double_check=False, double_check_threhold=0.005, handler=True)

universal fetcher for realtime price of literally everything.

Parameters
  • code – str. 规则同 get_daily(). 需要注意场外基金和外汇中间价是不支持实时行情的,因为其每日只有一个报价。对于 investing 的数据源,只支持网址格式代码。

  • _from – Optional[str]. can be one of “xueqiu”, “investing”. Only used for debug to enfore data source. For common use, _from can be chosed automatically based on code in the run time.

  • double_check – Optional[bool], default False. 如果设为 True,只适用于 A 股,美股,港股实时行情,会通过至少两个不同的数据源交叉验证,确保正确。 适用于需要自动交易等情形,防止实时数据异常。

  • handler – bool. Default True. 若为 False,则 handler 钩子失效,用于钩子函数中的嵌套。

Returns

Dict[str, Any]. 包括 “name”, “current”, “percent” 三个必有项和 “current_ext”(盘后价格), “currency” (计价货币), “market” (发行市场), “time”(记录时间) 可能为 None 的选项。

xalpha.universal.get_ri_status_ttl
xalpha.universal.get_rmb(start=None, end=None, prev=360, currency='USD/CNY')[source]

获取人民币汇率中间价, 该 API 官网数据源,稳定性很差

Parameters
  • start

  • end

  • prev

  • currency

Returns

pd.DataFrame

xalpha.universal.get_rmb_ttl
xalpha.universal.get_rt(code, _from=None, double_check=False, double_check_threhold=0.005, handler=True)[source]

universal fetcher for realtime price of literally everything.

Parameters
  • code – str. 规则同 get_daily(). 需要注意场外基金和外汇中间价是不支持实时行情的,因为其每日只有一个报价。对于 investing 的数据源,只支持网址格式代码。

  • _from – Optional[str]. can be one of “xueqiu”, “investing”. Only used for debug to enfore data source. For common use, _from can be chosed automatically based on code in the run time.

  • double_check – Optional[bool], default False. 如果设为 True,只适用于 A 股,美股,港股实时行情,会通过至少两个不同的数据源交叉验证,确保正确。 适用于需要自动交易等情形,防止实时数据异常。

  • handler – bool. Default True. 若为 False,则 handler 钩子失效,用于钩子函数中的嵌套。

Returns

Dict[str, Any]. 包括 “name”, “current”, “percent” 三个必有项和 “current_ext”(盘后价格), “currency” (计价货币), “market” (发行市场), “time”(记录时间) 可能为 None 的选项。

xalpha.universal.get_rt_from_ft(code, _type='indices')[source]
xalpha.universal.get_rt_from_sina(code)[source]
xalpha.universal.get_rt_from_ttjj(code)[source]
xalpha.universal.get_rt_from_ttjj_ttl
xalpha.universal.get_rt_from_ycharts(code)[source]
xalpha.universal.get_sh_status_ttl
xalpha.universal.get_stock_peb_range(code, start, end, wrapper=False)[source]

获取股票历史 pe pb

Parameters
  • code

  • start

  • end

Returns

xalpha.universal.get_sw_from_jq(code, start=None, end=None, **kws)[source]
Parameters
  • code – str. eg. 801180 申万行业指数

  • start

  • end

  • kws

Returns

xalpha.universal.get_sz_fs_ttl
xalpha.universal.get_sz_status_ttl
xalpha.universal.get_teb(code, date)[source]
xalpha.universal.get_teb_range(code, start, end, freq='W-FRI')[source]
xalpha.universal.get_token()[source]

获取雪球的验权 token,匿名也可获取,而且似乎永远恒定(大时间范围内会改变)

Returns

xalpha.universal.get_token_ttl
xalpha.universal.get_xueqiu_rt(code, token='a664afb60c7036c7947578ac1a5860c4cfb6b3b5')[source]
xalpha.universal.has_weekday(start, end)[source]
xalpha.universal.lru_cache_time(ttl=None, maxsize=None)[source]

TTL support on lru_cache

Parameters
  • ttl – float or int, seconds

  • maxsize – int, maxsize for lru_cache

Returns

xalpha.universal.make_ft_url(code, _type='indices')[source]
Parameters
  • code

  • _type – indices, commodities, currencies, funds, equities, bonds

Returns

xalpha.universal.prettify(df)[source]
xalpha.universal.reset_cache()[source]

clear all cache of daily data in memory.

Returns

None.

xalpha.universal.save_backend(key, df, mode='a', header=False)[source]
xalpha.universal.set_backend(**ioconf)[source]

设定 xalpha get_daily 函数的缓存后端,默认为内存。 ioconf 参数设置可参考 cachedio()

Parameters

ioconf

Returns

None.

xalpha.universal.set_handler(method='daily', f=None)[source]

get_daily, get_barget_rt 设置 hook,优先按照函数 f 进行处理,若返回 None,再按一般情形处理

Parameters
  • method – str. daily, rt, bar

  • f – func, default None.

Returns

None

xalpha.universal.tomorrow_ts()[source]
xalpha.universal.ts2pdts(ts)[source]
xalpha.universal.ttjjcode[source]

将天天基金的持仓股票代码或其他来源的代码标准化

Parameters

code – str.

Returns

str.

class xalpha.universal.vinfo(code, name=None, start=None, end=None, rate=0, col='close', **kws)[source]

Bases: xalpha.info.basicinfo, xalpha.indicator.indicator

vinfo is an info like class wrapper for get_daily, it behaves like info

__init__(code, name=None, start=None, end=None, rate=0, col='close', **kws)[source]

Initialize self. See help(type(self)) for accurate signature.

Indices and tables