Python_9.10_量化交易_main详解(二)

  • print(ParaCom)
  • 1-19
  • 20-40
  • 41-76


print(ParaCom)
Exchanges = pd.read_csv(roots + 'Exchanges.csv', index_col=0) # 换月合约文件, 包含current
    ExchangeIf = 1
    Positions = pd.read_csv(roots + 'Positions.csv', index_col=0) # 合约持仓, 包含prelong preshort
    print(Positions)
    farmer = pd.read_csv(roots + 'farm_com.csv', index_col= 'unique') # 各个商品在策略中的状态 包含以下字段
    farmer['precise'] = farmer['underlying'].map(lambda x: GoodTick[x.lower()] / 2.0)
    farmer['loss'] = ParaCom['loss'] # 止损
    farmer['profit'] = ParaCom['profit'] # 止盈
    farmer['pct'] = ParaCom['pct'] # 比例
    farmer['side'] =  ParaCom['side']
    farmer['soil'] = ParaCom['soil']
    farmer['advance'] = ParaCom['advance']
    farmer['last_max'] = 0
    farmer['last_min'] = 0
    farmer['last'] = 0
    farmer['newopen'] = 0
    farmer['newif'] = 0
    farmer['target'] = 0
    len_scheme = len(set(farmer['scheme'] + farmer['contract']))
    if (len(set(farmer.index)) < len(farmer)) or (len_scheme < len(farmer)):
        print("scheme and contract Error")
        time.sleep(10000)
    Exchanges = Exchanges[Exchanges['ComingContract'].map(lambda x: len(str(x)))> 3]
    Exchanges = Exchanges[Exchanges.index.isin(cover)]
    Exchanges['diff'] = 0
    print("Exchanges:")
    print(Exchanges)
    print(len(Exchanges))
    farm = farmer[farmer['underlying'].isin(cover)]
    rest = farmer[~farmer['underlying'].isin(cover)]
    contlist = list(set(farm['contract'])) # 当前交易日farm交易的主力合约
    booklist = list(set(farm['contract'])|set(Exchanges['ComingContract']) )
    if '0' in booklist:
        booklist.remove('0')
    if 0 in booklist:
        booklist.remove(0)
    contract_To_underlying = dict() # 建立合约到品种字典
    for item in booklist:
        contract_To_underlying[item] = ''.join(list(filter(str.isalpha, item))).lower()
    print(contract_To_underlying)
    db = MySQLdb.connect(host="localhost", port=8888, user="root", passwd="", db="quotenew")
    connects = db.cursor()
    for cont in contlist:
        tabname = 'q_min_' + contract_To_underlying[cont]  # 所有品种表名是小写
        keys = "InstrumentID, ActionDay"
        cond = " InstrumentID ='" + cont + "';"
        sqlline = "SELECT " + keys + " FROM " + tabname + " where " + cond
        connects.execute(sqlline)
        results = connects.fetchall()  # 获取查询结果
        print('len of '  + cont + " =     " +  str(len(results)))
        if len(results) > Goodminslen[contract_To_underlying[cont]]: #
            print(" - - - - - Cont Minute Len Error - - - - - ")
            time.sleep(100000)
    print("farm  :")
    print(farm[['longif', 'longval', 'shortif', 'shortval']])
    print(farm[['position', 'unit', 'longIn', 'longhighest', 'shortIn', 'shortlowest']])
    print("rest  :")
    print(rest)
    Kdict = dict()  # K bar Data # 这里涉及到品种夜盘交易结束后 第二天开盘前 K线数据如何选取的问题
    preKtimeDict = dict()  # 品种期货
    newopentimeDict = dict()  # 新区间 时间戳
    for item in booklist:
        preKtimeDict[item] = int(str(nowday) + preKtime) # 设定上一根K线到达的时间
        lastdaybar = pd.DataFrame(columns=['future', 'date', 'time', 'open', 'high', 'low', 'close', 'stamp'])
        for day in daylist: # 读入过去交易日的分钟数据
            fn = '.\MinuteBarData' + '\\' + item.lower() + '_' + str(day) + '_minutebar' + '.csv'  # 文件名
            daybar = pd.read_csv(fn) # index_col = 0
            daybar['stamp'] = daybar['date'] * 1000000 + daybar['time']
            daybar['future'] = item
            daybar = daybar[['future', 'date', 'time', 'open', 'high', 'low', 'close', 'stamp']]
            lastdaybar = lastdaybar.append(daybar)
        if time.time() < int(time.mktime(time.strptime(str(nowday) + '-' + preKtime, "%Y%m%d-%H%M%S"))):
            farm = Signal(lastdaybar, farm, item)  # 最后一根bar重新计算
        Kdict[item] = lastdaybar  # 同一品种的不同合约上可能会有交易,选用合约名做键值
    print("preKtimeDict: ")
    print(preKtimeDict)

print(ParaCom)

策略是收盘120的最高价,就买入,里面存的就是120,保存参数的一个文件,precise等等等……

