def getTime(self): """ 获取最小起始日期和min{最大交割日日期,当前日期} """ post = postgersql() colname = ['trade_date','delivery_date','currency_pair','dates'] sql = """select op.trade_date,op.delivery_date,op.currency_pair, case when t.dates<op.delivery_date then date(t.dates)+1 when t.dates=op.delivery_date then current_date end as dates from %s op left join (select max(pt.date) as dates,pt.der_id from %s pt group by pt.der_id) t on op.trade_type||'_'||op.id = t.der_id """%(self.table,self.querytable) time = post.view(sql,colname) if time==[] or time==None: self.begintime = None self.endtime = None else: time = filter(lambda x:x['currency_pair'] in getrate() and dateTostr(x['delivery_date'])>=getrate()[x['currency_pair']],time) #print len(time) for lst in time: if lst['dates'] is None: lst['dates'] = dateTostr(lst['trade_date']) if dateTostr(lst['trade_date'])>getrate()[lst['currency_pair']] else getrate()[lst['currency_pair']] else: lst['dates'] = dateTostr(lst['dates']) begintime = time[0]['dates'] if len(time)==1 else min(map(lambda x:x['dates'],time)) self.begintime = begintime if getNow('%Y-%m-%d')>=begintime else None endtime = dateTostr(time[0]['delivery_date'] if len(time)==1 else max(map(lambda x:x['delivery_date'],time))) self.endtime = endtime if getNow('%Y-%m-%d')>endtime else timedelta(getNow('%Y-%m-%d'),-1)
def cumputeLost(self): """ """ Time = dateTostr(self.Now) Lost = [] self.forwarddict = [] for trade_id in self.trfdata: spotList = self.trfdata[trade_id]['spotList'] orderlist = self.trfdata[trade_id]['orderlist'] S = self.trfdata[trade_id]['S'] K = self.trfdata[trade_id]['K'] SellRate = self.trfdata[trade_id]['SellRate'] BuyRate = self.trfdata[trade_id]['BuyRate'] Now = self.trfdata[trade_id]['Now'] lags = self.trfdata[trade_id]['lags'] TIV = self.trfdata[trade_id]['TIV'] amount = self.trfdata[trade_id]['amount'] #print 'knockoptions',lst['id'],currency_pair,dateTostr(lst['trade_date']),deliverydate, TRF = TargetRedemptionForward(spotList, orderlist, S, K, SellRate, BuyRate, lags, Now, TIV) ##计算损益值 gal = 0 for lst in TRF: lst['price'] = ( lst['price'] * amount) if lst['price'] is not None else lst['price'] gal += lst['price'] if TRF is not None: Lost.extend(TRF) """ 'date','com_code','der_id','cap_currency','cap_amount','gal','exrate','data_date': 日期,公司代码,衍生品编号,本金币种,本金金额,汇兑损益,当天的本金/人民币汇率,数据生成日期 """ forwarddict = {} forwarddict['date'] = Time forwarddict['com_code'] = self.trfdata[trade_id]['consign_entity'] forwarddict['der_id'] = self.trfdata[trade_id][ 'trade_type'] + '_' + str(self.trfdata[trade_id]['id']) forwarddict['gal'] = gal forwarddict['cap_amount'] = amount forwarddict['cap_currency'] = self.trfdata[trade_id]['currency'] currencypair = forwarddict['cap_currency'] + 'CNY' forwarddict['exrate'] = gethistoryrate( [currencypair], Time)[currencypair] if currencypair != 'CNYCNY' else 1.0 forwarddict['data_date'] = getNow('%Y-%m-%d %H:%M:%S') logs('compute', 'targetforwards', 'cumputeLost', forwarddict, infoFalg=True) self.forwarddict.append(forwarddict) self.updateData()
def setrate(): from database.database import mongodb ## mongo connect from help.help import getNow, strTostr ##get current datetime key = {'code': True} Time = strTostr(getNow('%Y-%m-%d')) initial = {'Time': Time} reduces = """function(doc,prev){ if (prev.Time>doc.Time){ prev.Time = doc.Time }}""" condition = {'type': '5'} db = mongodb() rate = db.group('kline', key, condition, initial, reduces) rate = map(lambda x: {x['code']: x['Time'].split()[0]}, rate) globalrate.rate = reduce(lambda x, y: dict(x, **y), rate) db.close()
def datafill(spots): """ 填充无交易日期的汇率 以上一个交易日的的收盘价进行填充 """ Now = getNow(format='%Y-%m-%d') spot = spots.copy() spot = pd.merge(pd.DataFrame(dateseris(spot['Time'].min(), Now), columns=['Time']), spot[['Time', 'Close']], on=['Time'], how='left') spot = spot.sort_values('Time') for i in range(spot.shape[0]): if spot['Close'].values[i].__str__() == 'nan': spot['Close'].values[i] = spot['Close'].values[i - 1] return spot
def getMax(self): """ 获取利率最大的日期对应的日期 """ key={'index':True} Time = strTostr(getNow('%Y'),'%Y') initial ={'rate':0,'datadate':Time} reduces = """function(doc,prev){ if (prev.datadate<doc.datadate){ prev.rate = doc.rate; prev.datadate = doc.datadate }}"""##遍历寻找当前最大汇率值 ratetype ='12月' condition={'ratetype':ratetype,'index':self.code} data = self.__mongo.group('KPI',key,condition,initial,reduces) self.__mongo.close() return data
def getDataFromMongo(self): """ from mongo get the currency_pairs and bank_rate """ ## currency_pairs currency_pairs = list(set(map(lambda x: x['currency_pair'], self.data))) Time = self.Now.split()[0] #currency_dict = getcurrentrate(currency_pairs) currency_dict = gethistoryrate(currency_pairs, Time) ##bank_rate self.forwarddict = [] for lst in self.data: forwarddict = {} sell_currency = lst['currency_pair'][:3] buy_currency = lst['currency_pair'][3:] currency_pair = lst['currency_pair'] #ratetype = getRate((lst['delivery_date'] -lst['trade_date']).days) ratetype = '12月' #SellRate,BuyRate = getcurrentbankrate(sell_currency,buy_currency,ratetype) SellRate, BuyRate = gethistorybankrate(sell_currency, buy_currency, ratetype, Time) ##获取银行历史拆借利率 #sell_amount = float64(lst['sell_amount']) #buy_amount = float64(lst['buy_amount']) ##获取厘定日的汇率,如果还未到厘定日,那么汇率返回None Setdate = dateTostr(lst['determined_date']) ##厘定日 if Setdate is None: Setdate = dateTostr(lst['delivery_date']) if Time < Setdate: SetRate = None else: SetRate = RateExchange(currency_pair).getdayMax( Setdate) ##厘定日汇率 #SetRate = RateExchange(currency_pair).getdayMax(Setdate)##厘定日汇率 if SetRate == []: SetRate = None ## 还未到厘定日 ## 执行汇率上下限 strikeLowerRate = float64(lst['exe_doexrate']) strikeUpperRate = float64(lst['exe_upexrate']) currentRate = currency_dict.get(currency_pair) if currentRate is None: print "{ } not Fund!\n".format(currency_pair) continue deliverydate = dateTostr(lst['delivery_date']) #print 'CollaOptions',lst['id'],currency_pair,dateTostr(lst['trade_date']),deliverydate, temp = self.cumputeLost(Setdate, SetRate, deliverydate, strikeLowerRate, strikeUpperRate, currentRate, SellRate, BuyRate, self.delta) #if forwarddict[lst['id']] is not None: ## 计算本金损益 #forwarddict[lst['id']] = chooselocalmoney(lst,forwarddict[lst['id']]) """ 'date','com_code','der_id','cap_currency','cap_amount','gal','exrate','data_date': 日期,公司代码,衍生品编号,本金币种,本金金额,汇兑损益,当天的本金/人民币汇率,数据生成日期 """ if temp is not None: forwarddict['gal'], forwarddict['cap_amount'], forwarddict[ 'cap_currency'] = chooselocalmoney(lst, temp) forwarddict['date'] = Time forwarddict['com_code'] = lst['consign_entity'] forwarddict['der_id'] = lst['trade_type'] + '_' + str(lst['id']) currencypair = forwarddict['cap_currency'] + 'CNY' forwarddict['exrate'] = gethistoryrate( [currencypair], Time)[currencypair] if currencypair != 'CNYCNY' else 1.0 forwarddict['data_date'] = getNow('%Y-%m-%d %H:%M:%S') logs('compute', 'CollaOptions', 'getDataFromMongo', forwarddict, infoFalg=True) self.forwarddict.append(forwarddict) #self.forwarddict = forwarddict self.updateData()
def getDataFromMongo(self): """ from mongo get the currency_pairs and bank_rate #卖出币种如果是人民币(CNY/CNH),那么买入币种是本金,否则就是卖出币种 """ ## currency_pairs ##--------------------获取汇率对的实时汇率 currency_pairs = list(set(map(lambda x: x['currency_pair'], self.data))) Time = self.Now.split()[0] #currency_dict = getcurrentrate(currency_pairs) currency_dict = gethistoryrate(currency_pairs, Time) ##--------------------获取汇率对的历史汇率 self.forwarddict = [] for lst in self.data: ## forwarddict = {} sell_currency = lst['currency_pair'][:3] buy_currency = lst['currency_pair'][3:] currency_pair = lst['currency_pair'] #ratetype = getRate((lst['delivery_date'] -lst['trade_date']).days) ratetype = '12月' #SellRate,BuyRate = getcurrentbankrate(sell_currency,buy_currency,ratetype)##获取银行拆借利率 SellRate, BuyRate = gethistorybankrate(sell_currency, buy_currency, ratetype, Time) ##获取银行历史拆借利率 LockedRate = float(lst['rate']) ##锁定汇率 currentRate = currency_dict.get(currency_pair) ##即期实时汇率 if currentRate is None: print "{} not fund!\n".format(currency_pair) continue deliverydate = dateTostr(lst['delivery_date']) ##交割日期 #print 'forwards',lst['id'],currency_pair,dateTostr(lst['trade_date']),deliverydate, temp = self.cumputeLost(SellRate, BuyRate, deliverydate, LockedRate, currentRate) #print temp ## 计算本金损益 #if forwarddict[lst['id']] is not None: #forwarddict[lst['id']] = chooselocalmoney(lst,forwarddict[lst['id']]) """ 'date','com_code','der_id','cap_currency','cap_amount','gal','exrate','data_date': 日期,公司代码,衍生品编号,本金币种,本金金额,汇兑损益,当天的本金/人民币汇率,数据生成日期 """ if temp is not None: forwarddict['gal'], forwarddict['cap_amount'], forwarddict[ 'cap_currency'] = chooselocalmoney(lst, temp) forwarddict['date'] = Time forwarddict['com_code'] = lst['consign_entity'] forwarddict['der_id'] = lst['trade_type'] + '_' + str(lst['id']) currencypair = forwarddict['cap_currency'] + 'CNY' forwarddict['exrate'] = gethistoryrate( [currencypair], Time)[currencypair] if currencypair != 'CNYCNY' else 1.0 forwarddict['data_date'] = getNow('%Y-%m-%d %H:%M:%S') logs('compute', 'forwards', 'getDataFromMongo', forwarddict, infoFalg=True) #forwarddict[lst['consign_entity']] self.forwarddict.append(forwarddict) #self.forwarddict = forwarddict self.updateData()
def getdataforsimulation(sendData): """ 通过从接口获取数据,返回待模拟的数据 """ ##modelnames = ['market','type','lockRate','sell','tradeDate','deliverDate','currencyPair','sellCurrency'] if sendData['data'] is None: return sendData else: data = sendData['data'] global ERROR ERROR = '' #data['code'] = data['moneyCurrency'] #data['sellCurrency'] = data['moneyCurrency'] ##买入货币币种 data['buyCurrency'] = map( lambda x: x[1][3:] if x[0] == x[1][:3] else x[1][:3], data[['sellCurrency', 'currencyPair']].values) ##卖出货币金额 data['buyMoney'] = map( lambda x: (x[0] * x[3]) if x[1] == x[2][:3] else (x[0] / 1.0 / x[3]), data[['sellMoney', 'sellCurrency', 'currencyPair', 'lockRate']].values) ##本金币种 结汇2:卖出币种,购汇1:买入币种,互换3:非美元币种 data['moneyCurrency'] = map( lambda x: x['buyCurrency'] if x['type'] == '1' ##购汇 else (x['sellCurrency'] if x['type'] == '2' ##结汇 else ##互换 (x['buyCurrency'] if x['sellCurrency'] == 'USD' else x['sellCurrency'])), data[['buyCurrency', 'sellCurrency', 'type']].to_dict('records')) ##本金 data['money'] = map( lambda x: x['buyMoney'] if x['type'] == '1' ##购汇 else (x['sellMoney'] if x['type'] == '2' ##结汇 else ##互换 (x['buyMoney'] if x['sellCurrency'] == 'USD' else x['sellMoney'])), data[[ 'buyCurrency', 'sellCurrency', 'type', 'sellMoney', 'buyMoney' ]].to_dict('records')) ##转换为美元金额 data['USDMoney'] = data['moneyCurrency'].map(lambda x: getSpot(x)) data['USDMoney'] = data['USDMoney'] * data['money'] ##汇率对之间的拆借利率 data['sellRate'] = data['currencyPair'].map( lambda x: getbanrate(x[:3])) data['buyRate'] = data['currencyPair'].map(lambda x: getbanrate(x[3:])) if data['USDMoney'].isnull().sum() > 0: ERROR += "'moneyCurrency' type is error!\n" sendData.update({'errMsg': ERROR, 'errCode': 5, 'data': None}) return sendData ## 拆借利率差 data['r'] = data['buyRate'] - data['sellRate'] ##美元对人民币汇率 data['CNY'] = data['market'].map(lambda x: getCNHCNY(x)) ##人民币金额 data['CNYMoney'] = data['USDMoney'] * data['CNY'] Now = getNow('%Y-%m-%d') ## 未来每笔产品的人民币,当天该笔交易未开始或者已经结束,其金额为0,后面算损益也为0 datarange = getdatarange(data) datarange = datarange[datarange['Time'] >= Now] datarange.index = datarange['Time'] datarange = datarange.drop('Time', axis=1) Currency = map(lambda x: x.split('_')[0], datarange.columns) index = map(lambda x: int(x.split('_')[1]), datarange.columns) ##获取模拟所需的实时数据及汇率的历史数据 sendData = getsimulationdata(Currency) Rate = sendData['data']['Rate'] ##历时收益率 S = sendData['data']['S'] ##即期价格 days = len(datarange) ##最后一笔交割日期截止当天剩余时间 lockRate = data['lockRate'].values[index] ##剩余交割期 T = np.array(map(lambda x: [x], range(1, days + 1))[::-1]) r = data['r'].values[index] ##拆借利率差 ##损益方向 lostFalg = map( lambda x: getlocalflag(x['type'], x['sellCurrency'], x[ 'currencyPair']), data[['type', 'sellCurrency', 'currencyPair']].to_dict('records')) sendData.update({ 'data': { 'S': S, 'Rate': Rate, 'days': days, 'T': T, 'lockRate': lockRate, ##锁定汇率 'lostFalg': lostFalg, 'datarange': datarange.values, 'r': r, ##拆借利率 'type': data['type'], ##交易类型:结汇,购汇、互换 'data': data } }) return sendData
def getDataFromMongo(self): """ from mongo get the currency_pairs and bank_rate """ ## currency_pairs currency_pairs = list(set(map(lambda x: x['currency_pair'], self.data))) Time = self.Now.split()[0] #currency_dict = getcurrentrate(currency_pairs) currency_dict = gethistoryrate(currency_pairs, Time) ##--------------------获取汇率对的历史汇率 ##bank_rate self.forwarddict = [] for lst in self.data: forwarddict = {} sell_currency = lst['currency_pair'][:3] buy_currency = lst['currency_pair'][3:] currency_pair = lst['currency_pair'] #ratetype = getRate((lst['delivery_date'] -lst['trade_date']).days) ratetype = '12月' #SellRate,BuyRate = getcurrentbankrate(sell_currency,buy_currency,ratetype) SellRate, BuyRate = gethistorybankrate(sell_currency, buy_currency, ratetype, Time) ##获取银行历史拆借利率 #sell_amount = float64(lst['sell_amount']) #buy_amount = float64(lst['buy_amount']) Setdate = dateTostr(lst['determined_date']) if Time < Setdate: SetRate = None else: SetRate = RateExchange(currency_pair).getdayMax( Setdate) ##厘定日汇率 #SetRate = RateExchange(currency_pair).getdayMax(Setdate)##厘定日汇率 kncockRate = float64(lst['knockout_exrate']) ##敲出汇率 LockedRate = float(lst['rate']) currentRate = currency_dict[currency_pair] deliverydate = dateTostr(lst['delivery_date']) #print 'knockoptions',lst['id'],currency_pair,dateTostr(lst['trade_date']),deliverydate, type = lst['type'] temp = self.cumputeLost(Setdate, SetRate, deliverydate, currentRate, LockedRate, kncockRate, SellRate, BuyRate, self.delta, type) #print temp #print '\n' ## 计算本金损益 #if forwarddict[lst['id']] is not None: #forwarddict[lst['id']] = chooselocalmoney(lst,forwarddict[lst['id']]) """ 'date','com_code','der_id','cap_currency','cap_amount','gal','exrate','data_date': 日期,公司代码,衍生品编号,本金币种,本金金额,汇兑损益,当天的本金/人民币汇率,数据生成日期 """ if temp is not None: forwarddict['gal'], forwarddict['cap_amount'], forwarddict[ 'cap_currency'] = chooselocalmoney(lst, temp) forwarddict['date'] = Time forwarddict['com_code'] = lst['consign_entity'] forwarddict['der_id'] = lst['trade_type'] + '_' + str(lst['id']) currencypair = forwarddict['cap_currency'] + 'CNY' forwarddict['exrate'] = gethistoryrate( [currencypair], Time)[currencypair] if currencypair != 'CNYCNY' else 1.0 forwarddict['data_date'] = getNow('%Y-%m-%d %H:%M:%S') logs('compute', 'knockoptions', 'getDataFromMongo', forwarddict, infoFalg=True) self.forwarddict.append(forwarddict) #self.forwarddict = forwarddict self.updateData()
def getDataFromMongo(self): """ from mongo get the currency_pairs and bank_rate """ ## currency_pairs currency_pairs = list(set(map(lambda x:x['currency_pair'],self.data))) Time = self.Now.split()[0] #currency_dict = getcurrentrate(currency_pairs) currency_dict = gethistoryrate(currency_pairs,Time) ##bank_rate self.forwarddict = [] for lst in self.data: forwarddict= {} ##交易本币与外币 ##支付固定利率 #print '计算订单{}\n'.format(lst) payFixRate = None if lst['pay_fix_rate'] is None else float64(lst['pay_fix_rate']) ##支付固定利率 chargeFixRate = None if lst['charge_fix_rate'] is None else float64(lst['charge_fix_rate'])##收取浮动利息固定部分 value_date = dateTostr(lst['value_date']) delivery_date = dateTostr(lst['delivery_date']) trade_date = dateTostr(lst['trade_date']) #print lst['id'] if lst['interest_pay_way'] == '3': ##到期一次性支付 br = BankRate(lst['buy_currency'],interestway(lst['interest_pay_way'],lst['charge_float_libor'])) if delivery_date> Time: date = {dateTostr(lst['delivery_date']):br.getday(Time)} else: date = {dateTostr(lst['delivery_date']):br.getday(delivery_date)} elif lst['interest_pay_way']== '0' or lst['trade_type']=='4': ##提前支付 br = BankRate(lst['buy_currency'],interestway(lst['interest_pay_way'],lst['charge_float_libor'])) if (lst['trade_date'] - lst['value_date']).days>180: date = {dateTostr(lst['delivery_date']):br.getday(trade_date)}## value_date trade_date else: date = {dateTostr(lst['delivery_date']):br.getday(value_date)}## value_date trade_date else: #print lst if (lst['trade_date'] - lst['value_date']).days>180: date = getbankrateoneday(lst['buy_currency'],trade_date,delivery_date,lst['interest_pay_way'],lst['charge_float_libor'],Time) else: date = getbankrateoneday(lst['buy_currency'],value_date,delivery_date,lst['interest_pay_way'],lst['charge_float_libor'],Time) #payFixRateDict = {} if chargeFixRate is None: chargeFixRate=0.0 for t in date: date[t] = date[t]/100.0+chargeFixRate##货币浮动利率及支付利息时间 Fix = array(sorted(date.items(),key=lambda x:x[0])) FixDate = Fix[:,0] FixRate = Fix[:,1][:] FixRate = FixRate.astype(float64) Rate = (FixDate,payFixRate,FixRate)##利息支付日期,支付卖出货币利息,收取浮动利率利息 currency_pair = lst['currency_pair'] ##货币对之间本币与外币 sellCurrency = currency_pair[:3] buyCurrency = currency_pair[3:] ratetype ='12月' #SellRate,BuyRate = getcurrentbankrate(sellCurrency,buyCurrency,ratetype) SellRate,BuyRate = gethistorybankrate(sellCurrency,buyCurrency,ratetype,Time)##获取银行历史拆借利率 LockedRate = float64(lst['exe_exrate'])##执行汇率 capped_exrate = None if lst['capped_exrate'] is None else float64(lst['capped_exrate']) ##封顶汇率 ##获取厘定日汇率 ##获取厘定日的汇率,如果还未到厘定日,那么汇率返回None Setdate = dateTostr(lst['determined_date'])##厘定日 if Time<Setdate: SetRate = None else: SetRate = RateExchange(currency_pair).getdayMax(Setdate)##厘定日汇率 #SetRate = RateExchange(currency_pair).getdayMax(Setdate)##厘定日汇率 if SetRate ==[]: SetRate = None## 还未到厘定日 currentRate = currency_dict.get(currency_pair) ## 实时汇率 if currentRate is None: print "{} not fund!".format(currency_pair) continue #deliverydate = dateTostr(lst['delivery_date'])## 交割日期 trade_type = lst['trade_type']##交易类型 rateway = lst['interest_pay_way']##利息支付方式 #sell_amount = float64(lst['sell_amount']) #buy_amount = float64(lst['buy_amount']) #2,3,4分别表示:区间式货币掉期(利率进行互换+固定补贴)、货币掉期(利率互换)、封顶式期权(固定补贴) #print 'SwapOptions', lst['id'],currency_pair,rateway,'区间式货币掉期' if trade_type=='2' else ('货币掉期' if trade_type=='3' else '封顶式期权'),value_date,delivery_date, temp = self.cumputeLost(Setdate,SetRate,value_date,delivery_date,currentRate,SellRate,BuyRate,LockedRate,rateway,self.delta,capped_exrate,trade_type,Rate) #if sell_currency+buy_currency !=currency_pair: # forwarddict[lst['id']] = forwarddict[lst['id']]/currentRate #if forwarddict[lst['id']] is not None: #forwarddict[lst['id']] = chooselocalmoney(lst,forwarddict[lst['id']]) """ 'date','com_code','der_id','cap_currency','cap_amount','gal','exrate','data_date': 日期,公司代码,衍生品编号,本金币种,本金金额,汇兑损益,当天的本金/人民币汇率,数据生成日期 """ if temp is not None: forwarddict['gal'],forwarddict['cap_amount'],forwarddict['cap_currency'] = chooselocalmoney(lst,temp) forwarddict['date'] = Time forwarddict['com_code'] = lst['consign_entity'] forwarddict['der_id'] = lst['trade_type']+'_'+str(lst['id']) currencypair = forwarddict['cap_currency']+'CNY' forwarddict['exrate'] = gethistoryrate([currencypair],Time)[currencypair] if currencypair!='CNYCNY' else 1.0 forwarddict['data_date'] = getNow('%Y-%m-%d %H:%M:%S') logs('compute','swaoption','getDataFromMongo',forwarddict,infoFalg=True) #if lst['id']==1170: #print Setdate,SetRate,value_date,delivery_date,currentRate,SellRate,BuyRate,LockedRate,rateway,self.delta,capped_exrate,trade_type,Rate,forwarddict['gal'] self.forwarddict.append(forwarddict) #print forwarddict #self.forwarddict = forwarddict self.updateData()