示例#1
0
def get_dominant_future(underlying_symbol, rule=0):
    # type: (str, Optional[int]) -> Optional[str]
    """
    获取某一期货品种策略当前日期的主力合约代码。 合约首次上市时,以当日收盘同品种持仓量最大者作为从第二个交易日开始的主力合约。当同品种其他合约持仓量在收盘后超过当前主力合约1.1倍时,从第二个交易日开始进行主力合约的切换。日内不会进行主力合约的切换。

    :param underlying_symbol: 期货合约品种,例如沪深300股指期货为'IF'
    :param rule: 默认是rule=0,采用最大昨仓为当日主力合约,每个合约只能做一次主力合约,不会重复出现。针对股指期货,只在当月和次月选择主力合约。 当rule=1时,主力合约的选取只考虑最大昨仓这个条件。

    :example:

    获取某一天的主力合约代码(策略当前日期是20160801):

    ..  code-block:: python3
        :linenos:

        get_dominant_future('IF')
        #[Out]
        #'IF1608'
    """
    dt = Environment.get_instance().trading_dt.date()
    ret = rqdatac.get_dominant_future(underlying_symbol, dt, dt, rule)
    if isinstance(ret, pd.Series) and ret.size == 1:
        return ret.item()
    else:
        user_log.warn(
            _("\'{0}\' future does not exist").format(underlying_symbol))
        return None
示例#2
0
def get_all_future_and_save_data():
    format_today = datetime.datetime.now().strftime('%Y%m%d')
    for temp in need_to_monitor_future_list:
        temp_dominant_list = rq.get_dominant_future(temp.lower(),
                                                    end_date=format_today)
        temp_dominant_list.sort_index(inplace=True)
        temp_dominant_list = pd.DataFrame(temp_dominant_list)
        a = temp_dominant_list.groupby('dominant')
        get_price_and_save_to_csv(a, temp)
示例#3
0
    def getAllMain(self, code, start=None):
        if start is None:
            start = public.getDate(diff=-2)

        res = rq.get_dominant_future(code,
                                     start_date=start,
                                     end_date=public.getDate(diff=1))
        pre = ''
        docs = []
        for i in range(len(res)):
            if pre != res[i]: docs.append((res.index[i], res[i]))
            pre = res[i]

        return docs
示例#4
0
    def getAdjustDate(self, code, diff=120, start=None):
        if start is None:
            start = public.getDate(diff=-diff)

        res = rq.get_dominant_future(code,
                                     start_date=start,
                                     end_date=public.getDate(diff=0))
        pre = res[0]
        l = []
        for i in range(len(res)):
            if pre != res[i]:
                l.append((res.index[i - 1], res.index[i], pre, res[i]))
                pre = res[i]
        return l
示例#5
0
    def getMain(self, codes, start=None, end=None):
        if start is None:
            start = public.getDate(diff=-5)
        if end is None:
            end = public.getDate()

        rs = []
        for c in codes:

            res = rq.get_dominant_future(c, start_date=start, end_date=end)
            if res is not None:
                rs.append(res.values[-1])
            else:
                rs.append(c + '88')
        return rs
def get_current_domain_future_info():
    for temp_future in need_to_monitor_future_list:
        temp_future_name = rq.get_dominant_future(temp_future,
                                                  time_of_today)[-1]
        temp_info = rq.instruments(temp_future_name)
        margin_rate = temp_info.margin_rate  # 保证金率
        contract_multiplier = temp_info.contract_multiplier  # 合约乘数
        margin_rate_list.append(margin_rate)
        contract_multiplier_list.append(contract_multiplier)
        symbol_list.append(temp_future_name)
    all_future_margin_and_contract_multiplier = pd.DataFrame({
        'future_name':
        symbol_list,
        'margin':
        margin_rate_list,
        'contract_multiplier':
        contract_multiplier_list
    })
    all_future_margin_and_contract_multiplier.to_csv(
        SAVE_PATH + "all_future_margin_and_contract_multiplier.csv")
