def process_execution_tasks(self): now_utc = datetime.now(pytz.timezone('UTC')).replace(tzinfo=None).replace(microsecond=0) for rec in self: try: if rec.got('Execution 3'): continue elif rec.ngot('Execution 1'): period = businessDuration(now_utc, t(rec.date_end_ex), unit='hour') exceeded = businessDuration(t(rec.date_end_ex), now_utc, unit='hour') if period < 25: rec.send_notification(rec.user_executor_id, u"Разрешите Вам напомнить, что %s дата выполнения задания заканчивается." % str(rec.date_end_ex), u"Выполнение") rec.history_record('Execution 1') elif (period < 1 or math.isnan(period)) and exceeded > 23: rec.send_notification(rec.user_executor_id, u"Задание просрочено, срок выполнения истек. Прошу перевести в утверждение.", u"Выполнение") rec.history_record('Execution 1') elif rec.ngot('Execution 2'): period = businessDuration(t(rec.date_end_ex), now_utc, unit='hour') if period > 24: msg = u"Задание просрочено, срок выполнения истек. Прошу перевести в утверждение, если задание выполнено или указать срок выполнения со вторым переносом и причину переноса. Третий срок переноса недопустим" rec.send_notification(rec.user_executor_id, msg, u"Выполнение просрочено") rec.history_record('Execution 2') elif rec.got('Execution 2') and rec.ngot('Execution 3'): period = businessDuration(t(rec.date_end_ex), now_utc, unit='hour') if period > 48: # msg = u"Сроки выполнения нарушены. Прошу перепланировать" msg = u"Прошу перепланировать статус и сроки в течение 3 дней. При отсутствии изменений и ответа задание перейдет в завершено как невыполненное через 10 дней." rec.send_notification(rec.user_id, msg, u"Выполнение просрочено ") rec.history_record('Execution 3') rec.history_record('Corrections 1') rec.set_to_corrections() time.sleep(1) except Exception as e: log.error(rec) log.error(e)
def process_approvement_tasks(self): now_utc = datetime.now(pytz.timezone('UTC')).replace(tzinfo=None).replace(microsecond=0) for rec in self: try: if rec.got('Approvement 3'): continue elif rec.ngot('Approvement 1'): rec.send_notification(rec.user_approver_id, u"Прошу подтвердить в срок до %s" % str(rec.date_end_ap) , u"Подтверждение") rec.history_record('Approvement 1') elif rec.ngot('Approvement 2'): period = businessDuration(t(rec.date_end_ap), now_utc, unit='hour') if period > 24: msg = u"""Задание просрочено, срок подтверждения истек. Прошу перевести в подтверждено, если результат задания принято, или указать срок подтверждения со вторым переносом и причину переноса. Третий срок переноса недопустим.""" rec.send_notification(rec.user_approver_id, msg, u"Подтверждение просрочено") rec.history_record('Approvement 2') elif rec.ngot('Approvement 3'): period = businessDuration(t(rec.date_end_ap), now_utc, unit='hour') if period > 48: # msg = u"Сроки подтверждения нарушены. Прошу перепланировать." msg = u"Прошу перепланировать статус и сроки в течение 3 дней. При отсутствии изменений и ответа задание перейдет в завершено как невыполненное через 10 дней." rec.send_notification(rec.user_id, msg, u"Подтверждение просрочено") rec.history_record('Approvement 3') rec.history_record('Corrections 1') rec.set_to_corrections() time.sleep(1) except Exception as e: log.error(rec) log.error(e)
def working_duration(start_unix, end_unix): ''' Determine working duration (working hours only) Keyword arguments: start_unix: start time (epoch seconds) end_unix: end time (epoch seconds) ''' open_time = datetime.time(6, 0, 0) close_time = datetime.time(18, 0, 0) holidaylist = pyholidays.US() startstring = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start_unix)) endstring = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(end_unix)) startdate = pd.to_datetime(startstring) enddate = pd.to_datetime(endstring) work_duration = businessDuration(startdate, enddate, open_time, close_time, holidaylist=holidaylist, unit='hour') * 3600 try: work_duration = int(work_duration) except ValueError as err: print(str(err) + ' for ' + startstring + ', ' + endstring) work_duration = end_unix - start_unix return work_duration
def get_note_bushours_period(self, note): # now and dates in notifications_history are UTC+5 now_ekt = datetime.now(pytz.timezone('Asia/Yekaterinburg')).replace(tzinfo=None) for l in self.notifications_history.splitlines(): if l.split('\t')[1] == note: notification_moment = datetime.strptime(l.split('\t')[0][:19], '%Y-%m-%d %H:%M:%S') res = businessDuration(notification_moment, now_ekt, unit='hour') return res return 0
def businesshours(start, end): US_holiday_list = pyholidays.US(state='NY') biz_open_time = time(8, 0, 0) biz_close_time = time(17, 0, 0) unit_hour = 'hour' return businessDuration(startdate=start, enddate=end, starttime=biz_open_time, endtime=biz_close_time, holidaylist=US_holiday_list, unit=unit_hour)
def seconds_between(self, end_date, start_date): # indicate time of working hours biz_open_time = time(8, 0, 0) biz_close_time = time(17, 0, 0) holiday_list = pyholidays.CZ() unit = 'sec' try: difference = businessDuration(startdate=start_date, enddate=end_date, starttime=biz_open_time, endtime=biz_close_time, holidaylist=holiday_list, unit=unit) return(difference) except Exception as e: print(e) return('Error in Date')
datetime.date(2020, 5, 5): '어린이날', datetime.date(2020, 6, 6): '현충일', datetime.date(2020, 8, 15): '광복절', datetime.date(2020, 9, 30): '추석', datetime.date(2020, 10, 1): '추석', datetime.date(2020, 10, 2): '추석', datetime.date(2020, 10, 3): '개천절', datetime.date(2020, 10, 9): '한글날', datetime.date(2020, 12, 25): '크리스마스', datetime.date(2021, 1, 1): '새해', datetime.date(2021, 2, 11): '설날', datetime.date(2021, 2, 12): '설날', datetime.date(2021, 2, 13): '설날', datetime.date(2021, 3, 1): '삼일절', datetime.date(2021, 5, 5): '어린이날', datetime.date(2021, 5, 19): '부처님오신날', datetime.date(2021, 6, 6): '현충일', datetime.date(2021, 8, 15): '광복절', datetime.date(2021, 9, 20): '추석', datetime.date(2021, 9, 21): '추석', datetime.date(2021, 9, 22): '추석', datetime.date(2021, 10, 3): '개천절', datetime.date(2021, 10, 9): '한글날', datetime.date(2021, 12, 25): '크리스마스'} unit='day' #By default Saturday and Sunday are excluded print(sd,"부터 ", ed,"까지 주말 및 공휴일 제외 평일 날짜수:", int(businessDuration(startdate,enddate,holidaylist=korean_holidaylist_2020_2021,unit=unit))+1,"일") print((int(businessDuration(startdate,enddate,holidaylist=korean_holidaylist_2020_2021,unit=unit))+1)/5,"주")
def get_issue_stats(jql): issues = get_issues(jql) counter = 0 for issue in issues: counter += 1 transitions = list(get_transitions(issue)) transitions = sorted(transitions, key=lambda tr: tr.get('at')) started = None finished = None back_from_finished = False for transition in transitions: if transition.get('to') == 'In Progress': if started == None: started = transition.get('at') elif transition.get('to') == 'To Do' or transition.get( 'to') == 'New': # or transition.get('to') == 'Input Needed': if finished == None and started != None: started = None elif finished != None: back_from_finished = True elif transition.get('to') == 'QA': back_from_finished = False if started != None: finished = transition.get('at') elif transition.get('to') == 'Done': back_from_finished = False if finished == None or back_from_finished: finished = transition.get('at') result = { 'issue': issue.get('key'), 'link': "https://beekeeper.atlassian.net/browse/{}".format( issue.get('key')), 'type': issue.get('fields', {}).get('issuetype', {}).get('name'), 'story_points': issue.get('fields', {}).get('customfield_10005'), 'started': started, 'finished': finished if not back_from_finished else None, 'lead_time_hours': None, 'normalized_lead_time': None, 'resolution': (issue.get('fields', {}).get('resolution') or {}).get('name'), 'summary': issue.get('fields', {}).get('summary'), 'accepted_outlier': 'ax-stats-outlier' in issue.get('fields', {}).get('labels', []), 'labels': issue.get('fields', {}).get('labels', []), } #Business open hour biz_open_time = datetime.time(9, 0, 0) #Business close time biz_close_time = datetime.time(18, 0, 0) weekend_list = [5, 6] holidaylist = pyholidays.Switzerland() if started != None and finished != None: result['lead_time_hours'] = businessDuration( startdate=started, enddate=finished, starttime=biz_open_time, endtime=biz_close_time, weekendlist=weekend_list, holidaylist=holidaylist, unit='hour') if result.get('lead_time_hours') != None and result.get( 'story_points') != None and result.get('story_points') > 0: result['normalized_lead_time'] = result.get( 'lead_time_hours') / result.get('story_points') yield result
def process_agreement_tasks(self): # olga = self.env['res.users'].browse(66) martynova = self.env['res.users'].browse(43) now_utc = datetime.now(pytz.timezone('UTC')).replace(tzinfo=None).replace(microsecond=0) for rec in self: try: if rec.is_agreed(): rec.state = 'assigned' rec.send_notification(rec.user_executor_id, "Прошу перейти в выполнение", u"Перейти в выполнение") if rec.ngot('Assigned 1'): rec.history_record('Assigned 1') self.env.cr.commit() continue elif rec.got('Agreement blocked'): # TODO filter it initially continue elif rec.got('Agreement no action'): # TODO filter it initially continue elif rec.got('Agreement expired by supervisor'): # TODO filter it initially continue elif rec.got('Agreement executors supervisor assigned'): if rec.get_note_bushours_period('Agreement executors supervisor assigned') > 24: if rec.user_executor_id and not rec.approved_by_executor: rec.send_notification(martynova, u"Просрочено руководителем", u"Просрочено руководителем") rec.history_record('Agreement expired by supervisor') rec.history_record('Corrections 1') rec.set_to_corrections() elif rec.got('Agreement approver supervisor assigned'): if rec.get_note_bushours_period('Agreement approver supervisor assigned') > 24: if rec.user_approver_id and rec.got_approver and not rec.approved_by_approver: rec.send_notification(martynova, u"Просрочено руководителем", u"Просрочено руководителем") rec.history_record('Agreement expired by supervisor') rec.history_record('Corrections 1') rec.set_to_corrections() elif rec.got('Agreement predicator supervisor assigned'): if rec.get_note_bushours_period('Agreement predicator supervisor assigned') > 24: if rec.user_predicator_id and not rec.approved_by_predicator: rec.send_notification(martynova, u"Просрочено руководителем", u"Просрочено руководителем") rec.history_record('Agreement expired by supervisor') rec.history_record('Corrections 1') rec.set_to_corrections() elif rec.got('Agreement 2'): if rec.get_note_bushours_period('Agreement 2') > 24: if rec.user_executor_id and not rec.approved_by_executor: executor_blockers = rec.get_blocking_users(rec.user_executor_id) if executor_blockers: period = businessDuration(t(executor_blockers.create_date), now_utc, unit='hour') if period > 24 and rec.ngot('Agreement blocked'): msg = u"Вопрошаемый не отвечает. Спрашивал исполнитель: %s. Вопрос задан: %s" % (executor_blockers.set_by_id.name, executor_blockers.user_id.name) msg += u"\nПрошу перепланировать статус и сроки в течение 3 дней. При отсутствии изменений и ответа задание перейдет в завершено как невыполненное через 10 дней." rec.send_notification(rec.user_id, msg, u"Блокировка задания. Нет ответа.") rec.history_record('Agreement blocked') rec.history_record('Corrections 1') rec.set_to_corrections() else: # last_answer = rec.get_last_answered_block(rec.user_executor_id) last_answer = False if last_answer: period = businessDuration(t(last_answer.answer_date), now_utc, unit='hour') if period > 24: if rec.user_executor_id.manager_id: rec.user_executor_id = rec.user_executor_id.manager_id msg = u"""Исполнитель заменен на его руководителя. Иполнитель задал вопрос. На него был дан ответ. Прошло больше одного рабочего дня. Исполнитель не согласовал и не задал новых вопросов.""" rec.send_notification(rec.user_id, msg, u"Автозамена исполнителя") # ОЗП rec.history_record('Agreement executors supervisor assigned') else: msg = u"""Сроки согласования просрочены и у исполнителя нет руководителя. Задание заблокировано. Иполнитель задал вопрос. На него был дан ответ. Прошло больше одного рабочего дня. Исполнитель не согласовал и не задал новых вопросов.""" msg += u"\nПрошу перепланировать статус и сроки в течение 3 дней. При отсутствии изменений и ответа задание перейдет в завершено как невыполненное через 10 дней." rec.send_notification(rec.user_id, msg, "Нет руководителя у исполнителя") # ОЗП rec.history_record('Agreement blocked\texecutor') rec.history_record('Corrections 1') rec.set_to_corrections() else: pass # Последний ответ был < 24 назад. Еще есть время среагировать else: if rec.user_executor_id.manager_id: rec.user_executor_id = rec.user_executor_id.manager_id rec.send_notification(rec.user_id, u"Исполнитель заменен на его руководителя. Нет согласования больше 3х рабочих дней.", u"Автозамена исполнителя") # ОЗП rec.history_record('Agreement executors supervisor assigned') else: msg = u"""Сроки согласования просрочены и у исполнителя нет руководителя. Задание заблокировано.""" msg += u"\nПрошу перепланировать статус и сроки в течение 3 дней. При отсутствии изменений и ответа задание перейдет в завершено как невыполненное через 10 дней." rec.send_notification(rec.user_id, msg, u"Нет руководителя у исполнителя") # ОЗП rec.history_record('Agreement blocked\texecutor') rec.history_record('Corrections 1') rec.set_to_corrections() if rec.user_approver_id and rec.got_approver and not rec.approved_by_approver: if rec.user_approver_id.manager_id: rec.user_approver_id = rec.user_approver_id.manager_id rec.send_notification(rec.user_id, u"Подтверждающий заменен на его руководителя. Нет согласования больше 3х рабочих дней.", u"Автозамена подтверждающего") # ОЗП rec.history_record('Agreement approver supervisor assigned') else: msg = u"""Сроки согласования просрочены и у подтверждающего нет руководителя. Задание заблокировано.""" msg += u"\nПрошу перепланировать статус и сроки в течение 3 дней. При отсутствии изменений и ответа задание перейдет в завершено как невыполненное через 10 дней." rec.send_notification(rec.user_id, msg, u"Нет руководителя у подтверждающего") # ОЗП rec.history_record('Agreement blocked\tapprover') rec.history_record('Corrections 1') rec.set_to_corrections() if rec.user_predicator_id and not rec.approved_by_predicator: if rec.user_predicator_id.manager_id: rec.user_predicator_id = rec.user_predicator_id.manager_id rec.send_notification(rec.user_id, u"Утверждающий заменен на его руководителя. Нет согласования больше 3х рабочих дней.", u"Автозамена утверждающего") # ОЗП rec.history_record('Agreement predicator supervisor assigned') else: msg = u"""Сроки согласования просрочены и у утверждающего нет руководителя. Задание заблокировано.""" msg += u"\nПрошу перепланировать статус и сроки в течение 3 дней. При отсутствии изменений и ответа задание перейдет в завершено как невыполненное через 10 дней." rec.send_notification(rec.user_id, msg, u"Нет руководителя у утверждающего") # ОЗП rec.history_record('Agreement blocked\tpredicator') rec.history_record('Corrections 1') rec.set_to_corrections() elif rec.ngot('Agreement 1'): msg_text = u"Прошу согласовать в течение 24 часов." subject = u"Согласование" rec.history_record('Agreement 1') if rec.user_executor_id and not rec.approved_by_executor: rec.send_notification(rec.user_executor_id, msg_text, subject) if rec.user_approver_id and rec.got_approver and not rec.approved_by_approver: rec.send_notification(rec.user_approver_id, msg_text, subject) if rec.user_predicator_id and not rec.approved_by_predicator: rec.send_notification(rec.user_predicator_id, msg_text, subject) elif rec.got('Agreement 1'): if rec.get_note_bushours_period('Agreement 1') > 24: if rec.user_executor_id and not rec.approved_by_executor: executor_blockers = rec.get_blocking_users(rec.user_executor_id) if executor_blockers: period = businessDuration(t(executor_blockers.create_date), now_utc, unit='hour') if period > 24 and rec.ngot('Agreement blocked'): msg = u"Вопрошаемый не отвечает. Спрашивал исполнитель: %s. Вопрос задан: %s" % (executor_blockers.set_by_id.name, executor_blockers.user_id.name) rec.send_notification(rec.user_id, msg, u"Блокировка задания. Нет ответа.") rec.history_record('Agreement blocked') rec.history_record('Corrections 1') rec.set_to_corrections() else: pass # Вопрос задан < 24 часов назад. Еще есть время ответить else: last_answer = False # last_answer = rec.get_last_answered_block(rec.user_executor_id) if last_answer: period = businessDuration(t(last_answer.answer_date), now_utc, unit='hour') if period > 24: msg_text = u"""Задание не согласовывается, прошу сменить исполнителя. Иполнитель задал вопрос. На него был дан ответ. Прошло больше одного рабочего дня. Исполнитель не согласовал и не задал новых вопросов.""" subject = u"Согласование просрочено" rec.send_notification(rec.user_executor_id, msg_text, subject) rec.send_notification(rec.user_id, msg_text, subject) # ОЗП rec.history_record('Agreement 2\texecutor') else: pass # Последний ответ был < 24 назад. Еще есть время среагировать else: msg_text = u"Задание не согласовывается. Исполнитель не проявляет активности больше 1 рабочего дня. Просьба сменить исполнителя." subject = u"Согласование просрочено. Прошло 48 часов." rec.send_notification(rec.user_executor_id, msg_text, subject) rec.send_notification(rec.user_id, msg_text, subject) # ОЗП rec.history_record('Agreement 2\texecutor') if rec.user_approver_id and rec.got_approver and not rec.approved_by_approver: msg_text = u"Задание не согласовывается. Подтверждающий не проявляет активности больше 1 рабочего дня." subject = u"Согласование просрочено. Прошло 48 часов." rec.send_notification(rec.user_approver_id, msg_text, subject) rec.send_notification(rec.user_id, msg_text, subject) # ОЗП rec.history_record('Agreement 2\tapprover') if rec.user_predicator_id and not rec.approved_by_predicator: msg_text = u"Задание не согласовывается. Утверждающий не проявляет активности больше 1 рабочего дня." subject = u"Согласование просрочено. Прошло 48 часов." rec.send_notification(rec.user_predicator_id, msg_text, subject) rec.send_notification(rec.user_id, msg_text, subject) # ОЗП rec.history_record('Agreement 2\tpredicator') self.env.cr.commit() except Exception as e: log.error(rec) log.error(e)
def write(self, vals): if len(self) == 1: if vals.get('state') and vals['state'] != self.state: current_user = self.env['res.users'].browse(self.env.uid) # moment = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S') moment = datetime.datetime.now(pytz.timezone(self.env.context.get('tz') or 'UTC')).strftime('%Y-%m-%d %H:%M:%S') vals['state_history'] = (self.state_history or '') + "%s\t%s\t%s\t%s\n" % (moment, vals['state'], current_user.name, self.env.uid) if vals['state'] == 'stating': now_utc = datetime.datetime.now(pytz.timezone('UTC')).replace(tzinfo=None).replace(microsecond=0) if self.date_end_ex: period = businessDuration(t(self.date_end_ex), now_utc, unit='day') if math.isnan(period): vals['mark_state'] = 7 elif period == 0: vals['mark_state'] = 6 elif period == 1: vals['mark_state'] = 5 elif period == 2: vals['mark_state'] = 4 elif period == 3: vals['mark_state'] = 3 elif period == 4 or period == 5: vals['mark_state'] = 2 elif period > 5: vals['mark_state'] = 1 if states_rang[vals['state']] < states_rang[self.state]: new_hist = '' if self.notifications_history and len(self.notifications_history) > 1: for l in self.notifications_history.splitlines(): new_hist += '-\t' + l + '\n' vals['notifications_history'] = new_hist now_ekt = datetime.datetime.now(pytz.timezone('Asia/Yekaterinburg')).replace(tzinfo=None).replace(microsecond=0) vals['notifications_history'] += u"%s\tСтатус изменен на более ранний\t%s->%s\n" % (str(now_ekt), self.state, vals['state']) if vals['state'] not in ['plan', 'correction', 'finished']: if (self.job_id and self.job_id.state == 'plan') or (self.job_id.finished_manually and self.job_id.state == 'finished'): self.job_id.state = 'defined' if (self.job_aim_id and self.job_aim_id.state == 'plan') or (self.job_aim_id.finished_manually and self.job_aim_id.state == 'finished'): self.job_aim_id.state = 'defined' if not vals.get('message_follower_ids'): # participants = self.user_executor_id + self.user_predicator_id + self.user_approver_id + self.user_id participants = [vals.get('user_executor_id'), vals.get('user_predicator_id'), vals.get('user_approver_id'), vals.get('user_id')] self.sudo().message_subscribe_users(user_ids=participants) if vals.get('date_end_ex'): if self.state not in ['plan', 'correction', 'finished']: # olga = self.env['res.users'].browse(66) # timur = self.env['res.users'].browse(91) if self.date_end_ex_change_qty is False: self.date_end_ex_change_qty = 0 if self.date_end_ex_change_qty > 1 and self.env.uid not in [66, 91]: raise ValidationError('Срок уже был изменен 2 раза. Третий раз изменять срок исполнения запрещено.') else: vals['date_end_ex_change_qty'] = self.date_end_ex_change_qty + 1 if vals.get('state') and vals.get('state') == 'plan': vals['date_end_ex_change_qty'] = 0 # Reset res = super(Task, self).write(vals=vals) # self.message_auto_subscribe(updated_fields=vals.keys()) if len(self) == 1: if self.state == 'finished': if self.job_id and self.job_id.state != 'finished': if all([r.state == 'finished' for r in self.job_id.task_ids]): self.job_id.state = 'finished' # if self.job_aim_id and self.job_aim_id.state != 'finished': # if all([r.state == 'finished' for r in self.job_aim_id.task_ids]): # self.job_aim_id.state = 'finished' if self.aim_id and self.aim_id.state != 'finished': if all([r.state == 'finished' for r in self.aim_id.task_ids]): self.aim_id.state = 'finished' return res
def TableUpdate1(data_timestamp, data, children): #### ---- Populating table if (data_timestamp != None) & (children != None): if len(data) > 0: data = pd.DataFrame(data) data['Amount'] = data['Amount'].astype(float) data['Price'] = data['Price'].astype(float) data['Strike'] = data['Strike'].astype(float) data['ImpVol'] = data['ImpVol'].astype(float) data["Day"] = pd.to_datetime(data["Day"]) data["Maturity"] = pd.to_datetime(data["Maturity"]) data["Financial"] = data['Amount'] * data['Price'] data["Financial"] = data["Financial"].round(2) spot = pd.DataFrame(json.loads(json.loads(str(children))['spot'])) spot["TRADE_DATE"] = pd.to_datetime(spot["TRADE_DATE"]) days = (data.apply(lambda row: businessDuration( startdate=row['Day'], enddate=row['Maturity'], unit='day'), axis=1)).values # ImpyVola=[round(Func.ImpliedVola(spot[spot["Instrument"]!="BRSELICD=CBBR"].TRDPRC_1.values[0].astype(float), # data["Strike"].values[j].astype(float), # spot[spot["Instrument"]=="BRSELICD=CBBR"].TRDPRC_1.values[0].astype(float)/100, # .70, # data["Price"].values[j].astype(float), # days[j], # data["type"],a=-12.0, b=12.0, xtol=1e-8)*100,2) for j in range(len(data))] ImpyVola = data['ImpVol'].values GREEKS = Func.OpitionsPrice( spot[spot["Instrument"] != "BRSELICD=CBBR"].TRDPRC_1.values[0]. astype(float), data["Strike"].values.astype(float), spot[spot["Instrument"] == "BRSELICD=CBBR"].TRDPRC_1.values[0].astype(float) / 100, np.array(ImpyVola) / 100, days) data[['Valor', 'Delta', 'Gamma', 'Vega', 'Theta', 'Rho', 'Etas']] = pd.DataFrame([[0 for i in range(7)]], columns=[ 'Valor', 'Delta', 'Gamma', 'Vega', 'Theta', 'Rho', 'Etas' ], index=data.index) callGreek = GREEKS[list(GREEKS.columns[GREEKS.columns.str.contains( 'C', regex=True)])][data.type.str.contains('C', regex=True).values] putGreek = GREEKS[list(GREEKS.columns[GREEKS.columns.str.contains( 'P', regex=True)])][data.type.str.contains('P', regex=True).values] callGreek.columns = [ 'Valor', 'Delta', 'Gamma', 'Vega', 'Theta', 'Rho', 'Etas' ] putGreek.columns = [ 'Valor', 'Delta', 'Gamma', 'Vega', 'Theta', 'Rho', 'Etas' ] data.loc[ list(data.type.str.contains('C', regex=True).values), ['Valor', 'Delta', 'Gamma', 'Vega', 'Theta', 'Rho', 'Etas' ]] = round(callGreek, 3).values data.loc[ list(data.type.str.contains('P', regex=True).values), ['Valor', 'Delta', 'Gamma', 'Vega', 'Theta', 'Rho', 'Etas' ]] = round(putGreek, 3).values data["ImpVol"] = ImpyVola data["Delta"] = data.Delta.values data["Gamma"] = data.Gamma.values data["Vega"] = data.Vega.values data["Theta"] = data.Theta.values data["Rho"] = data.Rho.values return (data[[ 'Financial', 'Delta', 'Gamma', 'Vega', 'Theta', 'Rho' ]].to_dict('records')) else: return [] else: return []
def CalcNetChart(row_ids, data, children, value): if (row_ids != None) & (data != None): if (len(row_ids) > 0) & (len(data) > 0): ek.set_app_key(value) ek.set_timeout(60 * 5) data = pd.DataFrame(data) data = data[data.index.isin(row_ids)] data['Amount'] = data['Amount'].astype(float) data['Price'] = data['Price'].astype(float) data['Strike'] = data['Strike'].astype(float) data["Day"] = pd.to_datetime(data["Day"]) data["Maturity"] = pd.to_datetime(data["Maturity"]) data["Financial"] = data['Amount'] * data['Price'] data["Financial"] = data["Financial"].round(2) spot = pd.DataFrame(json.loads(json.loads(str(children))['spot'])) spot['TRDPRC_1'] = spot['TRDPRC_1'].astype(float) spot["TRADE_DATE"] = pd.to_datetime(spot["TRADE_DATE"]) ssp = spot[ spot["Instrument"] != "BRSELICD=CBBR"].TRDPRC_1.values[0] days = (data.apply(lambda row: businessDuration( startdate=row['Day'], enddate=row['Maturity'], unit='day'), axis=1)).values days = list(set(days)) vola, err = ek.get_data([ spot[ spot["Instrument"] != "BRSELICD=CBBR"].Instrument.values[0] ], [ 'TR.Volatility5D', 'TR.Volatility10D', "TR.Volatility20D", "TR.Volatility30D", "TR.Volatility60D", "TR.Volatility90D" ]) volaV = (sum(( vola.T[0].values[1:] * (abs(np.array([5, 10, 20, 30, 60, 90]) - 15) + 1) / (sum(abs(np.array([5, 10, 20, 30, 60, 90]) - 15) + 1))))) / 100 vola.columns = ['Instrument', 5, 10, 20, 30, 60, 90] vola[[5, 10, 20, 30, 60, 90]] = vola[[5, 10, 20, 30, 60, 90]] / 100 days = list(np.unique(days)) dists = [] vollist = [] for d in days: y_interp = scipy.interpolate.interp1d( vola.columns[1:].astype(float), vola.T[0].values[1:].astype(float)) volaV = y_interp(d) Distrib = 1 - np.random.normal(0, (volaV / (252**0.5) * (d**0.5)), size=5000) Distrib = Distrib * ssp vollist.append(volaV) dists.append(Distrib) Price = dists[pd.DataFrame(dists).max(1).argmax()] Price.sort() net = [] for k in range(len(data)): if data['Amount'].iloc[k] >= 0: if "C" in data['type'].iloc[k]: Rt = -data['Strike'].iloc[k] - data['Price'].iloc[ k] + Price Rt[Rt <= -data['Price'].iloc[k]] = -data['Price'].iloc[k] Rt = Rt * abs(data['Amount'].iloc[k]) net.append(list(Rt)) else: Rt = data['Strike'].iloc[k] - data['Price'].iloc[ k] - Price Rt[Rt <= -data['Price'].iloc[k]] = -data['Price'].iloc[k] Rt = Rt * abs(data['Amount'].iloc[k]) net.append(list(Rt)) else: if "C" in data['type'].iloc[k]: Rt = data['Strike'].iloc[k] + data['Price'].iloc[ k] - Price Rt[Rt >= data['Price'].iloc[k]] = data['Price'].iloc[k] Rt = Rt * abs(data['Amount'].iloc[k]) net.append(list(Rt)) else: Rt = -data['Strike'].iloc[k] + data['Price'].iloc[ k] + Price Rt[Rt >= data['Price'].iloc[k]] = data['Price'].iloc[k] Rt = Rt * abs(data['Amount'].iloc[k]) net.append(list(Rt)) pay = pd.DataFrame(net) pay.columns = Price pays = pay # print(pays.values) pay = pay.sum() tempTT = [] for j in range(len(set(days))): tempT = [] for s in range(len(data["Strike"])): temp = Func.OpitionsPrice( Price, data["Strike"].values.astype(float)[s], spot[spot["Instrument"] == "BRSELICD=CBBR"].TRDPRC_1. values[0].astype(float) / 100, np.array(data['ImpVol'].values[j]) / 100, days[j]) if "C" in data["type"].values[s]: temp = list( (temp.ValorC.values - data['Price'].values[s]) * data['Amount'].values[s]) else: temp = list( (temp.ValorP.values - data['Price'].values[s]) * data['Amount'].values[s]) tempT.append(temp) tempTT.append(tempT) fig = go.FigureWidget( make_subplots(shared_xaxes=True, specs=[[{ "secondary_y": True }]], print_grid=False)) trace3 = go.Scatter(name="0 line", x=pay.index, y=np.array([0 for i in Distrib]), xaxis='x1', yaxis='y2', line=dict(color='black', width=2, dash='dash')) fig.add_trace(trace3, secondary_y=False) trace1 = go.Scatter(name="Payoff", x=pay.index, y=pay.values, xaxis='x1', yaxis='y2', mode='lines', fill='tozeroy') fig.add_trace(trace1, secondary_y=False) for i in range(len(tempTT)): trace5 = go.Scatter(name="Price - " + str(days[i]) + ' Days', x=pay.index, y=pd.DataFrame(tempTT[i]).sum().values, xaxis='x1', yaxis='y2', mode='lines') fig.add_trace(trace5, secondary_y=False) for lin, i in zip(pays.values, pays.index): trace4 = go.Scatter(name=data.Instrument.values[i], x=pay.index, y=lin, xaxis='x1', yaxis='y2', line=dict(width=2, dash='dash')) fig.add_trace(trace4, secondary_y=False) for i, j in zip(days, dists): trace2 = ff.create_distplot([j], [str(i) + " Days - Probabilidade"], bin_size=.5, curve_type='normal', show_hist=False, show_rug=False) fig.add_trace(trace2['data'][0], secondary_y=True) prob = round(sum(pay.values > 0) / len(Distrib) * 100, 2) return [fig, html.H6("Profit probability: " + str(prob) + "%")] else: fig = go.FigureWidget( make_subplots(shared_xaxes=True, specs=[[{ "secondary_y": True }]], print_grid=False)) trace3 = go.Scatter(name="0 line", x=[0], y=[0], xaxis='x1', yaxis='y2', line=dict(color='black', width=2, dash='dash')) fig.add_trace(trace3, secondary_y=False) return [fig, html.H6(str(0) + "%")] else: fig = go.FigureWidget( make_subplots(shared_xaxes=True, specs=[[{ "secondary_y": True }]], print_grid=False)) trace3 = go.Scatter(name="0 line", x=[0], y=[0], xaxis='x1', yaxis='y2', line=dict(color='black', width=2, dash='dash')) fig.add_trace(trace3, secondary_y=False) return [fig, html.H6(str(0) + "%")]
data=optionsInfo[optionsInfo.Instrument.isin(lll)] data['Amount']=[-1000,-1000] #data['Amount']=np.random.randint(-1,1, size=len(data)) data['Amount']=data['Amount'].astype(float) data['TRDPRC_1']=data['TRDPRC_1'].astype(float) data['STRIKE_PRC']=data['STRIKE_PRC'].astype(float) data["TRADE_DATE"]=pd.to_datetime(data["TRADE_DATE"]) data["EXPIR_DATE"]=pd.to_datetime(data["EXPIR_DATE"]) #data['PUTCALLIND']=['CALL','CALL'] ssp=spot[spot["Instrument"]!="BRSELICD=CBBR"].TRDPRC_1.values[0] days=(data.apply(lambda row: businessDuration(startdate=row['TRADE_DATE'],enddate=row['EXPIR_DATE'],unit='day'), axis=1)).values j=0 ImpyVola=[round(Func.ImpliedVola(spot[spot["Instrument"]!="BRSELICD=CBBR"].TRDPRC_1.values[0].astype(float), data["STRIKE_PRC"].values[j].astype(float), spot[spot["Instrument"]=="BRSELICD=CBBR"].TRDPRC_1.values[0].astype(float)/100, .70, data["TRDPRC_1"].values[j].astype(float), days[j], # (((data["EXPIR_DATE"].values[j])-(data["TRADE_DATE"].values[j])).astype('timedelta64[D]').astype(int)), data["PUTCALLIND"],a=-12.0, b=12.0, xtol=1e-8)*100,2) for j in range(len(data))] GREEKS=Func.OpitionsPrice(spot[spot["Instrument"]!="BRSELICD=CBBR"].TRDPRC_1.values[0].astype(float), data["STRIKE_PRC"].values.astype(float), spot[spot["Instrument"]=="BRSELICD=CBBR"].TRDPRC_1.values[0].astype(float)/100,
def all(spot,data): ssp=spot.TRDPRC_1.values[0] data['Amount']=data['Amount'].astype(float) data['TRDPRC_1']=data['TRDPRC_1'].astype(float) data['STRIKE_PRC']=data['STRIKE_PRC'].astype(float) data["TRADE_DATE"]=pd.to_datetime(data["TRADE_DATE"]) data["EXPIR_DATE"]=pd.to_datetime(data["EXPIR_DATE"]) days=(data.apply(lambda row: businessDuration(startdate=row['TRADE_DATE'],enddate=row['EXPIR_DATE'],unit='day'), axis=1)).values ImpyVola=[round(ImpliedVola(spot.TRDPRC_1.values[0].astype(float), data["STRIKE_PRC"].values[j].astype(float), spot.TRDPRC_1.values[1]/100, .70, data["TRDPRC_1"].values[j].astype(float), days[j], # (((data["EXPIR_DATE"].values[j])-(data["TRADE_DATE"].values[j])).astype('timedelta64[D]').astype(int)), data["PUTCALLIND"].values[j],a=-12.0, b=12.0, xtol=1e-8)*100,2) for j in range(len(data))] GREEKS=OpitionsPrice(spot.TRDPRC_1.values[0].astype(float), data["STRIKE_PRC"].values.astype(float), spot.TRDPRC_1.values[1]/100, np.array(ImpyVola)/100, days) vola, err = ek.get_data([spot[spot["Instrument"]!="BRSELICD=CBBR"].Instrument.values[0]], ['TR.Volatility5D','TR.Volatility10D',"TR.Volatility20D", "TR.Volatility30D","TR.Volatility60D","TR.Volatility90D"]) vola.columns=['Instrument',5,10,20,30,60,90] vola[[5,10,20,30,60,90]]=vola[[5,10,20,30,60,90]]/100 days=list(np.unique(days)) dists=[] vollist=[] for d in days: y_interp = scipy.interpolate.interp1d(vola.columns[1:].astype(float),vola.T[0].values[1:].astype(float)) volaV=y_interp(d) Distrib=np.random.lognormal(0,(volaV/(252**0.5)*(d**0.5)), size=5000) Distrib=Distrib*ssp vollist.append(volaV) dists.append(Distrib) for i in range(len(dists)): dists[i]=dists[i][(dists[i]>ssp*0.8)&(dists[i]<ssp*1.2)] Price=np.array(dists).reshape(np.array(dists).shape[0]*np.array(dists).shape[1]) # dists=[Price] Price.sort() net=[] for k in range(len(data)): if data['Amount'].iloc[k]>=0: if "C" in data['PUTCALLIND'].iloc[k]: Rt= -data['STRIKE_PRC'].iloc[k]-data['TRDPRC_1'].iloc[k] +Price Rt[Rt<=-data['TRDPRC_1'].iloc[k]]=-data['TRDPRC_1'].iloc[k] Rt=Rt*abs(data['Amount'].iloc[k]) net.append(list(Rt)) else: Rt= data['STRIKE_PRC'].iloc[k] -data['TRDPRC_1'].iloc[k] -Price Rt[Rt<=-data['TRDPRC_1'].iloc[k]]=-data['TRDPRC_1'].iloc[k] Rt=Rt*abs(data['Amount'].iloc[k]) net.append(list(Rt)) else: if "C" in data['PUTCALLIND'].iloc[k]: Rt= data['STRIKE_PRC'].iloc[k] +data['TRDPRC_1'].iloc[k] -Price Rt[Rt>=data['TRDPRC_1'].iloc[k]]=data['TRDPRC_1'].iloc[k] Rt=Rt*abs(data['Amount'].iloc[k]) net.append(list(Rt)) else: Rt= -data['STRIKE_PRC'].iloc[k] +data['TRDPRC_1'].iloc[k] +Price Rt[Rt>=data['TRDPRC_1'].iloc[k]]=data['TRDPRC_1'].iloc[k] Rt=Rt*abs(data['Amount'].iloc[k]) net.append(list(Rt)) tempTT=[] for j in range(len(set(days))): tempT=[] for s in range(len(data["STRIKE_PRC"])): temp=OpitionsPrice(Price, data["STRIKE_PRC"].values.astype(float)[s], spot.TRDPRC_1.values[1]/100, np.array(ImpyVola[j])/100, days[j]) if "C" in data["PUTCALLIND"].values[s]: temp=list((temp.ValorC.values-data['TRDPRC_1'].values[s])*data['Amount'].values[s]) else: temp=list((temp.ValorP.values-data['TRDPRC_1'].values[s])*data['Amount'].values[s]) tempT.append(temp) tempTT.append(tempT) pay=pd.DataFrame(net) pay.columns=Price pays=pay pay=pay.sum() fig=StrPL(Distrib,pay,pays,tempTT,days,dists,data) prob=round(sum(pay.values>0)/len(Distrib)*100,2) return(fig,prob)
from business_duration import businessDuration import pandas as pd received_time = pd.to_datetime('2020-10-19 08:32:00') complete_time = pd.to_datetime('2020-10-19 19:42:00') period = (businessDuration(received_time, complete_time, unit='min') - 90) / 60 print(period)
# -*- coding: utf-8 -*- """ Created on Thu Jun 13 14:15:35 2019 @author: amjuli """ # Install business-duration and holidays packages from command prompt # pip install business-duration # pip install holidays from business_duration import businessDuration import pandas as pd from datetime import time, datetime import holidays as pyholidays time_elapsed = businessDuration( startdate=pd.to_datetime('2019-06-13 14:23:42'), enddate=pd.to_datetime('2019-06-20 14:23:42'), starttime=time(9, 0, 0), endtime=time(17, 0, 0), weekendlist=[5, 6], holidaylist=pyholidays.UnitedStates(), unit='hour') print(time_elapsed)
import holidays as pyholidays from datetime import time #Start date must be in standard python datetime format start_date = pd.to_datetime('2017-07-01 02:02:00') #Start date must be in standard python datetime format end_date = pd.to_datetime('2017-07-07 04:48:00') #Business open hour must be in standard python time format-Hour,Min,Sec biz_open_time = time(8, 0, 0) biz_close_time = time(17, 0, 0) #US public holidays US_holiday_list = pyholidays.US(state='NY') #Business duration can be 'day', 'hour', 'min', 'sec' unit_hour = 'hour' #Printing output print( businessDuration(startdate=start_date, enddate=end_date, starttime=biz_open_time, endtime=biz_close_time, holidaylist=US_holiday_list, unit=unit_hour)) #Result #30.0
def CalculateResolutionTime(created_dt, resolved_dt, Country, Buss_hrs_df): try: # If the resolved_dt is not found, populate resolution_time_hrs with 0.00 if resolved_dt == '' or pd.isnull(resolved_dt) or resolved_dt is None: resolution_time_hrs = 0.00 else: Df_business_hrs = Buss_hrs_df.copy() date_tz = 'Asia/Singapore' Df_business_hrs['Country_TimeZone'] = Df_business_hrs[ 'Country_TimeZone'].replace('Sydney', 'Australia') Df_business_hrs['Country_TimeZone'] = Df_business_hrs[ 'Country_TimeZone'].replace('Tokyo', 'Japan') if (Country == "HK" or Country == "HKG" or Country == "Hong Kong"): Cntry = 'Hong Kong' elif (Country == "SG" or Country == "SIN"): Cntry = 'Singapore' else: Cntry = Country Start_Hour = 9 Start_Min = 0 End_Hour = 18 End_Min = 0 Cntry_tz = 'Singapore' for i, row in Df_business_hrs.iterrows(): if Cntry == row['Country_TimeZone']: Start_Hour = int(row['Start_Hour']) Start_Min = int(row['Start_Min']) End_Hour = int(row['End_Hour']) End_Min = int(row['End_Min']) Cntry_tz = Cntry if Cntry_tz != "Singapore": created_dt = ChangeDateToLocalTimeZone( created_dt, date_tz, row['Timezone']) resolved_dt = ChangeDateToLocalTimeZone( resolved_dt, date_tz, row['Timezone']) break starttime = time(Start_Hour, Start_Min, 0) endtime = time(End_Hour, End_Min, 0) if Cntry_tz == 'Hong Kong': Cntry_tz = 'HongKong' holidaylist = pyholidays.CountryHoliday(Cntry_tz) unit = 'hour' resolution_time_hrs = 0.00 #By default weekends are Saturday and Sunday created_dt = datetime.strptime(created_dt, '%Y-%m-%d %H:%M:%S') resolved_dt = datetime.strptime(resolved_dt, '%Y-%m-%d %H:%M:%S') resolution_time = (businessDuration(created_dt, resolved_dt, starttime, endtime, holidaylist=holidaylist, unit=unit)) if resolution_time == '' or pd.isnull(resolution_time): resolution_time_hrs = 0.00 else: resolution_time_hrs = resolution_time / 24 return resolution_time_hrs except: logger.error("Resolution time cannot be computed. Please check")
def process_mad(filename): open_time = datetime.time(6, 0, 0) close_time = datetime.time(18, 0, 0) holidaylist = pyholidays.US() try: CURSOR['mad'].execute(READ['all'], ) except MySQLdb.Error as err: sql_error(err) handle = open(filename, 'w') if filename else sys.stdout rows = CURSOR['mad'].fetchall() workdict = dict() for row in rows: if row[5] and (row[5] < row[4] or not row[4]): continue if (not row[5]) and ARG.COMPLETED: continue if (row[5]) and not ARG.COMPLETED: continue org = '' if row[1] in workdict: org = workdict[row[1]] else: workday = call_responder('config', 'config/workday/' + row[1], True) if 'config' in workday and 'organization' in workday['config']: org = workday['config']['organization'] workdict[row[1]] = org completed = 1 if row[5] else 0 duration = row[6] if (row[6] > 0) else 0 if row[5]: startstring = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(row[4])) endstring = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(row[5])) startdate = pd.to_datetime(startstring) enddate = pd.to_datetime(endstring) working_duration = businessDuration(startdate, enddate, open_time, close_time, holidaylist=holidaylist, unit='hour') * 3600 try: working_duration = int(working_duration) except ValueError as err: logger.error( str(err) + ' for ' + startstring + ', ' + endstring) working_duration = duration logger.debug("Working duration %s-%s is %f sec" % (startdate, enddate, working_duration)) else: working_duration = 0 rec = { 'id': row[0], 'user': row[1], 'organization': org, 'annotation': row[2], 'type': row[3], 'start_time': row[4], 'end_time': row[5], 'duration': duration, 'working_duration': working_duration } handle.write(json.dumps(rec) + "\n") if handle is not sys.stdout: handle.close()