xalpha package

xalpha.backtest module

xalpha.cons module

basic constants and utility functions

xalpha.cons._date_check(dtobj, check=False)[source]
xalpha.cons._float(n)[source]
xalpha.cons.avail_dates(dtlist, future=False)[source]

make every day in the list the next open day

Parameters:
  • dtlist – datetime obj list

  • future – bool, default False, indicating the latest day in the list is yesterday

Returns:

datetime obj list

xalpha.cons.calendar_selfcheck()[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.pd_get_week(series)[source]

version aware week getting for pandas series

xalpha.cons.pd_to_datetime(target, **kwargs)[source]

version aware pd.to_datetime, use format=”mixed” for pandas >= 2.0

xalpha.cons.pd_valid_freq(freq)[source]

version aware frequency string for pandas date_range. Converts modern aliases like ‘ME’, ‘QE’, ‘YE’ to legacy ‘M’, ‘Q’, ‘Y’ on unsupported pandas versions.

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

xalpha.indicator module

xalpha.info module

xalpha.multiple module

xalpha.policy module

modules for policy making: generate status table for simple backtesting

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

Bases: 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='2026-06-11', totmoney=100000)[source]

Bases: 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='2026-06-11', totmoney=100000)[source]
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='2026-06-11', totmoney=100000)[source]

Bases: 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='2026-06-11', totmoney=100000)[source]
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='2026-06-11', totmoney=100000)[source]

Bases: 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='2026-06-11', totmoney=100000)[source]
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='2026-06-11', totmoney=100000)[source]

Bases: 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='2026-06-11', totmoney=100000)[source]
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: 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]
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: 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

class xalpha.policy.scheduled_window(infoobj, totmoney, times, piece, window=7, window_dist=1, method='AVG')[source]

Bases: scheduled

在定投点前面设置一个滑动窗口,根据滑动窗口中的净值与当前净值进行比较,满足一定条件则进行定投。 通常用于跌了多投,跌越多投越多;涨了少投,涨越多投越少。

__init__(infoobj, totmoney, times, piece, window=7, window_dist=1, method='AVG')[source]
Parameters:
  • window – window width, means the total trading days in the window.

  • window_dist – the total trading days after window’s end date and up to current date. Sometimes we only use the data some days before, so we need window_dist to control the distance between window and current date. eg. the window is [2021-01-04, 2021-01-05, 2021-01-06], current date is 2021-01-07. In this example, the window width is 3, because there are three trading days in this window, the window dist for current date is 1, because there is only one trading date after 2021-01-06 and up to 2021-01-07.

  • piece – list of tuples, eg.[(-3,2),(0,1),(3,0.5)]. In this example, it means if the fund netvalue rise in the range of (-100%, -3%], we will buy 2*totmoney, if the fund netvalue rise in the range of (-3%, 0%], we will buy 1*totmoney, if the fund netvalue rise in the range of (0%, 3%], we will buy 0.5*totmoney, if the fund netvalue rise in the range of (3%, +infinity), then no purchase happen at all.

  • method – MAX, MIN, AVG, default value is AVG. It means how we process the data in the window.

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

xalpha.realtime module

xalpha.record module

module for status table IO

xalpha.record.IRecord

alias of irecord

xalpha.record.Record

alias of record

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

Bases: 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]
filter(code, start=None, end=None)[source]
sellout(date=datetime.datetime(2026, 6, 11, 21, 40, 1, 974656), 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%。

3. 账单上自定义申购费和赎回费,小数点后第三位的 5 标记,代表了该数据费用是自定义的。注意这和 -0.005 代表全部卖出并不冲突,其原因是自定义费用, 前边肯定不全为 0。第三位 5 之后,代表了 1% 位。也即 -51.28515 意义是赎回 51.28 份,赎回费为 1.5%. 200.205 代表申购 200.2 元,申购费为0 (因为标记位 5 后没有其他非零数字)。这种自定义通常可用于定期支付型基金的强制卖出(不收赎回费)和基金公司官网申购基金时申购费全免的记录。

关于基金行为的设定,基金份额是四舍五入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 or pd.DataFrame

  • 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]
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(2026, 6, 11, 21, 40, 1, 974623), 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

xalpha.trade module

xalpha.universal module