示例#7
0
def main():
    action = {"main": 1, "update": 0, "tick": 0}
    W = interface_Rice()
    if action["main"] == 1:
        Base = future_baseInfo()
        codes = Base.getUsedMap(hasIndex=1)
        for code in codes:
            #for code in ['NI']:
            print('---------', code)
            #res = rq.get_dominant_future(code, start_date=public.getDate(diff=-100), end_date=public.getDate(diff=1))
            res = rq.get_dominant_future(code,
                                         start_date='2019-03-30',
                                         end_date='2019-05-15')
            if res is None: continue
            pre = ''
            for i in range(len(res)):
                if pre != res[i]:
                    print(res.index[i], res[i])
                    pre = res[i]

    if action["update"] == 1:
        updateNightEnd()

    if action["tick"] == 1:
        c1 = 'SR1909'
        period = 'tick'
        start = '2019-05-14'
        end = '2019-05-14'

        res = rq.get_price(c1,
                           frequency=period,
                           fields=W.columns,
                           start_date=start,
                           end_date=end,
                           adjust_type='pre')

        file = W.basePath + '%s_tick.csv' % (c1)
        print(res)
        print(c1, '---------------------------- to_cvs', file)
        res['datetime'] = res.index
        res.to_csv(file, columns=['datetime', 'last'] + W.columns, index=0)
future_name_list = []
margin_list = []
open_interest_list = []
open_interest_price_list = []
DATA_PATH = "E:\\future_data\\all_data\\"
NO_MAKER_DATA_PATH = "other_table\\"
original_all_future_table = pd.read_csv(DATA_PATH + NO_MAKER_DATA_PATH + "all_future.csv")
test1 = original_all_future_table['underlying_symbol'].drop_duplicates()
# 获取当天的日期并转换为rq需要的格式
time_of_today = datetime.datetime.now().strftime("%Y%m%d")
time_of_yesterday = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y%m%d")
last_trading_day = rq.get_previous_trading_date(time_of_today, n=1)
# date_list.append(last_trading_day)
for temp_future_name in test1:
    # 获取截止当天为止每个期货品种的主力合约
    temp_dominant_list = rq.get_dominant_future(temp_future_name, end_date=last_trading_day)
    print "当前合约为:" + temp_future_name
    # 最新的主力合约对应的具体合约
    newest_domiant_contract = pd.DataFrame(temp_dominant_list)
    if 'dominant' in newest_domiant_contract.columns:
        if not newest_domiant_contract['dominant'].empty:
            newest_domiant_contract = pd.DataFrame(temp_dominant_list)['dominant'].unique()[-1]
        else:
            continue
    else:
        continue
    # 最新具体合约的当天收盘价
    yesterday_price = pd.DataFrame(rq.get_price(newest_domiant_contract, start_date=last_trading_day,
                                                end_date=last_trading_day, frequency='1d'))
    newest_domiant_contract_close_price = yesterday_price['close']
    newest_domiant_contract_open_interest = yesterday_price['open_interest']
示例#9
0
import numpy as np
import pandas as pd
import rqdatac as rq
from rqdatac import *

rq.init()

startdate = pd.to_datetime('20100104')
enddate = pd.to_datetime('20190329')
cat_list = pd.read_csv("cat_list.csv", header=None)
cat_list = pd.Series(cat_list.iloc[:, 0])
df = pd.DataFrame()
#分品种提取主力合约
for i in range(0, len(cat_list)):
    dominants = rq.get_dominant_future(cat_list[i],
                                       start_date=startdate,
                                       end_date=enddate)
    df = df.join(pd.DataFrame(dominants), how='outer', rsuffix=cat_list[i])
df = df.reset_index()
df = df.rename(columns={'dominant': 'dominantA'})
df.to_csv("dominants.csv", index=None)
import DATA_CONSTANTS as DC
import os
from datetime import datetime
import time

rq.init()

startdate = '2014-01-01'
enddate = '2015-04-16'

bookid = pd.read_excel(DC.PUBLIC_DATA_PATH +
                       'domainMap.xlsx')['book_id'].tolist()
domain_map = pd.DataFrame()
for id in bookid:
    domain_map[id] = rq.get_dominant_future(id,
                                            start_date=startdate,
                                            end_date=enddate)
    print("%s finished" % id)
domain_map.to_csv('domain_list %s to %s.csv' % (startdate, enddate))

symboldf = pd.read_csv(DC.PUBLIC_DATA_PATH + 'contractMap.csv',
                       index_col='symbol')
exist_symbol_list = symboldf.index.tolist()
domain_map = pd.read_csv('domain_list %s to %s.csv' % (startdate, enddate))
rice_book_list = symboldf['rice_book_id'].drop_duplicates().tolist()
for id in rice_book_list:
    grouped = domain_map.groupby(id)
    first_date_list = grouped['date'].first()
    last_date_list = grouped['date'].last()
    symbollist = first_date_list.index.tolist()
    for symbol in symbollist: