xalpha package

xalpha.cons module

basic constants and utility functions

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.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.reconnect(tries=5)[source]
xalpha.cons.rget_json(*args, **kws)[source]
xalpha.cons.rpost_json(*args, **kws)[source]
xalpha.cons.today()
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 表中最近的起始时间。 但需要注意,由于拉取的基金净值表,往往在开始几天缺失净值数据,即使使用默认时间也可能无法对齐所有净值数据。 因此建议手动设置起始时间到最近的起始时间一周后左右。

correlation_table(end=datetime.datetime(2020, 3, 28, 0, 0))[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, 3, 28, 0, 0), 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, 3, 28, 0, 0), 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

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.

algorithm_volatility(date=datetime.datetime(2020, 3, 28, 0, 0))[source]
alpha(date=datetime.datetime(2020, 3, 28, 0, 0))[source]
annualized_returns(start, date=datetime.datetime(2020, 3, 28, 0, 0))[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, 3, 28, 0, 0))[source]
benchmark_volatility(date=datetime.datetime(2020, 3, 28, 0, 0))[source]
beta(date=datetime.datetime(2020, 3, 28, 0, 0))[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, 3, 28, 0, 0))[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, 3, 28, 0, 0))[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, 3, 28, 0, 0))[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, 3, 28, 0, 0))[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

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

ratedaily(date=datetime.datetime(2020, 3, 28, 0, 0))[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, 3, 28, 0, 0))[source]
total_annualized_returns(date=datetime.datetime(2020, 3, 28, 0, 0))[source]
total_return(date=datetime.datetime(2020, 3, 28, 0, 0))[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, 3, 28, 0, 0), benchmark=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, 3, 28, 0, 0), col=None, 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

