INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Extract links from robots.txt and sitemap.xml.
def zap(input_url, archive, domain, host, internal, robots, proxies): """Extract links from robots.txt and sitemap.xml.""" if archive: print('%s Fetching URLs from archive.org' % run) if False: archived_urls = time_machine(domain, 'domain') else: archived_urls = t...
Handle the requests and return the response body.
def requester( url, main_url=None, delay=0, cook=None, headers=None, timeout=10, host=None, proxies=[None], user_agents=[None], failed=None, processed=None ): """Handle the requests and return the response body.""" cook ...
Extract intel from the response body.
def intel_extractor(url, response): """Extract intel from the response body.""" for rintel in rintels: res = re.sub(r'<(script).*?</\1>(?s)', '', response) res = re.sub(r'<[^<]+?>', '', res) matches = rintel[0].findall(res) if matches: for match in matches: ...
Extract js files from the response body
def js_extractor(response): """Extract js files from the response body""" # Extract .js files matches = rscript.findall(response) for match in matches: match = match[2].replace('\'', '').replace('"', '') verb('JS file', match) bad_scripts.add(match)
Extract details from the response body.
def extractor(url): """Extract details from the response body.""" response = requester(url, main_url, delay, cook, headers, timeout, host, proxies, user_agents, failed, processed) if clone: mirror(url, response) matches = rhref.findall(response) for link in matches: # Remove e...
Extract endpoints from JavaScript code.
def jscanner(url): """Extract endpoints from JavaScript code.""" response = requester(url, main_url, delay, cook, headers, timeout, host, proxies, user_agents, failed, processed) # Extract URLs/endpoints matches = rendpoint.findall(response) # Iterate over the matches, match is a tuple for...
Update the current installation. git clones the latest version and merges it with the current directory.
def updater(): """Update the current installation. git clones the latest version and merges it with the current directory. """ print('%s Checking for updates' % run) # Changes must be separated by ; changes = '''major bug fixes;removed ninja mode;dropped python < 3.2 support;fixed unicode outpu...
Find subdomains according to the TLD.
def find_subdomains(domain): """Find subdomains according to the TLD.""" result = set() response = get('https://findsubdomains.com/subdomains-of/' + domain).text matches = findall(r'(?s)<div class="domains js-domain-name">(.*?)</div>', response) for match in matches: result.add(match.replace...
Process the URLs and uses a threadpool to execute a function.
def flash(function, links, thread_count): """Process the URLs and uses a threadpool to execute a function.""" # Convert links (set) to list links = list(links) threadpool = concurrent.futures.ThreadPoolExecutor( max_workers=thread_count) futures = (threadpool.submit(function, link) for l...
Extract a string based on regex pattern supplied by user.
def regxy(pattern, response, supress_regex, custom): """Extract a string based on regex pattern supplied by user.""" try: matches = re.findall(r'%s' % pattern, response) for match in matches: verb('Custom regex', match) custom.add(match) except: supress_regex ...
Determine whether or not a link should be crawled A url should not be crawled if it - Is a file - Has already been crawled Args: url: str Url to be processed processed: list[str] List of urls that have already been crawled Returns: bool If `url` should be crawled
def is_link(url, processed, files): """ Determine whether or not a link should be crawled A url should not be crawled if it - Is a file - Has already been crawled Args: url: str Url to be processed processed: list[str] List of urls that have already been crawled Ret...
Parse a list for non-matches to a regex. Args: urls: iterable of urls regex: string regex to be parsed for Returns: list of strings not matching regex
def remove_regex(urls, regex): """ Parse a list for non-matches to a regex. Args: urls: iterable of urls regex: string regex to be parsed for Returns: list of strings not matching regex """ if not regex: return urls # To avoid iterating over the characters...
Write the results.
def writer(datasets, dataset_names, output_dir): """Write the results.""" for dataset, dataset_name in zip(datasets, dataset_names): if dataset: filepath = output_dir + '/' + dataset_name + '.txt' with open(filepath, 'w+') as out_file: joined = '\n'.join(dataset) ...
Return the passed time.
def timer(diff, processed): """Return the passed time.""" # Changes seconds into minutes and seconds minutes, seconds = divmod(diff, 60) try: # Finds average time taken by requests time_per_request = diff / float(len(processed)) except ZeroDivisionError: time_per_request = 0 ...
Calculate the entropy of a string.
def entropy(string): """Calculate the entropy of a string.""" entropy = 0 for number in range(256): result = float(string.encode('utf-8').count( chr(number))) / len(string.encode('utf-8')) if result != 0: entropy = entropy - result * math.log(result, 2) return ent...
This function extracts valid headers from interactive input.
def extract_headers(headers): """This function extracts valid headers from interactive input.""" sorted_headers = {} matches = re.findall(r'(.*):\s(.*)', headers) for match in matches: header = match[0] value = match[1] try: if value[-1] == ',': value ...
Extract the top level domain from an URL.
def top_level(url, fix_protocol=True): """Extract the top level domain from an URL.""" ext = tld.get_tld(url, fix_protocol=fix_protocol) toplevel = '.'.join(urlparse(url).netloc.split('.')[-2:]).split( ext)[0] + ext return toplevel
Match IP:PORT or DOMAIN:PORT in a losse manner
def proxy_type(v): """ Match IP:PORT or DOMAIN:PORT in a losse manner """ proxies = [] if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", v): proxies.append({"http": v, "https": v}) return proxies elif re.match(r"((http|socks5):\/...
Query dnsdumpster.com.
def dnsdumpster(domain, output_dir): """Query dnsdumpster.com.""" response = requests.Session().get('https://dnsdumpster.com/').text csrf_token = re.search( r"name='csrfmiddlewaretoken' value='(.*?)'", response).group(1) cookies = {'csrftoken': csrf_token} headers = {'Referer': 'https://dns...
Present the user a prompt.
def prompt(default=None): """Present the user a prompt.""" editor = 'nano' with tempfile.NamedTemporaryFile(mode='r+') as tmpfile: if default: tmpfile.write(default) tmpfile.flush() child_pid = os.fork() is_child = child_pid == 0 if is_child: ...
start the market thread and register backtest broker thread QAMarket 继承QATrader, QATrader 中有 trade_engine属性 , trade_engine类型是QA_Engine从 QA_Thread继承
def start_market(self): """ start the market thread and register backtest broker thread QAMarket 继承QATrader, QATrader 中有 trade_engine属性 , trade_engine类型是QA_Engine从 QA_Thread继承 """ # 启动 trade_engine 线程 self.market.start() # 注册 backtest_broker ,并且启动和它关联线程QAThread 存...
generator driven data flow
def run(self): """generator driven data flow """ # 如果出现了日期的改变 才会进行结算的事件 _date = None while QA_util_if_tradetime(self.now): for data in self.ingest_data: # 对于在ingest_data中的数据 # <class 'QUANTAXIS.QAData.QADataStruct.QA_DataStruct_Stock_day'> ...
the standard message which can be transfer
def message(self): 'the standard message which can be transfer' return { 'source': 'account', 'frequence': self.frequence, 'account_cookie': self.account_cookie, 'portfolio_cookie': self.portfolio_cookie, ...
带account_cookie的初始化持仓 Returns: [type] -- [description]
def init_hold_with_account(self): """带account_cookie的初始化持仓 Returns: [type] -- [description] """ return self.init_hold.reset_index().assign( account_cookie=self.account_cookie ).set_index(['code', 'account_cookie'])
账户的起始交易日期(只在回测中使用) Raises: RuntimeWarning -- [description] Returns: [type] -- [description]
def start_date(self): """账户的起始交易日期(只在回测中使用) Raises: RuntimeWarning -- [description] Returns: [type] -- [description] """ if self.start_==None: if len(self.time_index_max) > 0: return str(min(self.time_index_max))[0:10] ...
账户的交易结束日期(只在回测中使用) Raises: RuntimeWarning -- [description] Returns: [type] -- [description]
def end_date(self): """账户的交易结束日期(只在回测中使用) Raises: RuntimeWarning -- [description] Returns: [type] -- [description] """ if self.start_==None: if len(self.time_index_max) > 0: return str(max(self.time_index_max))[0:10] ...
区间交易历史的table
def history_table_min(self): '区间交易历史的table' if len(self.history_min) > 0: lens = len(self.history_min[0]) else: lens = len(self._history_headers) return pd.DataFrame( data=self.history_min, columns=self._history_headers[:lens] ).so...
交易历史的table
def history_table(self): '交易历史的table' if len(self.history) > 0: lens = len(self.history[0]) else: lens = len(self._history_headers) return pd.DataFrame( data=self.history, columns=self._history_headers[:lens] ).sort_index()
现金的table
def cash_table(self): '现金的table' _cash = pd.DataFrame( data=[self.cash[1::], self.time_index_max], index=['cash', 'datetime'] ).T _cash = _cash.assign( date=_cash.datetime.apply(lambda x: pd.to_datetime(str(x)[0:10]...
真实持仓
def hold(self): """真实持仓 """ return pd.concat( [self.init_hold, self.hold_available] ).groupby('code').sum().replace(0, np.nan).dropna().sort_index()
可用持仓
def hold_available(self): """可用持仓 """ return self.history_table.groupby('code').amount.sum().replace( 0, np.nan ).dropna().sort_index()
每次交易的pivot表 Returns: pd.DataFrame 此处的pivot_table一定要用np.sum
def trade(self): """每次交易的pivot表 Returns: pd.DataFrame 此处的pivot_table一定要用np.sum """ return self.history_table.pivot_table( index=['datetime', 'account_cookie'], columns='code', values='amount', a...
每日交易结算时的现金表
def daily_cash(self): '每日交易结算时的现金表' res = self.cash_table.drop_duplicates(subset='date', keep='last') le=pd.DataFrame(pd.Series(data=None, index=pd.to_datetime(self.trade_range_max).set_names('date'), name='predrop')) ri=res.set_index('date') res_=pd.merge(le,ri,how='left',left_i...
每日交易结算时的持仓表
def daily_hold(self): '每日交易结算时的持仓表' data = self.trade.cumsum() if len(data) < 1: return None else: # print(data.index.levels[0]) data = data.assign(account_cookie=self.account_cookie).assign( date=pd.to_datetime(data.index.levels[0]).da...
每日交易结算时的持仓表
def daily_frozen(self): '每日交易结算时的持仓表' res_=self.history_table.assign(date=pd.to_datetime(self.history_table.datetime)).set_index('date').resample('D').frozen.last().fillna(method='pad') res_=res_[res_.index.isin(self.trade_range)] return res_
到某一个时刻的持仓 如果给的是日期,则返回当日开盘前的持仓
def hold_table(self, datetime=None): "到某一个时刻的持仓 如果给的是日期,则返回当日开盘前的持仓" if datetime is None: hold_available = self.history_table.set_index( 'datetime' ).sort_index().groupby('code').amount.sum().sort_index() else: hold_available = self.history_tab...
计算目前持仓的成本 用于模拟盘和实盘查询 Returns: [type] -- [description]
def current_hold_price(self): """计算目前持仓的成本 用于模拟盘和实盘查询 Returns: [type] -- [description] """ def weights(x): n=len(x) res=1 while res>0 or res<0: res=sum(x[:n]['amount']) n=n-1 ...
计算持仓成本 如果给的是日期,则返回当日开盘前的持仓 Keyword Arguments: datetime {[type]} -- [description] (default: {None}) Returns: [type] -- [description]
def hold_price(self, datetime=None): """计算持仓成本 如果给的是日期,则返回当日开盘前的持仓 Keyword Arguments: datetime {[type]} -- [description] (default: {None}) Returns: [type] -- [description] """ def weights(x): if sum(x['amount']) != 0: return...
持仓时间 Keyword Arguments: datetime {[type]} -- [description] (default: {None})
def hold_time(self, datetime=None): """持仓时间 Keyword Arguments: datetime {[type]} -- [description] (default: {None}) """ def weights(x): if sum(x['amount']) != 0: return pd.Timestamp(self.datetime ) - pd.to_datet...
reset_history/cash/
def reset_assets(self, init_cash=None): 'reset_history/cash/' self.sell_available = copy.deepcopy(self.init_hold) self.history = [] self.init_cash = init_cash self.cash = [self.init_cash] self.cash_available = self.cash[-1]
快速撮合成交接口 此接口是一个直接可以成交的接口, 所以务必确保给出的信息是可以成交的 此接口涉及的是 1. 股票/期货的成交 2. 历史记录的增加 3. 现金/持仓/冻结资金的处理 Arguments: code {[type]} -- [description] trade_price {[type]} -- [description] trade_amount {[type]} -- [description] trade_tow...
def receive_simpledeal( self, code, trade_price, trade_amount, trade_towards, trade_time, message=None, order_id=None, trade_id=None, realorder_id=None ): """快速撮合成交接口 此接口是一个直接可以成...
更新deal Arguments: code {str} -- [description] trade_id {str} -- [description] order_id {str} -- [description] realorder_id {str} -- [description] trade_price {float} -- [description] trade_amount {int} -- [description] trade_to...
def receive_deal( self, code: str, trade_id: str, order_id: str, realorder_id: str, trade_price: float, trade_amount: int, trade_towards: int, trade_time: str, message=None ): """更新deal ...
ATTENTION CHANGELOG 1.0.28 修改了Account的send_order方法, 区分按数量下单和按金额下单两种方式 - AMOUNT_MODEL.BY_PRICE ==> AMOUNT_MODEL.BY_MONEY # 按金额下单 - AMOUNT_MODEL.BY_AMOUNT # 按数量下单 在按金额下单的时候,应给予 money参数 在按数量下单的时候,应给予 amount参数 python code: Account=QA.QA_Account() Order_bym...
def send_order( self, code=None, amount=None, time=None, towards=None, price=None, money=None, order_model=None, amount_model=None, *args, **kwargs ): """ ATTENTION CHA...
平仓单 Raises: RuntimeError -- if ACCOUNT.RUNNING_ENVIRONMENT is NOT TZERO Returns: list -- list with order
def close_positions_order(self): """平仓单 Raises: RuntimeError -- if ACCOUNT.RUNNING_ENVIRONMENT is NOT TZERO Returns: list -- list with order """ order_list = [] time = '{} 15:00:00'.format(self.date) if self.running_environment == RUNNIN...
股票/期货的日结算 股票的结算: 结转股票可卖额度 T0的结算: 结转T0的额度 期货的结算: 结转静态资金 @2019-02-25 yutiansut hold 在下面要进行大变化: 从 只计算数量 ==> 数量+成本+买入价 (携带更多信息) 基于history去计算hold ==> last_settle+ today_pos_change
def settle(self, settle_data = None): """ 股票/期货的日结算 股票的结算: 结转股票可卖额度 T0的结算: 结转T0的额度 期货的结算: 结转静态资金 @2019-02-25 yutiansut hold 在下面要进行大变化: 从 只计算数量 ==> 数量+成本+买入价 (携带更多信息) 基于history去计算hold ==> last_settle+ today_pos_change """ #pr...
策略事件 :param event: :return:
def on_bar(self, event): ''' 策略事件 :param event: :return: ''' 'while updating the market data' print( "on_bar account {} ".format(self.account_cookie), event.market_data.data ) print(event.send_order) try: ...
resume the account from standard message 这个是从数据库恢复账户时需要的
def from_message(self, message): """resume the account from standard message 这个是从数据库恢复账户时需要的""" self.account_cookie = message.get('account_cookie', None) self.portfolio_cookie = message.get('portfolio_cookie', None) self.user_cookie = message.get('user_cookie', None) self...
[summary] balance = static_balance + float_profit "currency": "", # "CNY" (币种) "pre_balance": float("nan"), # 9912934.78 (昨日账户权益) "static_balance": float("nan"), # (静态权益) "balance": float("nan"), # 9963216.55 (账户权益) "available": float("nan"), # ...
def from_otgdict(self, message): """[summary] balance = static_balance + float_profit "currency": "", # "CNY" (币种) "pre_balance": float("nan"), # 9912934.78 (昨日账户权益) "static_balance": float("nan"), # (静态权益) "balance": float("nan"), # 9963216.55 (账户权益...
打印出account的内容
def table(self): """ 打印出account的内容 """ return pd.DataFrame([ self.message, ]).set_index( 'account_cookie', drop=False ).T
这个方法是被 QA_ThreadEngine 处理队列时候调用的, QA_Task 中 do 方法调用 run (在其它线程中) 'QA_WORKER method 重载' :param event: 事件类型 QA_Event :return:
def run(self, event): ''' 这个方法是被 QA_ThreadEngine 处理队列时候调用的, QA_Task 中 do 方法调用 run (在其它线程中) 'QA_WORKER method 重载' :param event: 事件类型 QA_Event :return: ''' 'QA_WORKER method' if event.event_type is ACCOUNT_EVENT.SETTLE: print('account_settle') ...
同步账户 Arguments: sync_message {[type]} -- [description]
def sync_account(self, sync_message): """同步账户 Arguments: sync_message {[type]} -- [description] """ self.init_hold = sync_message['hold_available'] self.init_cash = sync_message['cash_available'] self.sell_available = copy.deepcopy(self.init_hold) s...
外部操作|高危|
def change_cash(self, money): """ 外部操作|高危| """ res = self.cash[-1] + money if res >= 0: # 高危操作 self.cash[-1] = res
返回历史成交 Arguments: start {str} -- [description] end {str]} -- [description]
def get_history(self, start, end): """返回历史成交 Arguments: start {str} -- [description] end {str]} -- [description] """ return self.history_table.set_index( 'datetime', drop=False ).loc[slice(pd.Timestamp(start), p...
存储order_handler的order_status Arguments: orderlist {[dataframe]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE})
def QA_SU_save_order(orderlist, client=DATABASE): """存储order_handler的order_status Arguments: orderlist {[dataframe]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ if isinstance(orderlist, pd.DataFrame): collection = client.o...
存储order_handler的deal_status Arguments: dealist {[dataframe]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE})
def QA_SU_save_deal(dealist, client=DATABASE): """存储order_handler的deal_status Arguments: dealist {[dataframe]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ if isinstance(dealist, pd.DataFrame): collection = client.deal ...
增量存储order_queue Arguments: order_queue {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE})
def QA_SU_save_order_queue(order_queue, client=DATABASE): """增量存储order_queue Arguments: order_queue {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ collection = client.order_queue collection.create_index( [('accoun...
威廉SMA算法 本次修正主要是对于返回值的优化,现在的返回值会带上原先输入的索引index 2018/5/3 @yutiansut
def SMA(Series, N, M=1): """ 威廉SMA算法 本次修正主要是对于返回值的优化,现在的返回值会带上原先输入的索引index 2018/5/3 @yutiansut """ ret = [] i = 1 length = len(Series) # 跳过X中前面几个 nan 值 while i < length: if np.isnan(Series.iloc[i]): i += 1 else: break preY = Series...
A<B then A>B A上穿B B下穿A Arguments: A {[type]} -- [description] B {[type]} -- [description] Returns: [type] -- [description]
def CROSS(A, B): """A<B then A>B A上穿B B下穿A Arguments: A {[type]} -- [description] B {[type]} -- [description] Returns: [type] -- [description] """ var = np.where(A < B, 1, 0) return (pd.Series(var, index=A.index).diff() < 0).apply(int)
2018/05/23 修改 参考https://github.com/QUANTAXIS/QUANTAXIS/issues/429 现在返回的是series
def COUNT(COND, N): """ 2018/05/23 修改 参考https://github.com/QUANTAXIS/QUANTAXIS/issues/429 现在返回的是series """ return pd.Series(np.where(COND, 1, 0), index=COND.index).rolling(N).sum()
表达持续性 从前N1日到前N2日一直满足COND条件 Arguments: COND {[type]} -- [description] N1 {[type]} -- [description] N2 {[type]} -- [description]
def LAST(COND, N1, N2): """表达持续性 从前N1日到前N2日一直满足COND条件 Arguments: COND {[type]} -- [description] N1 {[type]} -- [description] N2 {[type]} -- [description] """ N2 = 1 if N2 == 0 else N2 assert N2 > 0 assert N1 > N2 return COND.iloc[-N1:-N2].all()
平均绝对偏差 mean absolute deviation 修正: 2018-05-25 之前用mad的计算模式依然返回的是单值
def AVEDEV(Series, N): """ 平均绝对偏差 mean absolute deviation 修正: 2018-05-25 之前用mad的计算模式依然返回的是单值 """ return Series.rolling(N).apply(lambda x: (np.abs(x - x.mean())).mean(), raw=True)
macd指标 仅适用于Series 对于DATAFRAME的应用请使用QA_indicator_macd
def MACD(Series, FAST, SLOW, MID): """macd指标 仅适用于Series 对于DATAFRAME的应用请使用QA_indicator_macd """ EMAFAST = EMA(Series, FAST) EMASLOW = EMA(Series, SLOW) DIFF = EMAFAST - EMASLOW DEA = EMA(DIFF, MID) MACD = (DIFF - DEA) * 2 DICT = {'DIFF': DIFF, 'DEA': DEA, 'MACD': MACD} VAR = pd.Da...
多空指标
def BBI(Series, N1, N2, N3, N4): '多空指标' bbi = (MA(Series, N1) + MA(Series, N2) + MA(Series, N3) + MA(Series, N4)) / 4 DICT = {'BBI': bbi} VAR = pd.DataFrame(DICT) return VAR
支持MultiIndex的cond和DateTimeIndex的cond 条件成立 yes= True 或者 yes=1 根据不同的指标自己定 Arguments: cond {[type]} -- [description]
def BARLAST(cond, yes=True): """支持MultiIndex的cond和DateTimeIndex的cond 条件成立 yes= True 或者 yes=1 根据不同的指标自己定 Arguments: cond {[type]} -- [description] """ if isinstance(cond.index, pd.MultiIndex): return len(cond)-cond.index.levels[0].tolist().index(cond[cond != yes].index[-1][0])-1 ...
today all Returns: [type] -- [description]
def get_today_all(output='pd'): """today all Returns: [type] -- [description] """ data = [] today = str(datetime.date.today()) codes = QA_fetch_get_stock_list('stock').code.tolist() bestip = select_best_ip()['stock'] for code in codes: try: l = QA_fetch_get_...
save stock_day 保存日线数据 :param client: :param ui_log: 给GUI qt 界面使用 :param ui_progress: 给GUI qt 界面使用 :param ui_progress_int_value: 给GUI qt 界面使用
def QA_SU_save_stock_day(client=DATABASE, ui_log=None, ui_progress=None): ''' save stock_day 保存日线数据 :param client: :param ui_log: 给GUI qt 界面使用 :param ui_progress: 给GUI qt 界面使用 :param ui_progress_int_value: 给GUI qt 界面使用 ''' stock_list = QA_fetch_get_stock_list().code.unique().tolist...
用户登陆 不使用 QAUSER库 只返回 TRUE/FALSE
def QA_user_sign_in(username, password): """用户登陆 不使用 QAUSER库 只返回 TRUE/FALSE """ #user = QA_User(name= name, password=password) cursor = DATABASE.user.find_one( {'username': username, 'password': password}) if cursor is None: QA_util_log_info('SOMETHING WRONG') return ...
只做check! 具体逻辑需要在自己的函数中实现 参见:QAWEBSERVER中的实现 Arguments: name {[type]} -- [description] password {[type]} -- [description] client {[type]} -- [description] Returns: [type] -- [description]
def QA_user_sign_up(name, password, client): """只做check! 具体逻辑需要在自己的函数中实现 参见:QAWEBSERVER中的实现 Arguments: name {[type]} -- [description] password {[type]} -- [description] client {[type]} -- [description] Returns: [type] -- [description] """ coll = client...
对order/market的封装 [description] Arguments: order {[type]} -- [description] Returns: [type] -- [description]
def warp(self, order): """对order/market的封装 [description] Arguments: order {[type]} -- [description] Returns: [type] -- [description] """ # 因为成交模式对时间的封装 if order.order_model == ORDER_MODEL.MARKET: if order.frequence is FREQ...
get_filename
def get_filename(): """ get_filename """ return [(l[0],l[1]) for l in [line.strip().split(",") for line in requests.get(FINANCIAL_URL).text.strip().split('\n')]]
会创建一个download/文件夹
def download_financialzip(): """ 会创建一个download/文件夹 """ result = get_filename() res = [] for item, md5 in result: if item in os.listdir(download_path) and md5==QA_util_file_md5('{}{}{}'.format(download_path,os.sep,item)): print('FILE {} is already in {}'.format(it...
读取历史财务数据文件,并返回pandas结果 , 类似gpcw20171231.zip格式,具体字段含义参考 https://github.com/rainx/pytdx/issues/133 :param data_file: 数据文件地址, 数据文件类型可以为 .zip 文件,也可以为解压后的 .dat :return: pandas DataFrame格式的历史财务数据
def get_df(self, data_file): """ 读取历史财务数据文件,并返回pandas结果 , 类似gpcw20171231.zip格式,具体字段含义参考 https://github.com/rainx/pytdx/issues/133 :param data_file: 数据文件地址, 数据文件类型可以为 .zip 文件,也可以为解压后的 .dat :return: pandas DataFrame格式的历史财务数据 """ crawler = QAHistoryFinancialCrawle...
return shanghai margin data Arguments: date {str YYYY-MM-DD} -- date format Returns: pandas.DataFrame -- res for margin data
def QA_fetch_get_sh_margin(date): """return shanghai margin data Arguments: date {str YYYY-MM-DD} -- date format Returns: pandas.DataFrame -- res for margin data """ if date in trade_date_sse: data= pd.read_excel(_sh_url.format(QA_util_date_str2int ...
return shenzhen margin data Arguments: date {str YYYY-MM-DD} -- date format Returns: pandas.DataFrame -- res for margin data
def QA_fetch_get_sz_margin(date): """return shenzhen margin data Arguments: date {str YYYY-MM-DD} -- date format Returns: pandas.DataFrame -- res for margin data """ if date in trade_date_sse: return pd.read_excel(_sz_url.format(date)).assign(date=date).assign(sse='sz')
更新市场数据 broker 为名字, data 是市场数据 被 QABacktest 中run 方法调用 upcoming_data
def upcoming_data(self, broker, data): ''' 更新市场数据 broker 为名字, data 是市场数据 被 QABacktest 中run 方法调用 upcoming_data ''' # main thread' # if self.running_time is not None and self.running_time!= data.datetime[0]: # for item in self.broker.keys(): ...
开启查询子线程(实盘中用)
def start_order_threading(self): """开启查询子线程(实盘中用) """ self.if_start_orderthreading = True self.order_handler.if_start_orderquery = True self.trade_engine.create_kernel('ORDER', daemon=True) self.trade_engine.start_kernel('ORDER') self.sync_order_and_deal()
login 登录到交易前置 2018-07-02 在实盘中,登录到交易前置后,需要同步资产状态 Arguments: broker_name {[type]} -- [description] account_cookie {[type]} -- [description] Keyword Arguments: account {[type]} -- [description] (default: {None}) Returns: [type] -- [descrip...
def login(self, broker_name, account_cookie, account=None): """login 登录到交易前置 2018-07-02 在实盘中,登录到交易前置后,需要同步资产状态 Arguments: broker_name {[type]} -- [description] account_cookie {[type]} -- [description] Keyword Arguments: account {[type]} -- [descript...
同步账户信息 Arguments: broker_id {[type]} -- [description] account_cookie {[type]} -- [description]
def sync_account(self, broker_name, account_cookie): """同步账户信息 Arguments: broker_id {[type]} -- [description] account_cookie {[type]} -- [description] """ try: if isinstance(self.broker[broker_name], QA_BacktestBroker): pass ...
内部函数
def _trade(self, event): "内部函数" print('==================================market enging: trade') print(self.order_handler.order_queue.pending) print('==================================') self.order_handler._trade() print('done')
交易前置结算 1. 回测: 交易队列清空,待交易队列标记SETTLE 2. 账户每日结算 3. broker结算更新
def settle_order(self): """交易前置结算 1. 回测: 交易队列清空,待交易队列标记SETTLE 2. 账户每日结算 3. broker结算更新 """ if self.if_start_orderthreading: self.order_handler.run( QA_Event( event_type=BROKER_EVENT.SETTLE, event_queue=...
需要对于datetime 和date 进行转换, 以免直接被变成了时间戳
def QA_util_to_json_from_pandas(data): """需要对于datetime 和date 进行转换, 以免直接被变成了时间戳""" if 'datetime' in data.columns: data.datetime = data.datetime.apply(str) if 'date' in data.columns: data.date = data.date.apply(str) return json.loads(data.to_json(orient='records'))
将所有沪深股票从数字转化到6位的代码 因为有时候在csv等转换的时候,诸如 000001的股票会变成office强制转化成数字1
def QA_util_code_tostr(code): """ 将所有沪深股票从数字转化到6位的代码 因为有时候在csv等转换的时候,诸如 000001的股票会变成office强制转化成数字1 """ if isinstance(code, int): return "{:>06d}".format(code) if isinstance(code, str): # 聚宽股票代码格式 '600000.XSHG' # 掘金股票代码格式 'SHSE.600000' # Wind股票代码格式 '600000.SH' ...
转换code==> list Arguments: code {[type]} -- [description] Keyword Arguments: auto_fill {bool} -- 是否自动补全(一般是用于股票/指数/etf等6位数,期货不适用) (default: {True}) Returns: [list] -- [description]
def QA_util_code_tolist(code, auto_fill=True): """转换code==> list Arguments: code {[type]} -- [description] Keyword Arguments: auto_fill {bool} -- 是否自动补全(一般是用于股票/指数/etf等6位数,期货不适用) (default: {True}) Returns: [list] -- [description] """ if isinstance(code, str): ...
订阅一个策略 会扣减你的积分 Arguments: strategy_id {str} -- [description] last {int} -- [description] Keyword Arguments: today {[type]} -- [description] (default: {datetime.date.today()}) cost_coins {int} -- [description] (default: {10})
def subscribe_strategy( self, strategy_id: str, last: int, today=datetime.date.today(), cost_coins=10 ): """订阅一个策略 会扣减你的积分 Arguments: strategy_id {str} -- [description] last {int} -- [description] ...
取消订阅某一个策略 Arguments: strategy_id {[type]} -- [description]
def unsubscribe_stratgy(self, strategy_id): """取消订阅某一个策略 Arguments: strategy_id {[type]} -- [description] """ today = datetime.date.today() order_id = str(uuid.uuid1()) if strategy_id in self._subscribed_strategy.keys(): self._subscribed_strategy...
订阅一个策略 Returns: [type] -- [description]
def subscribing_strategy(self): """订阅一个策略 Returns: [type] -- [description] """ res = self.subscribed_strategy.assign( remains=self.subscribed_strategy.end.apply( lambda x: pd.Timestamp(x) - pd.Timestamp(datetime.date.today()) ) ...
根据 self.user_cookie 创建一个 portfolio :return: 如果存在 返回 新建的 QA_Portfolio 如果已经存在 返回 这个portfolio
def new_portfolio(self, portfolio_cookie=None): ''' 根据 self.user_cookie 创建一个 portfolio :return: 如果存在 返回 新建的 QA_Portfolio 如果已经存在 返回 这个portfolio ''' _portfolio = QA_Portfolio( user_cookie=self.user_cookie, portfolio_cookie=portfolio_cookie ...
直接从二级目录拿到account Arguments: portfolio_cookie {str} -- [description] account_cookie {str} -- [description] Returns: [type] -- [description]
def get_account(self, portfolio_cookie: str, account_cookie: str): """直接从二级目录拿到account Arguments: portfolio_cookie {str} -- [description] account_cookie {str} -- [description] Returns: [type] -- [description] """ try: return self...
make a simple account with a easier way 如果当前user中没有创建portfolio, 则创建一个portfolio,并用此portfolio创建一个account 如果已有一个或多个portfolio,则使用第一个portfolio来创建一个account
def generate_simpleaccount(self): """make a simple account with a easier way 如果当前user中没有创建portfolio, 则创建一个portfolio,并用此portfolio创建一个account 如果已有一个或多个portfolio,则使用第一个portfolio来创建一个account """ if len(self.portfolio_list.keys()) < 1: po = self.new_portfolio() els...
注册一个account到portfolio组合中 account 也可以是一个策略类,实现其 on_bar 方法 :param account: 被注册的account :return:
def register_account(self, account, portfolio_cookie=None): ''' 注册一个account到portfolio组合中 account 也可以是一个策略类,实现其 on_bar 方法 :param account: 被注册的account :return: ''' # 查找 portfolio if len(self.portfolio_list.keys()) < 1: po = self.new_portfolio() ...
将QA_USER的信息存入数据库 ATTENTION: 在save user的时候, 需要同时调用 user/portfolio/account链条上所有的实例化类 同时save
def save(self): """ 将QA_USER的信息存入数据库 ATTENTION: 在save user的时候, 需要同时调用 user/portfolio/account链条上所有的实例化类 同时save """ if self.wechat_id is not None: self.client.update( {'wechat_id': self.wechat_id}, {'$set': self.message}, ...
基于账户/密码去sync数据库
def sync(self): """基于账户/密码去sync数据库 """ if self.wechat_id is not None: res = self.client.find_one({'wechat_id': self.wechat_id}) else: res = self.client.find_one( { 'username': self.username, 'password': self...
恢复方法 Arguments: message {[type]} -- [description]
def reload(self, message): """恢复方法 Arguments: message {[type]} -- [description] """ self.phone = message.get('phone') self.level = message.get('level') self.utype = message.get('utype') self.coins = message.get('coins') self.wechat_id = messa...
对输入日期进行格式化处理,返回格式为 "%Y-%m-%d" 格式字符串 支持格式包括: 1. str: "%Y%m%d" "%Y%m%d%H%M%S", "%Y%m%d %H:%M:%S", "%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H%M%S" 2. datetime.datetime 3. pd.Timestamp 4. int -> 自动在右边加 0 然后转换,譬如 '20190302093' --> "2019-03-02" :param cursor_date: str/datetime.datetime...
def QA_util_format_date2str(cursor_date): """ 对输入日期进行格式化处理,返回格式为 "%Y-%m-%d" 格式字符串 支持格式包括: 1. str: "%Y%m%d" "%Y%m%d%H%M%S", "%Y%m%d %H:%M:%S", "%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H%M%S" 2. datetime.datetime 3. pd.Timestamp 4. int -> 自动在右边加 0 然后转换,譬如 '20190302093' --> "2019...
得到下 n 个交易日 (不包含当前交易日) :param date: :param n:
def QA_util_get_next_trade_date(cursor_date, n=1): """ 得到下 n 个交易日 (不包含当前交易日) :param date: :param n: """ cursor_date = QA_util_format_date2str(cursor_date) if cursor_date in trade_date_sse: # 如果指定日期为交易日 return QA_util_date_gap(cursor_date, n, "gt") real_pre_trade_date = Q...
得到前 n 个交易日 (不包含当前交易日) :param date: :param n:
def QA_util_get_pre_trade_date(cursor_date, n=1): """ 得到前 n 个交易日 (不包含当前交易日) :param date: :param n: """ cursor_date = QA_util_format_date2str(cursor_date) if cursor_date in trade_date_sse: return QA_util_date_gap(cursor_date, n, "lt") real_aft_trade_date = QA_util_get_real_date(c...
时间是否交易
def QA_util_if_tradetime( _time=datetime.datetime.now(), market=MARKET_TYPE.STOCK_CN, code=None ): '时间是否交易' _time = datetime.datetime.strptime(str(_time)[0:19], '%Y-%m-%d %H:%M:%S') if market is MARKET_TYPE.STOCK_CN: if QA_util_if_trade(str(_time.date())[0:10]): i...
获取真实的交易日期,其中,第三个参数towards是表示向前/向后推 towards=1 日期向后迭代 towards=-1 日期向前迭代 @ yutiansut
def QA_util_get_real_date(date, trade_list=trade_date_sse, towards=-1): """ 获取真实的交易日期,其中,第三个参数towards是表示向前/向后推 towards=1 日期向后迭代 towards=-1 日期向前迭代 @ yutiansut """ date = str(date)[0:10] if towards == 1: while date not in trade_list: date = str( datetim...
取数据的真实区间,返回的时候用 start,end=QA_util_get_real_datelist @yutiansut 2017/8/10 当start end中间没有交易日 返回None, None @yutiansut/ 2017-12-19
def QA_util_get_real_datelist(start, end): """ 取数据的真实区间,返回的时候用 start,end=QA_util_get_real_datelist @yutiansut 2017/8/10 当start end中间没有交易日 返回None, None @yutiansut/ 2017-12-19 """ real_start = QA_util_get_real_date(start, trade_date_sse, 1) real_end = QA_util_get_real_date(end, trade_...
给出交易具体时间
def QA_util_get_trade_range(start, end): '给出交易具体时间' start, end = QA_util_get_real_datelist(start, end) if start is not None: return trade_date_sse[trade_date_sse .index(start):trade_date_sse.index(end) + 1:1] else: return None