diff --git a/TradeInterface/HistoryTrading.py b/TradeInterface/HistoryTrading.py index db427b6..c1d4d7f 100644 --- a/TradeInterface/HistoryTrading.py +++ b/TradeInterface/HistoryTrading.py @@ -2,7 +2,7 @@ import os import time import json -import urllib2 +import urllib.request import urllib import hashlib import sys @@ -167,7 +167,7 @@ def get_stock_dic(): def md5encryption(password): if password.strip() != '': md = hashlib.md5() - md.update(password) + md.update(password.encode("utf8")) return md.hexdigest() else: return '' @@ -176,8 +176,8 @@ def md5encryption(password): @staticmethod def http_post(send_dic, urlencode_name, url): jdata = json.dumps(send_dic) # json格式化编码 - jdata = urllib.urlencode({urlencode_name: jdata}) # urlencode编码 - req = urllib2.Request(url, jdata) # 生成页面请求的完整数据 - res = urllib2.urlopen(req) # 发送页面请求 + jdata = urllib.parse.urlencode({urlencode_name: jdata}).encode(encoding='UTF8') # urlencode编码 + req = urllib.request.Request(url, jdata) # 生成页面请求的完整数据 + res = urllib.request.urlopen(req) # 发送页面请求 temp_res = res.read() # 返回结果,把list结果处理为字符串显示 return temp_res diff --git a/TradeInterface/RealTimeTrading.py b/TradeInterface/RealTimeTrading.py index 7782181..54df784 100644 --- a/TradeInterface/RealTimeTrading.py +++ b/TradeInterface/RealTimeTrading.py @@ -2,15 +2,12 @@ import os import time import json -import urllib2 +import urllib.request import urllib import hashlib import sys -import pandas as pd +import importlib,sys -if sys.getdefaultencoding() != 'utf-8': - reload(sys) - sys.setdefaultencoding('utf-8') class RealTimeTrading(object): @@ -107,7 +104,7 @@ def get_stock_dic(): def md5encryption(password): if password.strip() != '': md = hashlib.md5() - md.update(password) + md.update(password.encode("utf8")) return md.hexdigest() else: return '' @@ -118,9 +115,9 @@ def http_post(send_dic, urlencode_name, url): jdata = json.dumps(send_dic) # json格式化编码 # print(jdata) # exit() - jdata = urllib.urlencode({urlencode_name: jdata}) # urlencode编码 - req = urllib2.Request(url, jdata) # 生成页面请求的完整数据 - res = urllib2.urlopen(req) # 发送页面请求 + jdata = urllib.parse.urlencode({urlencode_name: jdata}).encode(encoding='UTF8') # urlencode编码 + req = urllib.request.Request(url, jdata) # 生成页面请求的完整数据 + res = urllib.request.urlopen(req) # 发送页面请求 temp_res = res.read() # 返回结果,把list结果处理为字符串显示 return temp_res diff --git a/TradeInterface/TestEngine.py b/TradeInterface/TestEngine.py index 0edbaa1..2f1f22b 100644 --- a/TradeInterface/TestEngine.py +++ b/TradeInterface/TestEngine.py @@ -1,18 +1,21 @@ -#coding:utf-8 +# coding:utf-8 import datetime import json -from HistoryTrading import HistoryTrading -from RealTimeTrading import RealTimeTrading +from .HistoryTrading import HistoryTrading +from .RealTimeTrading import RealTimeTrading '''装饰器''' + + def input_checker(func): ''' 用于监测函数输入是否合法,code,volume均转化为str :param func: :return: ''' - def _input_checker(self,**kwargs): + + def _input_checker(self, **kwargs): # 股票代码检查 if isinstance(kwargs['code'], str): pass @@ -21,34 +24,35 @@ def _input_checker(self,**kwargs): while len(kwargs['code']) < 6: kwargs['code'] = '0' + kwargs['code'] else: - raise TypeError, 'code must be str or int' + raise TypeError('code must be str or int') # 股票交易量检查 if isinstance(kwargs['volume'], str): pass elif isinstance(kwargs['volume'], int): kwargs['volume'] = str(kwargs['volume']) else: - raise TypeError, 'volume must be str or int' - #回测日期检查 - if isinstance(self._core,HistoryTrading): + raise TypeError('volume must be str or int') + # 回测日期检查 + if isinstance(self._core, HistoryTrading): if 'date' not in kwargs: kwargs['date'] = self._current_time.strftime('%Y-%m-%d') - elif isinstance(kwargs['date'],datetime.datetime): + elif isinstance(kwargs['date'], datetime.datetime): kwargs['date'] = datetime.datetime.strftime('%Y-%m-%d') - elif isinstance(kwargs['date'],str): + elif isinstance(kwargs['date'], str): pass else: - raise TypeError,'date must be str or datetime object' - #返回函数 - print kwargs + raise TypeError('date must be str or datetime object') + # 返回函数 + print(kwargs) res = func(self, **kwargs) return res + return _input_checker class TestEngine(object): - def __init__(self,user_id='',password = '',type = 'RealTimeTrading'): + def __init__(self, user_id='', password='', type='RealTimeTrading'): ''' {'buy_sell': 'sell', 'code': '000006', 'volume': '100', 'price': '1', 'price_type': 'now_price', 'effect_term': '2'} :param user_id:用户id @@ -60,12 +64,13 @@ def __init__(self,user_id='',password = '',type = 'RealTimeTrading'): self._core = RealTimeTrading(userid=user_id, password=password) elif type == 'HistoryTrading': stratagy_name = user_id - self._current_time = datetime.datetime.today()-datetime.timedelta(days=1) - self._core = HistoryTrading(userid=user_id,password=password,strategy_name = stratagy_name) + self._current_time = datetime.datetime.today() - datetime.timedelta(days=1) + self._core = HistoryTrading(userid=user_id, password=password, strategy_name=stratagy_name) self._core.create_strategy(stratagy_name) else: - raise ValueError,'type must be "RealTimeTrading" or "HistoryTrading"' - #显示当前的交易引擎类型 + raise ValueError('type must be "RealTimeTrading" or "HistoryTrading"') + + # 显示当前的交易引擎类型 @property def core(self): ''' @@ -73,60 +78,62 @@ def core(self): :return: ''' return self._core.__class__ - #显示当前回测引擎时间 + + # 显示当前回测引擎时间 @property def current_time(self): ''' 返回当前的引擎时间,主要用于回测 :return: ''' - if isinstance(self._core,RealTimeTrading): + if isinstance(self._core, RealTimeTrading): return datetime.datetime.now().strftime('%Y-%m-%d,%H:%M:%S') - elif isinstance(self._core,HistoryTrading): + elif isinstance(self._core, HistoryTrading): return self._current_time.strftime('%Y-%m-%d') @current_time.setter - def current_time(self,date): + def current_time(self, date): ''' 自由设定引擎时间 :param date: :return: ''' - if isinstance(self._core,HistoryTrading): - if isinstance(date,str): - self._current_time = datetime.datetime.strptime(date,'%Y-%m-%d') - elif isinstance(date,datetime.datetime): + if isinstance(self._core, HistoryTrading): + if isinstance(date, str): + self._current_time = datetime.datetime.strptime(date, '%Y-%m-%d') + elif isinstance(date, datetime.datetime): pass else: - raise TypeError, '%s can not operate on current_time' % (self._core.__class__) + raise TypeError('%s can not operate on current_time' % (self._core.__class__)) - def shift_current_time(self,days): + def shift_current_time(self, days): ''' 按时间步长调整时间 :param days: :return: ''' - if isinstance(self._core,RealTimeTrading): - raise TypeError,'RealTimeTrading can not operate on current_time' - elif isinstance(self._core,HistoryTrading): + if isinstance(self._core, RealTimeTrading): + raise TypeError('RealTimeTrading can not operate on current_time') + elif isinstance(self._core, HistoryTrading): self._current_time += datetime.timedelta(days=days) return self._current_time.strftime('%Y-%m-%d') - #购买 + + # 购买 @input_checker - def buy(self,code,volume,price_type='now_price',price=None,date=None,effect_term = 1): - if isinstance(self._core,RealTimeTrading): - dic = {'code':code, - 'volume':volume, + def buy(self, code, volume, price_type='now_price', price=None, date=None, effect_term=1): + if isinstance(self._core, RealTimeTrading): + dic = {'code': code, + 'volume': volume, 'price_type': price_type, 'price': price, - 'effect_term':str(effect_term)} + 'effect_term': str(effect_term)} self._core.set_stock_dic(dic) res = self._core.buy() return json.loads(res) - elif isinstance(self._core,HistoryTrading): + elif isinstance(self._core, HistoryTrading): if not date: date = self._current_time.strftime("%Y-%m-%d") - dic = {'date':date, + dic = {'date': date, 'code': code, 'volume': volume, 'price_type': 'average_price', @@ -134,19 +141,20 @@ def buy(self,code,volume,price_type='now_price',price=None,date=None,effect_term self._core.set_stock_dic(dic) res = self._core.bt_buy() return json.loads(res) - #卖出 + + # 卖出 @input_checker - def sell(self,code,volume,price_type='now_price',price=None,date=None,effect_term = 1): - if isinstance(self._core,RealTimeTrading): - dic = {'code':code, - 'volume':volume, + def sell(self, code, volume, price_type='now_price', price=None, date=None, effect_term=1): + if isinstance(self._core, RealTimeTrading): + dic = {'code': code, + 'volume': volume, 'price_type': price_type, 'price': price, - 'effect_term':str(effect_term)} + 'effect_term': str(effect_term)} self._core.set_stock_dic(dic) res = self._core.sell() return json.loads(res) - elif isinstance(self._core,HistoryTrading): + elif isinstance(self._core, HistoryTrading): if not date: date = self._current_time.strftime("%Y-%m-%d") dic = {'date': date, @@ -157,60 +165,64 @@ def sell(self,code,volume,price_type='now_price',price=None,date=None,effect_ter self._core.set_stock_dic(dic) res = self._core.bt_sell() return json.loads(res) - #撤单 - def cancel_order(self,pre_id): - if isinstance(self._core,RealTimeTrading): + + # 撤单 + def cancel_order(self, pre_id): + if isinstance(self._core, RealTimeTrading): return self._core.cancel_order(pre_id) else: raise TypeError - #资产和持仓情况 + + # 资产和持仓情况 def query_profit(self): if isinstance(self._core, RealTimeTrading): return json.loads(self._core.query_profit()) - elif isinstance(self._core,HistoryTrading): + elif isinstance(self._core, HistoryTrading): pass - #委托查询 - def query_records(self,start="2018-4-4", end="2018-04-05"): - if isinstance(self._core,RealTimeTrading): - return json.loads(self._core.query_records(start,end)) - #历史交割查询 - def query_history_records(self,start='',end=''): - if isinstance(self._core,RealTimeTrading): - return json.loads(self._core.query_history_records(start,end)) - elif isinstance(self._core,HistoryTrading): + + # 委托查询 + def query_records(self, start="2018-4-4", end="2018-04-05"): + if isinstance(self._core, RealTimeTrading): + return json.loads(self._core.query_records(start, end)) + + # 历史交割查询 + def query_history_records(self, start='', end=''): + if isinstance(self._core, RealTimeTrading): + return json.loads(self._core.query_history_records(start, end)) + elif isinstance(self._core, HistoryTrading): return json.loads(self._core.bt_query_history_records(start, end)) - #历史交割单输出到csv文件 - def history_to_csv(self,path='history_record'): - if isinstance(self._core,RealTimeTrading): + + # 历史交割单输出到csv文件 + def history_to_csv(self, path='history_record'): + if isinstance(self._core, RealTimeTrading): pass - elif isinstance(self._core,HistoryTrading): + elif isinstance(self._core, HistoryTrading): return self._core.get_history_csv(path) - #查询策略 + + # 查询策略 def list_stratagy(self): - if isinstance(self._core,HistoryTrading): + if isinstance(self._core, HistoryTrading): return json.loads(self._core.get_strategy()) else: - raise AttributeError, '%s has no attribute stratagy_name' % (self._core.__class__) + raise AttributeError('%s has no attribute stratagy_name' % (self._core.__class__)) + # 设置策略名称 def set_stratagy(self, stratagy_name): if isinstance(self._core, HistoryTrading): self._core.set_strategy_name(stratagy_name) else: - raise AttributeError, '%s has no attribute stratagy_name' % (self._core.__class__) - #创建策略 - def create_stratagy(self,stratagy_name): - if isinstance(self._core,HistoryTrading): + raise AttributeError('%s has no attribute stratagy_name' % (self._core.__class__)) + + # 创建策略 + def create_stratagy(self, stratagy_name): + if isinstance(self._core, HistoryTrading): return self._core.create_strategy(stratagy_name) else: raise AttributeError - #删除策略 - def del_stratagy(self,stratagy_name): - if isinstance(self._core,HistoryTrading): + + # 删除策略 + def del_stratagy(self, stratagy_name): + if isinstance(self._core, HistoryTrading): return self._core.del_strategy(stratagy_name) else: - raise AttributeError, '%s has no attribute stratagy_name' % (self._core.__class__) - - - - - + raise AttributeError('%s has no attribute stratagy_name' % (self._core.__class__)) diff --git a/TradeInterface/TradeInterface.py b/TradeInterface/TradeInterface.py index 8fe0b2b..6519b1c 100644 --- a/TradeInterface/TradeInterface.py +++ b/TradeInterface/TradeInterface.py @@ -11,14 +11,13 @@ import os import time import json -import urllib2 +import urllib.request import urllib import hashlib import sys import pandas as pd -if sys.getdefaultencoding() != 'utf-8': - reload(sys) - sys.setdefaultencoding('utf-8') +import importlib,sys + class Trade: @@ -126,9 +125,9 @@ def http_post(send_dic, urlencode_name, url): jdata = json.dumps(send_dic) # json格式化编码 # print(jdata) # exit() - jdata = urllib.urlencode({urlencode_name: jdata}) # urlencode编码 - req = urllib2.Request(url, jdata) # 生成页面请求的完整数据 - res = urllib2.urlopen(req) # 发送页面请求 + jdata = urllib.parse.urlencode({urlencode_name: jdata}) # urlencode编码 + req = urllib.request.Request(url, jdata) # 生成页面请求的完整数据 + res = urllib.request.urlopen(req) # 发送页面请求 temp_res = res.read() # 返回结果,把list结果处理为字符串显示 return temp_res @@ -159,7 +158,7 @@ def __init__(self, userid='', strategy_name='', password=''): self.stock_encode_name = 'tradeinfo' self.query_pro_encode_name = 'query_info' self.cancel_encode_name = 'cancel_info' - self.send_dic = {'userid': '', 'password': '', 'buy_sell_type': '', 'strategy_name': '', 'stock_dic': {}} + self.send_dic = {'userid': '', 'password': '', 'buy_sell_type': '', 'strategy_name': '', 'stock_dic': {}} self.set_userid(userid) self.set_password(password) self.set_strategy_name(strategy_name) @@ -203,7 +202,7 @@ def get_history_csv(self, csv_path=''): for idx in data.index: line = data.loc[idx] if line['trade_type'] == '3': # 卖出成交量设为负 - line['Volume'] = '-'+line['Volume'] + line['Volume'] = '-' + line['Volume'] if line['trade_type'] == '1': # 买入发生金额设为负 line['hap_fund'] = '-' + line['hap_fund'] @@ -215,10 +214,10 @@ def get_history_csv(self, csv_path=''): # 转换列表名 data = data.rename(columns={'timestamp': '成交时间', 'SecurityID': '代码', 'Symbol': '名称', 'trade_type': '操作', 'price_order': '委托价', 'price_deal': '成交价', 'Volume': '成交量', 'fund_deal': '成交金额', - 'fee': '手续费', 'tax': '印花税', 'other_fee': '其他杂费', 'security_holding': '证券余额', + 'fee': '手续费', 'tax': '印花税', 'other_fee': '其他杂费', 'security_holding': '证券余额', 'hap_fund': '发生金额', 'remain_fund': '现金余额'}) - data.to_csv(csv_path+'/交割单.csv', sep=",", index=False, encoding='gbk') + data.to_csv(csv_path + '/交割单.csv', sep=",", index=False, encoding='gbk') return 'generate trade csv success!' @@ -301,13 +300,13 @@ def md5encryption(password): @staticmethod def http_post(send_dic, urlencode_name, url): jdata = json.dumps(send_dic) # json格式化编码 - jdata = urllib.urlencode({urlencode_name: jdata}) # urlencode编码 - req = urllib2.Request(url, jdata) # 生成页面请求的完整数据 - res = urllib2.urlopen(req) # 发送页面请求 + jdata = urllib.parse.urlencode({urlencode_name: jdata}) # urlencode编码 + req = urllib.request.Request(url, jdata) # 生成页面请求的完整数据 + res = urllib.request.urlopen(req) # 发送页面请求 temp_res = res.read() # 返回结果,把list结果处理为字符串显示 return temp_res if __name__ == '__main__': trade = Trade() - print "".isdigit() + print("".isdigit()) diff --git a/TradeInterface/__init__.py b/TradeInterface/__init__.py index 72e4ec7..da98e5e 100644 --- a/TradeInterface/__init__.py +++ b/TradeInterface/__init__.py @@ -1,12 +1,9 @@ #coding:utf-8 -import sys -if sys.getdefaultencoding() != 'utf-8': - reload(sys) - sys.setdefaultencoding('utf-8') +import importlib,sys -from HistoryTrading import HistoryTrading -from RealTimeTrading import RealTimeTrading -from TestEngine import TestEngine +from .HistoryTrading import HistoryTrading +from .RealTimeTrading import RealTimeTrading +from .TestEngine import TestEngine __all__ = ['RealTimeTrading', 'HistoryTrading', diff --git a/setup.py b/setup.py index ba4f930..76de3ee 100644 --- a/setup.py +++ b/setup.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -#-*- coding:utf-8 -*- +# -*- coding:utf-8 -*- ############################################# # File Name: setup.py @@ -12,18 +12,18 @@ from setuptools import setup, find_packages setup( - name = "TradeInterface", - py_modules = ['TradeInterface'], - version = "0.2.7", - keywords = ("pip", "TradeInterface","trade",'haizhi'), - description = "a interface of simulate-trading stocks", - long_description = "a interface of simulate-trading stocks", - license = "MIT Licence", - url = "https://github.com/Inistlwq/TradeInterface", - author = "cb_Lian", - author_email = "787162506@qq.com", + name="TradeInterface", + py_modules=['TradeInterface'], + version="0.2.9", + keywords=("pip", "TradeInterface", "trade", 'haizhi'), + description="a interface of simulate-trading stocks", + long_description="a interface of simulate-trading stocks", + license="MIT Licence", + url="https://github.com/RManOfCN/TradeInterface.git", + author="Raymond Luo", + author_email="luolinhao1998@gmail.com", - packages = find_packages(), - include_package_data = True, - platforms = "any" -) \ No newline at end of file + packages=find_packages(), + include_package_data=True, + platforms="any" +) diff --git a/test.py b/test.py index 5f7bef6..b53468a 100644 --- a/test.py +++ b/test.py @@ -1,37 +1,43 @@ -#coding:utf-8 +# coding:utf-8 from TradeInterface import TestEngine import datetime import json '''实盘交易引擎示例''' -user_id ='18126352115' +user_id = '18126352115' password = 'Cloud25683' + + def Realtime(): ''' 实盘交易引擎 :return: ''' - Engine = TestEngine(user_id=user_id,password=password,type='RealTimeTrading') - print Engine.core - print Engine.current_time - #print Engine.buy(code='600848',volume=100) - #print Engine.sell(code='600848', volume=100) + Engine = TestEngine(user_id=user_id, password=password, type='RealTimeTrading') + print(Engine.core) + print(Engine.current_time) + # print Engine.buy(code='600848',volume=100) + # print Engine.sell(code='600848', volume=100) temp = Engine.query_records(start="2018-04-25", end="2018-04-26") - print len(temp) - print temp[0]['pre_id'] - print Engine.cancel_order(str(temp[0]['pre_id'])) - print Engine.query_history_records(start="2018-4-4", end="2018-04-05") - print Engine.query_profit() + print(len(temp)) + print(temp[0]['pre_id']) + print(Engine.cancel_order(str(temp[0]['pre_id']))) + print(Engine.query_history_records(start="2018-4-4", end="2018-04-05")) + print(Engine.query_profit()) + + '''历史回测引擎示例''' + + def History(): ''' 历史回测引擎 :return: ''' - Engine = TestEngine(user_id=user_id,password=password,type='HistoryTrading') - print Engine.core - print Engine.current_time - print Engine.list_stratagy() + Engine = TestEngine(user_id=user_id, password=password, type='HistoryTrading') + print(Engine.core) + print(Engine.current_time) + print(Engine.list_stratagy()) if Engine.list_stratagy(): Engine.del_stratagy(Engine.list_stratagy()[0]['strategy_name']) Engine.create_stratagy(user_id) @@ -39,16 +45,16 @@ def History(): else: Engine.create_stratagy(user_id) Engine.set_stratagy(user_id) - print Engine.buy(code =600848,volume=1000,date = '2017-10-11') + print(Engine.buy(code=600848, volume=1000, date='2017-10-11')) Engine.current_time = '2018-4-8' Engine.shift_current_time(1) - print Engine.current_time - print Engine.sell(code='600848',volume=100) - print Engine.history_to_csv('data') + print(Engine.current_time) + print(Engine.sell(code='600848', volume=100)) + print(Engine.history_to_csv('data')) if __name__ == '__main__': - #Realtime() + # Realtime() History() ''' Engine.shift_current_time(-20) @@ -70,5 +76,3 @@ def History(): #print type(Engine.current_time) #print Engine.shift_current_time(1) ''' - -