1-19

1.Exchanges = pd.read_csv(roots + 'Exchanges.csv', index_col=0) 2.ExchangeIf = 1 3.Positions = pd.read_csv(roots + 'Positions.csv', index_col=0) 4.print(Positions) 5.farmer = pd.read_csv(roots + 'farm_com.csv', index_col= 'unique')

farm是指一个不停更新的参数表,就实时更新最新的数据,然后发过来保存
unique是指索引,以unique为索引

6.farmer['precise'] = farmer['underlying'].map(lambda x: GoodTick[x.lower()] / 2.0)

一旦购买的,买入价,最高价,各种数据,卖出价,持仓状态的记录,position,仓位,
9:30没有买茅台,就是0,10点了,它欠我就是1,我欠它就是-1。
GoodTick里x.lower()是把goodtick里的都变成小写

# 一跳大小
goodtick = {‘if’: 0.2, ‘ic’: 0.2, ‘ih’: 0.2, ‘tf’: 0.005, ‘t’: 0.005, ‘ts’: 0.005, # 金融期货
‘au’: 0.02, ‘ag’: 1.0, # 贵金属
‘cu’: 10.0, ‘al’: 5.0, ‘zn’: 5.0, ‘pb’: 5.0, ‘ni’: 10.0, ‘sn’: 10.0, # 有色
‘jm’: 0.5, ‘j’: 0.5, ‘rb’: 1.0, ‘i’: 0.5, ‘hc’: 1.0, ‘ss’: 5.0, ‘wr’: 1.0, ‘sm’: 2.0, ‘sf’: 2.0,
# 焦煤钢矿
‘fg’: 1.0, ‘v’: 5.0, ‘fb’: 0.5, ‘bb’: 0.05, # 建材
‘sc’: 0.1, ‘zc’: 0.2, ‘fu’: 1.0, ‘pg’: 1.0, ‘lu’: 1.0, # 能源
‘bu’: 2.0, ‘ru’: 5.0, ‘sp’: 2.0, ‘nr’: 5.0, ‘l’: 5.0, ‘ta’: 2.0, ‘eg’: 1.0, # 化工
‘ma’: 1.0, ‘pp’: 1.0, ‘eb’: 2.0, ‘ur’: 1.0, ‘sa’: 1.0, # 化工
‘c’: 1.0, ‘wh’: 1.0, ‘pm’: 1.0, ‘rr’: 1.0, ‘ri’: 1.0, ‘jr’: 1.0, ‘lr’: 1.0, # 谷物
‘a’: 1.0, ‘b’: 1.0, ‘m’: 1.0, ‘y’: 2.0, ‘rs’: 1.0, ‘rm’: 1.0, ‘oi’: 1.0, ‘p’: 2.0, # 油脂油料
‘cf’: 5.0, ‘sr’: 1.0, ‘cy’: 5.0, # 软商品
‘jd’: 1.0, ‘ap’: 1.0, ‘cj’: 5.0, ‘cs’: 1.0} # 农副产品

map根据提供的函数对指定序列做映射。

map(lambda x: x ** 2, [1, 2, 3, 4, 5]) # 使用 lambda 匿名函数, 每个位置都平方
[1, 4, 9, 16, 25]

提供了两个列表,对相同位置的列表数据进行相加

map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]

7.farmer['loss'] = ParaCom['loss']# 止损
8.farmer['profit'] = ParaCom['profit'] # 止盈
9.farmer['pct'] = ParaCom['pct'] # 比例
10.farmer['side'] = ParaCom['side'] 11.farmer['soil'] = ParaCom['soil'] 12.farmer['advance'] = ParaCom['advance'] 13.farmer['last_max'] = 0 14.farmer['last_min'] = 0 15.farmer['last'] = 0 16.farmer['newopen'] = 0 17.farmer['newif'] = 0 18.farmer['target'] = 0 farmer是从farm_com.csv取出来的,这
19.len_scheme = len(set(farmer['scheme'] + farmer['contract']))这是两个字符串相连

20-40

20.if (len(set(farmer.index)) < len(farmer)) or (len_scheme < len(farmer)): 要求一个scheme下只有一个同一合约, index是唯一的
famer的index是unique(之前定义的),
它本身的len是条数
set是一个去重,也就是说这个列表里,横向的合约如果有重复的,那么去重以后的条数就会少于整体的条数,就报错

21.print("scheme and contract Error") 22.time.sleep(10000) 报错进入休眠,就可以开始调试

下一阶段进入交易的合约 部分合约无夜盘
上期 / 能源所 / 大商所 小写 + 4个数字
中金所 大写 + 4个数字
郑商所 大写 + 3个数字
[‘rb2010’, ‘ni2008’, ‘au2012’, ‘j2009’]
farm进入交易的合约,rest不在交易时间

23.Exchanges = Exchanges[Exchanges['ComingContract'].map(lambda x: len(str(x)))> 3]

跳过