volatility(date=datetime.datetime(2020, 3, 28, 0, 0))[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.info module

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

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

Bases: object

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

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

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 代表记账单上的赎回数目是按金额而非份额的,只能完美支持货币基金。其他净值型基金本质上无法精确到分支持这一选项,因此不开放支持。

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)[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, 记账单数字按金额赎回。

class xalpha.info.fundinfo(code, round_label=0, dividend_label=0, fetch=False, save=False, path='', form='csv')[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’

feedecision(day)[source]

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

Parameters

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

Returns

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

info()[source]

print basic info on the class

shuhui(share, date, rem)[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

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’

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’

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

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

Bases: xalpha.multiple.mul

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’

combsummary(date=datetime.datetime(2020, 3, 28, 0, 0))[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

tot(prop='基金现值', date=datetime.datetime(2020, 3, 28, 0, 0))[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_positions(date=datetime.datetime(2020, 3, 28, 0, 0), vopts=None)[source]

pie chart visualization of positions ratio in combination

v_positions_history(end='2020-03-28', **vkwds)[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')[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, 3, 28, 0, 0), guess=0.1)[source]

xirr rate evauation of the whole invest combination

class xalpha.multiple.mulfix(*fundtradeobj, status=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

unitvalue(date=datetime.datetime(2020, 3, 28, 0, 0))[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-03-28', 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-03-28', 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 – 总钱数,平均分给各个网格买入仓位

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-03-28', 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

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-03-28', 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

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-03-28', 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

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

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

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

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)[source]

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

Parameters

proxy – str. format as “http://user:passwd@host:port” user passwd part can be omitted if not set.

Returns

xalpha.provider.show_providers()[source]

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

Returns

xalpha.realtime module

module for realtime watch and notfication

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, 3, 29, 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

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

xalpha.record module

module for status table IO

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 使用,进行场内交易的整合分析。

filter(code, start=None, end=None)[source]
sellout(date=datetime.datetime(2020, 3, 28, 0, 0), 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.

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, 3, 28, 0, 0), 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

class xalpha.toolbox.Compare(*codes, start='20200101', end='20200328', col='close')[source]

Bases: object

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

corr()[source]

打印相关系数矩阵

Returns

pd.DataFrame

v()[source]

显示日线可视化

Returns

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

Bases: object

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

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'), '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()[source]

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

Returns

v(y='pe')[source]

pe 或 pb 历史可视化

Parameters

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

Returns

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

Bases: xalpha.toolbox.PEBHistory

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

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']

xalpha.trade module

module for trade class

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 现金流表

get_netvalue(date=datetime.datetime(2020, 3, 28, 0, 0))[source]
v_totvalue(end=datetime.datetime(2020, 3, 28, 0, 0), vopts=None)[source]

visualization on the total values daily change of the aim

v_tradecost(start=None, end=datetime.datetime(2020, 3, 28, 0, 0), vopts=None)[source]

visualization giving the average cost line together with netvalue line

Parameters

vopts – global option for line in pyecharts

Returns

pyecharts.line

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

briefdailyreport(date=datetime.datetime(2020, 3, 28, 0, 0))[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, 3, 28, 0, 0))[source]
get_netvalue(date=datetime.datetime(2020, 3, 28, 0, 0))[source]
unitcost(date=datetime.datetime(2020, 3, 28, 0, 0))[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, 3, 28, 0, 0), vopts=None)[source]

visualization on the total values daily change of the aim

v_tradecost(start=None, end=datetime.datetime(2020, 3, 28, 0, 0), vopts=None)[source]

visualization giving the average cost line together with netvalue line

Parameters

vopts – global option for line in pyecharts

Returns

pyecharts.line

v_tradevolume(freq='D')[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, 3, 28, 0, 0), guess=0.1)[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

xalpha.trade.turnoverrate(cftable, end=datetime.datetime(2020, 3, 28, 0, 0))[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')[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, guess=0.1)[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.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, **kws)[source]
xalpha.universal.dstr2dobj(dstr)[source]
xalpha.universal.get_cninvesting(curr_id, st_date, end_date)[source]
xalpha.universal.get_cninvesting_rt(suburl)[source]
xalpha.universal.get_daily(code, start=None, end=None, prev=365, _from=None, wrapper=True, **kws)

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

Parameters
  • code

    str.

    1. 对于沪深市场的股票,指数,ETF,LOF 场内基金,可转债和债券,直接使用其代码,主要开头需要包括 SH 或者 SZ。

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

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

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

    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。

    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

    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

  • 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 enfore data source. For common use, _from can be chosed automatically based on code in the run time.

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

Returns

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

xalpha.universal.get_fund(code)[source]
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 封禁措施, 且最新数据更新滞后,似乎难以支持 T-1 净值预测。强烈建议从英为或雅虎能找到的标的,不要用彭博源,该 API 只能作为 last resort。

Parameters
  • code

  • start

  • end

  • kws

Returns

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

标普官网数据源

Parameters
  • code

  • start

  • end

  • kws

Returns

xalpha.universal.get_historical_fromxq(code, count)[source]
xalpha.universal.get_historical_fromyh(code, start=None, end=None)[source]

雅虎财经数据源,支持数据丰富,不限于美股。但存在部分历史数据确实 NAN 或者周末进入交易日的现象,可能数据需要进一步清洗和处理。

Parameters
  • code

  • start

  • end

Returns

xalpha.universal.get_history(code, prefix='SH', count=365, token='a664afb60c7036c7947578ac1a5860c4cfb6b3b5')[source]
xalpha.universal.get_index_weight_range(code, start, end)
xalpha.universal.get_investing_id(suburl)[source]
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_realtime(code, _from=None, double_check=False, double_check_threhold=0.005)

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 股,美股,港股实时行情,会通过至少两个不同的数据源交叉验证,确保正确。 适用于需要自动交易等情形,防止实时数据异常。

Returns

Dict[str, Any]. 包括 “name”, “current”, “percent” 三个必有项和 “current_ext”(盘后价格), “currency” (计价货币)两个值可能为 None 的选项。

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_rt(code, _from=None, double_check=False, double_check_threhold=0.005)[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 股,美股,港股实时行情,会通过至少两个不同的数据源交叉验证,确保正确。 适用于需要自动交易等情形,防止实时数据异常。

Returns

Dict[str, Any]. 包括 “name”, “current”, “percent” 三个必有项和 “current_ext”(盘后价格), “currency” (计价货币)两个值可能为 None 的选项。

xalpha.universal.get_rt_from_sina(code)[source]
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_teb(code, date)[source]
xalpha.universal.get_teb_range(code, start, end)[source]
xalpha.universal.get_token()[source]

获取雪球的验权 token,匿名也可获取,而且似乎永远恒定

Returns

xalpha.universal.get_xueqiu_rt(code, token='a664afb60c7036c7947578ac1a5860c4cfb6b3b5')[source]
xalpha.universal.has_weekday(start, end)[source]
xalpha.universal.prettify(df)[source]
xalpha.universal.reset_cache()[source]

clear all cache of daily data in memory.

Returns

None.

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

设定 xalpha get_daily 函数的缓存后端,默认为内存。 ioconf 参数设置可参考 cachedio()

Parameters

ioconf

Returns

None.

xalpha.universal.today_obj()[source]
xalpha.universal.tomorrow_ts()[source]
xalpha.universal.ts2pdts(ts)[source]