api
errors
special
¶
trade
special
¶
base
¶
ErrorCodes (IntEnum)
¶
An enumeration.
Source code in coretypes/errors/trade/base.py
class ErrorCodes(IntEnum):
Unknown = 1000
ClientGeneric = 2000
ClientBadParams = 2001
ClientAccountConflict = 2002
ClientAccountStopped = 2003
ClientTimeRewind = 2004
ServerGeneric = 3000
ServerNoDataForMatch = 3001
ServerNoData = 3002
TradeGeneric = 4000
TradeNoCash = 4001
TradeVolNotEnough = 4002
TradeReachBuyLimit = 4003
TradeReachSellLimit = 4004
TradeNoPosition = 4005
TradePirceNotMeet = 4006
TradeError (Exception)
¶
交易错误基类
在交易和回测过程产生的各种异常,包括客户端参数错误、账户错误、交易限制等。由于需要本异常信息可能需要从服务器传递到客户端并重建,所以需要有串行化能力(使用json),以及需要传递callstack trace.
Source code in coretypes/errors/trade/base.py
class TradeError(Exception):
"""交易错误基类
在交易和回测过程产生的各种异常,包括客户端参数错误、账户错误、交易限制等。由于需要本异常信息可能需要从服务器传递到客户端并重建,所以需要有串行化能力(使用json),以及需要传递callstack trace.
"""
error_code = ErrorCodes.Unknown
def __init__(self, msg: str, with_stack: bool = False):
self.error_msg = msg
self.stack = None
if with_stack:
buffer = io.StringIO()
traceback.print_stack(file=buffer, limit=20)
stack = buffer.getvalue()
# last 2 lines are print_stack and etc.
self.stack = "\n".join(stack.split("\n")[:-2])
@classmethod
def parse_msg(cls, msg: str) -> dict:
raise NotImplementedError
@classmethod
def from_json(cls, e: dict):
"""从json字符串中重建错误对象"""
error_code = e["error_code"]
error_msg = e["msg"]
stack = e.get("stack")
for klass in cls.__subclasses__():
if klass.error_code.value == error_code:
try:
obj = klass(**klass.parse_msg(error_msg))
if stack is not None:
obj.stack = stack
return obj
except Exception:
te = TradeError(f"异常对象构建时出错。原错误代码:{error_code}, 原错误消息:{error_msg}")
te.stack = stack
return te
else:
te = TradeError(f"未知错误类型。错误代码: {error_code}, 错误消息为{error_msg}")
te.stack = stack
return te
def as_json(self):
"""将对象串行化为json字符串,以遍可以通过网络传输"""
if self.stack is not None:
return {
"error_code": self.error_code.value,
"msg": self.error_msg,
"stack": self.stack,
}
else:
return {
"error_code": self.error_code.value,
"msg": self.error_msg,
}
def __str__(self):
return f"{self.error_code}: {self.error_msg}"
as_json(self)
¶
将对象串行化为json字符串,以遍可以通过网络传输
Source code in coretypes/errors/trade/base.py
def as_json(self):
"""将对象串行化为json字符串,以遍可以通过网络传输"""
if self.stack is not None:
return {
"error_code": self.error_code.value,
"msg": self.error_msg,
"stack": self.stack,
}
else:
return {
"error_code": self.error_code.value,
"msg": self.error_msg,
}
from_json(e)
classmethod
¶
从json字符串中重建错误对象
Source code in coretypes/errors/trade/base.py
@classmethod
def from_json(cls, e: dict):
"""从json字符串中重建错误对象"""
error_code = e["error_code"]
error_msg = e["msg"]
stack = e.get("stack")
for klass in cls.__subclasses__():
if klass.error_code.value == error_code:
try:
obj = klass(**klass.parse_msg(error_msg))
if stack is not None:
obj.stack = stack
return obj
except Exception:
te = TradeError(f"异常对象构建时出错。原错误代码:{error_code}, 原错误消息:{error_msg}")
te.stack = stack
return te
else:
te = TradeError(f"未知错误类型。错误代码: {error_code}, 错误消息为{error_msg}")
te.stack = stack
return te
client
¶
AccountConflictError (TradeError)
¶
账户冲突异常
Source code in coretypes/errors/trade/client.py
class AccountConflictError(TradeError):
"""账户冲突异常"""
error_code = ErrorCodes.ClientAccountConflict
def __init__(self, account: str, with_stack: bool = False):
super().__init__(f"账户名{account}已被占用", with_stack=with_stack)
@classmethod
def parse_msg(cls, account: str) -> dict:
m = re.match(r"账户名(.*?)已被占用", account)
return {"account": m.group(1)} # type: ignore
AccountStoppedError (TradeError)
¶
账户已停止异常
Source code in coretypes/errors/trade/client.py
class AccountStoppedError(TradeError):
"""账户已停止异常"""
error_code = ErrorCodes.ClientAccountStopped
def __init__(self, bid_time: Frame, stop_time: Frame, with_stack: bool = False):
super().__init__(f"下单时间为{bid_time},而账户已于{stop_time}冻结。", with_stack=with_stack)
@classmethod
def parse_msg(cls, msg: str) -> dict:
m = re.match(r"下单时间为(.*?),而账户已于(.*?)冻结。", msg)
return {"bid_time": m.group(1), "stop_time": m.group(2)} # type: ignore
BadParamsError (TradeError)
¶
客户端参数错误异常
Source code in coretypes/errors/trade/client.py
class BadParamsError(TradeError):
"""客户端参数错误异常"""
error_code = ErrorCodes.ClientBadParams
def __init__(self, msg: str, with_stack:bool = False):
super().__init__(msg, with_stack)
@classmethod
def parse_msg(cls, msg: str) -> dict:
return {"msg": msg}
TimeRewindError (TradeError)
¶
客户端时间回退异常
Source code in coretypes/errors/trade/client.py
class TimeRewindError(TradeError):
"""客户端时间回退异常"""
error_code = ErrorCodes.ClientTimeRewind
def __init__(self, cur: Frame, last_trade_time: Frame, with_stack: bool = False):
super().__init__(
"委托时间必须递增出现。当前{cur}, 前一个委托时间{last_trade_time}", with_stack=with_stack
)
@classmethod
def parse_msg(cls, msg: str) -> dict:
m = re.match(r"委托时间必须递增出现。当前(.*?), 前一个委托时间(.*?)", msg)
return {
"cur": m.group(1), # type: ignore
"last_trade_time": m.group(2), # type: ignore
}
entrust
¶
BuylimitError (TradeError)
¶
不允许涨停板上买入
Source code in coretypes/errors/trade/entrust.py
class BuylimitError(TradeError):
"""不允许涨停板上买入"""
error_code = ErrorCodes.TradeReachBuyLimit
def __init__(self, security: str, time: Frame, with_stack: bool = False):
super().__init__(f"不能在涨停板上买入{security}, {time}", with_stack=with_stack)
@classmethod
def parse_msg(cls, msg: str) -> dict:
m = re.match(r"不能在涨停板上买入(.*?), (.*?)", msg)
return {
"security": m.group(1), # type: ignore
"time": m.group(2), # type: ignore
}
CashError (TradeError)
¶
账户余额不足
Source code in coretypes/errors/trade/entrust.py
class CashError(TradeError):
"""账户余额不足"""
error_code = ErrorCodes.TradeNoCash
def __init__(
self,
account: str,
required: float,
available: float,
with_stack: bool = False,
):
super().__init__(
f"账户{account}资金不足, 需要{required}, 当前{available}", with_stack=with_stack
)
@classmethod
def parse_msg(cls, msg: str) -> dict:
m = re.match(r"账户(.*?)资金不足, 需要(\d+(\.\d+)?), 当前(\d+(\.\d+)?)", msg)
return {
"account": m.group(1), # type: ignore
"required": float(m.group(2)), # type: ignore
"available": float(m.group(3)), # type: ignore
}
GenericError (TradeError)
¶
原因不明的委托错误
Source code in coretypes/errors/trade/entrust.py
class GenericError(TradeError):
"""原因不明的委托错误"""
error_code = ErrorCodes.TradeGeneric
def __init__(self, security: str, time: Frame, with_stack: bool=False):
super().__init__(f"委托{security}在{time}发生未知错误", with_stack=with_stack)
@classmethod
def parse_msg(cls, msg: str) -> dict:
m = re.match(r"委托(.*?)在(.*?)发生未知错误", msg)
return {
"security": m.group(1), # type: ignore
"time": m.group(2), # type: ignore
}
PositionError (TradeError)
¶
security
在期间没有持仓时发出卖出指令
Source code in coretypes/errors/trade/entrust.py
class PositionError(TradeError):
"""`security`在期间没有持仓时发出卖出指令"""
error_code = ErrorCodes.TradeNoPosition
def __init__(self, security: str, time: Frame, with_stack: bool = False):
super().__init__(f"{security}在{time}期间没有持仓", with_stack=with_stack)
@classmethod
def parse_msg(cls, msg: str) -> dict:
m = re.match(r"(.*?)在(.*?)期间没有持仓", msg)
return {
"security": m.group(1), # type: ignore
"time": m.group(2), # type: ignore
}
PriceNotMeet (TradeError)
¶
security
现价未达到委托价,无法成交
Source code in coretypes/errors/trade/entrust.py
class PriceNotMeet(TradeError):
"""`security`现价未达到委托价,无法成交"""
error_code = ErrorCodes.TradePirceNotMeet
def __init__(
self, security: str, price: float, order_time: Frame, with_stack: bool = False
):
super().__init__(
f"{security}在{order_time}之后未达到委托价:{price}", with_stack=with_stack
)
@classmethod
def parse_msg(cls, msg: str) -> dict:
m = re.match(r"(.*?)在(.*?)之后未达到委托价:(\d+(\.\d+)?)", msg)
return {
"security": m.group(1), # type: ignore
"order_time": m.group(2), # type: ignore
"price": float(m.group(3)), # type: ignore
}
SellLimitError (TradeError)
¶
不允许跌停板上卖出
Source code in coretypes/errors/trade/entrust.py
class SellLimitError(TradeError):
"""不允许跌停板上卖出"""
error_code = ErrorCodes.TradeReachSellLimit
def __init__(self, security: str, time: Frame, with_stack: bool = False):
super().__init__(f"不能在跌停板上卖出{security}, {time}", with_stack=with_stack)
@classmethod
def parse_msg(cls, msg: str) -> dict:
m = re.match(r"不能在跌停板上卖出(.*?), (.*?)", msg)
return {
"security": m.group(1), # type: ignore
"time": m.group(2), # type: ignore
}
VolumeNotMeet (TradeError)
¶
security
委托价达到,但成交量为零。
Source code in coretypes/errors/trade/entrust.py
class VolumeNotMeet(TradeError):
"""`security`委托价达到,但成交量为零。"""
error_code = ErrorCodes.TradeVolNotEnough
def __init__(self, security: str, price: float, with_stack: bool = False):
super().__init__(f"{security}委托价{price}达到,但成交量为零", with_stack=with_stack)
@classmethod
def parse_msg(cls, msg: str) -> dict:
m = re.match(r"(.*?)委托价(\d+(\.\d+)?)达到,但成交量为零", msg)
return {
"security": m.group(1), # type: ignore
"price": float(m.group(2)), # type: ignore
}
server
¶
NoData (TradeError)
¶
服务器无数据异常
Source code in coretypes/errors/trade/server.py
class NoData(TradeError):
"""服务器无数据异常"""
error_code = ErrorCodes.ServerNoData
def __init__(self, security: str, time: Frame, with_stack: bool = False):
super().__init__(
f"获取{security}在{time}的行情数据失败,请检查日期是否为交易日,或者当天是否停牌", with_stack=with_stack
)
@classmethod
def parse_msg(cls, msg: str) -> dict:
m = re.match(r"获取(.*?)在(.*?)的行情数据失败,请检查日期是否为交易日,或者当天是否停牌", msg)
return {
"security": m.group(1), # type: ignore
"time": m.group(2), # type: ignore
}
NoDataForMatch (TradeError)
¶
服务器无数据匹配异常
Source code in coretypes/errors/trade/server.py
class NoDataForMatch(TradeError):
"""服务器无数据匹配异常"""
error_code = ErrorCodes.ServerNoDataForMatch
def __init__(self, security: str, order_time: Frame, with_stack: bool = False):
super().__init__(f"没有匹配到{security}在{order_time}的成交数据", with_stack=with_stack)
@classmethod
def parse_msg(cls, msg: str) -> dict:
m = re.match(r"没有匹配到(.*?)在(.*?)的成交数据", msg)
return {
"security": m.group(1), # type: ignore
"order_time": m.group(2), # type: ignore
}
quote_fetcher
¶
Interface for quotes worker
QuotesFetcher (ABC)
¶
Source code in coretypes/quote_fetcher.py
class QuotesFetcher(ABC):
async def get_quota(self) -> int:
"""获取接口当前可用的quota
Raises:
NotImplementedError: [description]
Returns:
int: [description]
"""
raise NotImplementedError
async def get_security_list(self) -> numpy.ndarray:
"""fetch security list from server.
The returned list is a numpy.ndarray, which each elements should look like:
code display_name name start_date end_date type
000001.XSHE 平安银行 PAYH 1991-04-03 2200-01-01 stock
000002.XSHE 万科A WKA 1991-01-29 2200-01-01 stock
all fields are string type
Returns:
numpy.ndarray: [description]
"""
raise NotImplementedError
async def get_bars(
self,
sec: str,
end: Frame,
n_bars: int,
frame_type: FrameType,
allow_unclosed=True,
) -> numpy.ndarray:
"""取n个单位的k线数据。
k线周期由frame_type指定。最后结束周期为end。股票停牌期间的数据会使用None填充。
Args:
sec (str): 证券代码
end (Frame):
n_bars (int):
frame_type (FrameType):
allow_unclosed (bool): 为真时,当前未结束的帧数据也获取
Returns:
a numpy.ndarray, with each element is:
'frame': datetime.date or datetime.datetime, depends on frame_type.
Denotes which time frame the data
belongs .
'open, high, low, close': float
'volume': double
'amount': the buy/sell amount in total, double
'factor': float, may exist or not
"""
raise NotImplementedError
async def get_price(
self,
sec: Union[List, str],
end_at: Union[str, datetime.datetime],
n_bars: int,
frame_type: str,
) -> Dict[str, numpy.recarray]:
raise NotImplementedError
async def create_instance(self, **kwargs):
raise NotImplementedError
async def get_all_trade_days(self):
"""返回交易日历。不同的服务器可能返回的时间跨度不一样,但相同跨度内的时间应该一样。对已
经过去的交易日,可以用上证指数来验证。
"""
raise NotImplementedError
async def get_valuation(
self, code: Union[str, List[str]], day: Frame
) -> numpy.ndarray:
"""读取code指定的股票在date指定日期的市值数据。
返回数据包括:
code: 股票代码
day: 日期
captialization: 总股本
circulating_cap: 流通股本(万股)
market_cap: 总市值(亿元)
circulating_market_cap: 流通市值(亿元)
turnover_ration: 换手率(%)
pe_ratio: 市盈率(PE,TTM)每股市价为每股收益的倍数,反映投资人对每元净利润所愿支付的价
格,用来估计股票的投资报酬和风险
pe_ratio_lyr: 市盈率(PE),以上一年度每股盈利计算的静态市盈率. 股价/最近年度报告EPS
pb_ratio: 市净率(PB)
ps_ratio: 市销率(PS)
pcf_ratio: 市现率(PCF)
Args:
code (Union[str, List[str]]): [description]
day (Frame): [description]
Returns:
numpy.ndarray: [description]
"""
raise NotImplementedError
async def get_fund_list(self, codes: Union[str, List[str]] = None) -> numpy.ndarray:
"""
获取所有的基金基本信息
Args:
codes (Union[str, List[str]]): [description]
Returns:
np.array: [基金的基本信息]
"""
raise NotImplementedError
async def get_fund_portfolio_stock(
self, codes: Union[str, List[str]], pub_date: Union[str, datetime.date] = None
) -> numpy.array:
raise NotImplementedError
async def get_fund_net_value(
self,
codes: Union[str, List[str]],
day: datetime.date = None,
) -> numpy.array:
raise NotImplementedError
async def get_fund_share_daily(
self, codes: Union[str, List[str]] = None, day: datetime.date = None
) -> numpy.array:
raise NotImplementedError
@deprecation.deprecated(
deprecated_in="0.2",
removed_in="0.3",
current_version=__version__,
details="Use get_quota instead",
)
async def get_query_count(self):
"""查询当日剩余可调用数据条数"""
raise NotImplementedError
get_all_trade_days(self)
async
¶
返回交易日历。不同的服务器可能返回的时间跨度不一样,但相同跨度内的时间应该一样。对已 经过去的交易日,可以用上证指数来验证。
Source code in coretypes/quote_fetcher.py
async def get_all_trade_days(self):
"""返回交易日历。不同的服务器可能返回的时间跨度不一样,但相同跨度内的时间应该一样。对已
经过去的交易日,可以用上证指数来验证。
"""
raise NotImplementedError
get_bars(self, sec, end, n_bars, frame_type, allow_unclosed=True)
async
¶
取n个单位的k线数据。
k线周期由frame_type指定。最后结束周期为end。股票停牌期间的数据会使用None填充。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sec |
str |
证券代码 |
required |
end |
Frame |
required | |
n_bars |
int |
required | |
frame_type |
FrameType |
required | |
allow_unclosed |
bool |
为真时,当前未结束的帧数据也获取 |
True |
Returns:
Type | Description |
---|---|
a numpy.ndarray, with each element is |
'frame': datetime.date or datetime.datetime, depends on frame_type. Denotes which time frame the data belongs . 'open, high, low, close': float 'volume': double 'amount': the buy/sell amount in total, double 'factor': float, may exist or not |
Source code in coretypes/quote_fetcher.py
async def get_bars(
self,
sec: str,
end: Frame,
n_bars: int,
frame_type: FrameType,
allow_unclosed=True,
) -> numpy.ndarray:
"""取n个单位的k线数据。
k线周期由frame_type指定。最后结束周期为end。股票停牌期间的数据会使用None填充。
Args:
sec (str): 证券代码
end (Frame):
n_bars (int):
frame_type (FrameType):
allow_unclosed (bool): 为真时,当前未结束的帧数据也获取
Returns:
a numpy.ndarray, with each element is:
'frame': datetime.date or datetime.datetime, depends on frame_type.
Denotes which time frame the data
belongs .
'open, high, low, close': float
'volume': double
'amount': the buy/sell amount in total, double
'factor': float, may exist or not
"""
raise NotImplementedError
get_fund_list(self, codes=None)
async
¶
获取所有的基金基本信息
Parameters:
Name | Type | Description | Default |
---|---|---|---|
codes |
Union[str, List[str]] |
[description] |
None |
Returns:
Type | Description |
---|---|
np.array |
[基金的基本信息] |
Source code in coretypes/quote_fetcher.py
async def get_fund_list(self, codes: Union[str, List[str]] = None) -> numpy.ndarray:
"""
获取所有的基金基本信息
Args:
codes (Union[str, List[str]]): [description]
Returns:
np.array: [基金的基本信息]
"""
raise NotImplementedError
get_query_count(self)
async
¶
查询当日剩余可调用数据条数
.. deprecated:: 0.2 This will be removed in 0.3. Use get_quota instead
Source code in coretypes/quote_fetcher.py
@deprecation.deprecated(
deprecated_in="0.2",
removed_in="0.3",
current_version=__version__,
details="Use get_quota instead",
)
async def get_query_count(self):
"""查询当日剩余可调用数据条数"""
raise NotImplementedError
get_quota(self)
async
¶
获取接口当前可用的quota
Exceptions:
Type | Description |
---|---|
NotImplementedError |
[description] |
Returns:
Type | Description |
---|---|
int |
[description] |
Source code in coretypes/quote_fetcher.py
async def get_quota(self) -> int:
"""获取接口当前可用的quota
Raises:
NotImplementedError: [description]
Returns:
int: [description]
"""
raise NotImplementedError
get_security_list(self)
async
¶
fetch security list from server. The returned list is a numpy.ndarray, which each elements should look like: code display_name name start_date end_date type 000001.XSHE 平安银行 PAYH 1991-04-03 2200-01-01 stock 000002.XSHE 万科A WKA 1991-01-29 2200-01-01 stock
all fields are string type
Returns:
Type | Description |
---|---|
numpy.ndarray |
[description] |
Source code in coretypes/quote_fetcher.py
async def get_security_list(self) -> numpy.ndarray:
"""fetch security list from server.
The returned list is a numpy.ndarray, which each elements should look like:
code display_name name start_date end_date type
000001.XSHE 平安银行 PAYH 1991-04-03 2200-01-01 stock
000002.XSHE 万科A WKA 1991-01-29 2200-01-01 stock
all fields are string type
Returns:
numpy.ndarray: [description]
"""
raise NotImplementedError
get_valuation(self, code, day)
async
¶
读取code指定的股票在date指定日期的市值数据。
返回数据包括: code: 股票代码 day: 日期 captialization: 总股本 circulating_cap: 流通股本(万股) market_cap: 总市值(亿元) circulating_market_cap: 流通市值(亿元) turnover_ration: 换手率(%) pe_ratio: 市盈率(PE,TTM)每股市价为每股收益的倍数,反映投资人对每元净利润所愿支付的价 格,用来估计股票的投资报酬和风险 pe_ratio_lyr: 市盈率(PE),以上一年度每股盈利计算的静态市盈率. 股价/最近年度报告EPS pb_ratio: 市净率(PB) ps_ratio: 市销率(PS) pcf_ratio: 市现率(PCF)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
code |
Union[str, List[str]] |
[description] |
required |
day |
Frame |
[description] |
required |
Returns:
Type | Description |
---|---|
numpy.ndarray |
[description] |
Source code in coretypes/quote_fetcher.py
async def get_valuation(
self, code: Union[str, List[str]], day: Frame
) -> numpy.ndarray:
"""读取code指定的股票在date指定日期的市值数据。
返回数据包括:
code: 股票代码
day: 日期
captialization: 总股本
circulating_cap: 流通股本(万股)
market_cap: 总市值(亿元)
circulating_market_cap: 流通市值(亿元)
turnover_ration: 换手率(%)
pe_ratio: 市盈率(PE,TTM)每股市价为每股收益的倍数,反映投资人对每元净利润所愿支付的价
格,用来估计股票的投资报酬和风险
pe_ratio_lyr: 市盈率(PE),以上一年度每股盈利计算的静态市盈率. 股价/最近年度报告EPS
pb_ratio: 市净率(PB)
ps_ratio: 市销率(PS)
pcf_ratio: 市现率(PCF)
Args:
code (Union[str, List[str]]): [description]
day (Frame): [description]
Returns:
numpy.ndarray: [description]
"""
raise NotImplementedError
types
¶
Zillionare中要用到的核心数据类型都定义在此模块中。注意部分定义仅能用作Type Annotation,比如BarsArray等别名。它们通常以大写字母开头
BarsArray
¶
行情数据(包含列frame, open, high, low, close, volume, amount, factor)数组
BarsPanel
¶
带证券代码的行情数据数组
BarsWithLimitArray
¶
带涨跌停价(high_limit, low_limit)的行情数据数组
Frame
¶
包含日期date和时间datetime的联合类型
LimitPriceOnlyBarsArray
¶
仅包括日期、代码、涨跌停价的的行情数据数组
bars_cols
¶
行情数据列名数组,即[frame, open, high, low, close, volume, amount, factor]
bars_dtype
¶
行情数据元类型,包括字段(frame, open, high, low, close, volume, amount, factor)
bars_dtype_with_code
¶
带证券代码的行情数据元类型,在bars_dtype基础上增加了code字段
bars_with_limit_cols
¶
带涨跌停价的行情数据列名数组,即[frame, open, high, low, close, volume, amount, factort high_limit, low_limit]
bars_with_limit_dtype
¶
带涨跌停价格的行情数据元类型,包含frame, open, high, low, close, volume, amount, factort high_limit, low_limit
limit_price_only_dtype
¶
只包含涨跌停价的行情数据元类型,即frame, code, high_limit, low_limit
security_info_dtype
¶
证券信息类型,包括code, alias, name, ipo, end, type字段
FrameType (Enum)
¶
对证券交易中K线周期的封装。提供了以下对应周期:
周期 | 字符串 | 类型 | 数值 |
---|---|---|---|
年线 | 1Y | FrameType.YEAR | 10 |
季线 | 1Q | FrameType.QUARTER | 9 |
月线 | 1M | FrameType.MONTH | 8 |
周线 | 1W | FrameType.WEEK | 7 |
日线 | 1D | FrameType.DAY | 6 |
60分钟线 | 60m | FrameType.MIN60 | 5 |
30分钟线 | 30m | FrameType.MIN30 | 4 |
15分钟线 | 15m | FrameType.MIN15 | 3 |
5分钟线 | 5m | FrameType.MIN5 | 2 |
分钟线 | 1m | FrameType.MIN1 | 1 |
Source code in coretypes/types.py
class FrameType(Enum):
"""对证券交易中K线周期的封装。提供了以下对应周期:
| 周期 | 字符串 | 类型 | 数值 |
| --------- | --- | ------------------ | -- |
| 年线 | 1Y | FrameType.YEAR | 10 |
| 季线 | 1Q | FrameType.QUARTER | 9 |
| 月线 | 1M | FrameType.MONTH | 8 |
| 周线 | 1W | FrameType.WEEK | 7 |
| 日线 | 1D | FrameType.DAY | 6 |
| 60分钟线 | 60m | FrameType.MIN60 | 5 |
| 30分钟线 | 30m | FrameType.MIN30 | 4 |
| 15分钟线 | 15m | FrameType.MIN15 | 3 |
| 5分钟线 | 5m | FrameType.MIN5 | 2 |
| 分钟线 | 1m | FrameType.MIN1 | 1 |
"""
DAY = "1d"
MIN60 = "60m"
MIN30 = "30m"
MIN15 = "15m"
MIN5 = "5m"
MIN1 = "1m"
WEEK = "1w"
MONTH = "1M"
QUARTER = "1Q"
YEAR = "1Y"
def to_int(self) -> int:
"""转换为整数表示,用于串行化"""
mapping = {
FrameType.MIN1: 1,
FrameType.MIN5: 2,
FrameType.MIN15: 3,
FrameType.MIN30: 4,
FrameType.MIN60: 5,
FrameType.DAY: 6,
FrameType.WEEK: 7,
FrameType.MONTH: 8,
FrameType.QUARTER: 9,
FrameType.YEAR: 10,
}
return mapping[self]
@staticmethod
def from_int(frame_type: int) -> "FrameType":
"""将整数表示的`frame_type`转换为`FrameType`类型"""
mapping = {
1: FrameType.MIN1,
2: FrameType.MIN5,
3: FrameType.MIN15,
4: FrameType.MIN30,
5: FrameType.MIN60,
6: FrameType.DAY,
7: FrameType.WEEK,
8: FrameType.MONTH,
9: FrameType.QUARTER,
10: FrameType.YEAR,
}
return mapping[frame_type]
def __lt__(self, other):
if self.__class__ is other.__class__:
return self.to_int() < other.to_int()
return NotImplemented
def __le__(self, other) -> bool:
if self.__class__ is other.__class__:
return self.to_int() <= other.to_int()
return NotImplemented
def __ge__(self, other) -> bool:
if self.__class__ is other.__class__:
return self.to_int() >= other.to_int()
return NotImplemented
def __gt__(self, other) -> bool:
if self.__class__ is other.__class__:
return self.to_int() > other.to_int()
return NotImplemented
MarketType (Enum)
¶
市场类型。当前支持的类型为上交所XSHG
和XSHE
Source code in coretypes/types.py
class MarketType(Enum):
"""市场类型。当前支持的类型为上交所`XSHG`和`XSHE`"""
XSHG = "XSHG"
XSHE = "XSHE"
SecurityType (Enum)
¶
支持的证券品种类型定义
类型 | 值 | 说明 |
---|---|---|
SecurityType.STOCK | stock | 股票类型 |
SecurityType.INDEX | index | 指数类型 |
SecurityType.ETF | etf | ETF基金 |
SecurityType.FUND | fund | 基金 |
SecurityType.LOF | lof,LOF基金 | |
SecurityType.FJA | fja | 分级A基金 |
SecurityType.FJB | fjb | 分级B基金 |
SecurityType.BOND | bond | 债券基金 |
SecurityType.STOCK_B | stock_b | B股 |
SecurityType.UNKNOWN | unknown | 未知品种 |
Source code in coretypes/types.py
class SecurityType(Enum):
"""支持的证券品种类型定义
| 类型 | 值 | 说明 |
| ------------------------ | --------- | ----- |
| SecurityType.STOCK | stock | 股票类型 |
| SecurityType.INDEX | index | 指数类型 |
| SecurityType.ETF | etf | ETF基金 |
| SecurityType.FUND | fund | 基金 |
| SecurityType.LOF | lof,LOF基金 | |
| SecurityType.FJA | fja | 分级A基金 |
| SecurityType.FJB | fjb | 分级B基金 |
| SecurityType.BOND | bond | 债券基金 |
| SecurityType.STOCK_B | stock_b | B股 |
| SecurityType.UNKNOWN | unknown | 未知品种 |
"""
STOCK = "stock"
INDEX = "index"
ETF = "etf"
FUND = "fund"
LOF = "lof"
FJA = "fja"
FJB = "fjb"
FUTURES = "futures"
BOND = "bond"
STOCK_B = "stock_b"
UNKNOWN = "unknown"