Exchanges = pd.read_csv(roots + ‘Exchanges.csv’, index_col=0) # 换月合约文件, 包含current

24.Exchanges = Exchanges[Exchanges.index.isin(cover)]

新表格,在Exchanges里的index这列中,含有cover的行就是TRUE
跳过

cover是BasicCont/MoonCont,白天/夜晚连续交易的商品期货集合

A B C D E
0 -0.018330 2.093506 -0.086293 -2.150479 a
1 0.104931 -0.271810 -0.054599 0.361612 a
2 0.590216 0.218049 0.157213 0.643540 c
3 -0.254449 -0.593278 -0.150455 -0.244485 b
df.E.isin([‘a’,‘c’])
0 True
1 True
2 True
3 False

25.Exchanges['diff'] = 0 26.print("Exchanges:") 27.print(Exchanges) 28.print(len(Exchanges)) 29.farm = farmer[farmer['underlying'].isin(cover)]跳过《

30.rest = farmer[~farmer['underlying'].isin(cover)]

~ : 逐位取反

31.contlist = list(set(farm['contract'])) # 当前交易日farm交易的主力合约

32.booklist = list(set(farm['contract'])|set(Exchanges['ComingContract']) )

包括尾盘移仓的合约

33.if '0' in booklist:

34.booklist.remove('0')

35.if 0 in booklist:

36.booklist.remove(0) 37.contract_To_underlying = dict() # 建立合约到品种字典
38.for item in booklist: 39.contract_To_underlying[item] = ''.join(list(filter(str.isalpha, item))).lower()

》跳过

40.print(contract_To_underlying)

41-76

41.db = MySQLdb.connect(host="localhost", port=8888, user="root", passwd="", db="quotenew")

连接数据库

42.connects = db.cursor()

使用连接对象获得一个cursor对象

43.for cont in contlist:

contlist = list(set(farm[‘contract’])) # 当前交易日farm交易的主力合约

44.tabname = 'q_min_' + contract_To_underlying[cont] # 所有品种表名是小写

contract_To_underlying[item] = ‘’.join(list(filter(str.isalpha, item))).lower()

45.keys = "InstrumentID, ActionDay" 46.cond = " InstrumentID ='" + cont + "';" 47.sqlline = "SELECT " + keys + " FROM " + tabname + " where " + cond 48.connects.execute(sqlline)

从tabname里筛出满足InstrumentID = ‘contlist’;InstrumentID, ActionDay

使用execute方法执行SQL语句
cursor.execute(“SELECT VERSION()”)

49.results = connects.fetchall() # 获取查询结果

使用 fetchone() 方法获取一条数据
data = cursor.fetchone()

50.print('len of ' + cont + " = " + str(len(results))) 51.if len(results) > Goodminslen[contract_To_underlying[cont]]:

52.print(" - - - - - Cont Minute Len Error - - - - - ") 53.time.sleep(100000)

54.print("farm :") 55.print(farm[['longif', 'longval', 'shortif', 'shortval']]) 56.print(farm[['position', 'unit', 'longIn', 'longhighest', 'shortIn', 'shortlowest']]) 57.print("rest :") 58.print(rest) 59.Kdict = dict() K bar Data
这里涉及到品种夜盘交易结束后 第二天开盘前 K线数据如何选取的问题

60.preKtimeDict = dict() # 品种期货

61.newopentimeDict = dict() # 新区间 时间戳

62.for item in booklist:

booklist = list(set(farm[‘contract’])|set(Exchanges[‘ComingContract’]) )

63.preKtimeDict[item] = int(str(nowday) + preKtime) # 设定上一根K线到达的时间
64.lastdaybar = pd.DataFrame(columns=['future', 'date', 'time', 'open', 'high', 'low', 'close', 'stamp']) 65.for day in daylist: # 读入过去交易日的分钟数据
66.fn = '.\MinuteBarData' + '\\' + item.lower() + '_' + str(day) + '_minutebar' + '.csv'# 文件名
67.daybar = pd.read_csv(fn) # index_col = 0
68.daybar['stamp'] = daybar['date'] * 1000000 + daybar['time']8位和6位凑成14位

69.daybar['future'] = item 70.daybar = daybar[['future', 'date', 'time', 'open', 'high', 'low', 'close', 'stamp']] 71.lastdaybar = lastdaybar.append(daybar)

append() 方法用于在列表末尾添加新的对象。

72.if time.time() < int(time.mktime(time.strptime(str(nowday) + '-' + preKtime, "%Y%m%d-%H%M%S"))): 盘中中断重启时这里不需要计算信号
73.farm = Signal(lastdaybar, farm, item) # 最后一根bar重新计算
每隔一分钟(一次K线的生成)就会做出一次signal的更新,signal更新的是四个参数,

def Signal(bardata, sigdf, cont):

74.Kdict[item] = lastdaybar # 同一品种的不同合约上可能会有交易,选用合约名做键值

75.print("preKtimeDict: ") 76.print(preKtimeDict)