def create_event(self, event_data, today): event_id = event_data['identifier'] event = models.Event(identifier=event_id) startTime = event_data['startTime'].split(':') adjusted_now = datetime(today.year, today.month, today.day, int(startTime[0]), int(startTime[1]), int(startTime[2])) event_data['startDate'] = utils.add_time( adjusted_now, event_data['startDateDelta'], event_data['startDateDeltaType']) event_data['endDate'] = utils.add_time(event_data['startDate'], event_data['durationDelta'], event_data['durationDeltaType']) event_data['duration'] = 'PT' + \ str(event_data['durationDelta']) + event_data['durationDeltaType'] event_data['offers'] = [] print('>>> Creating Event ' + event_id) i = 1 for offer_data in LOCAL_DATA['Offers']: offer_id = event_id + str(i) offer = self.create_offer(offer_data, event_id, offer_id, event_data['startDate']) del offer['@context'] event_data['offers'].append(offer) i += 1 event.create(event_data)
def __init__(self, portfolio, params): """ Right so this is the actual strategy. At least this the most basic form of it, planning on interating up :param portfolio: The portfolio of data in the getOneSector return format :param params: Parameters to the strategy as a dictionary I think """ # Parameters self.coint_check_length = None self.use_check_for = None self.critValue = None self.buy_cutoff = None self.sell_cutoff = None self.__set_parameters(params) self.data = portfolio self.format = "%Y-%m-%d" # Start Date of the data entered self.startPortfolio = portfolio[list(portfolio.keys())[0]].index[0] self.endPortfolio = portfolio[list(portfolio.keys())[0]].index[-1] self.CA = CointAnalysis(self.data) self.start_coint_check = self.startPortfolio self.end_coint_check = self.start_future = add_time( self.start_coint_check, month=self.coint_check_length) self.end_future = add_time(self.start_future, month=self.use_check_for) # Gathers all the cointegrated pairs over the last n months. self.cointPairs = self.CA.checkPortfolioForCoint( critValue=self.critValue, fromDate=self.start_coint_check, toDate=self.end_coint_check)
def generateCointegratedPairs(self, fromDate, toDate, cointOver=4, lookback=True): """ This should return a dataframe with dates down the left and all pairs across the top, with a boolean of 0 if the pairs are not cointegrated over the time period looking backward, 1 if they are cointegrated over the time period :param fromDate: Date to start calculation of cointover :param toDate: date to end calculation of cointover :param cointOver:The number of months to test if something is cointegrated over. Too long and it likely breaks, too short and it doesn't have enough :return: The dataframe described above """ lookback_str = self.__lookback_str(lookback) monthsDiff = calc_diff(fromDate, toDate, type='months') array_of_end_dates = [] for i in range(0, monthsDiff + 1): array_of_end_dates.append(add_time(fromDate, month=i)) columns = ['symbol1', 'symbol2'] + array_of_end_dates df = pd.DataFrame(columns=columns) if lookback: current_p_values = self.return_pvalues_portfolio( fromDate=subtract_time(fromDate, month=cointOver), toDate=fromDate) else: current_p_values = self.return_pvalues_portfolio( fromDate=fromDate, toDate=add_time(fromDate, month=cointOver)) df['symbol1'] = current_p_values['symbol1'] df['symbol2'] = current_p_values['symbol2'] if lookback: df[fromDate] = current_p_values[fromDate] else: df[fromDate] = current_p_values[add_time(fromDate, month=cointOver)] for current_date in array_of_end_dates: if current_date == fromDate: continue if lookback: current_p_values = self.return_pvalues_portfolio( fromDate=subtract_time(current_date, month=cointOver), toDate=current_date) df[current_date] = current_p_values[current_date] else: current_p_values = self.return_pvalues_portfolio( fromDate=current_date, toDate=add_time(current_date, month=cointOver)) df[current_date] = current_p_values[add_time(current_date, month=cointOver)] print("{} data stored for {} {}".format(current_date, cointOver, lookback_str)) return df
def get_ideal_series(self, times, task, direction): series = [] weekday = 5 task_per_day = float(task / (weekday * self.SPRINT_WEEK)) remain_task = task for (index, time) in enumerate(times): if index == 0: series.append(remain_task) continue time = utils.add_time(time, -1) if utils.is_weekend(time): series.append(remain_task) else: remain_task -= task_per_day series.append(remain_task) if direction == "up": maximum = max(series) return list(map(lambda x: maximum - x, series)) return series
def create_offer(self, offer_data, event_id, offer_id, event_start_date): print('>>>> Creating Offer ' + offer_id) offer_data['itemOffered'] = { "type": "Event", "id": "$HOST$/events/" + event_id } offer_data['validFrom'] = utils.add_time( event_start_date, offer_data['validFromDelta'], offer_data['validFromDeltaType']) offer_data['validThrough'] = utils.add_time( event_start_date, offer_data['validThroughDelta'], offer_data['validThroughDeltaType']) if offer_data['isCancellable']: offer_data['cancellationValidUntil'] = utils.add_time( event_start_date, offer_data['cancellationValidUntilDelta'], offer_data['cancellationValidUntilDeltaType']) offer = models.Offer(offer_id) offer.create(offer_data) return offer.as_json_ld()
def __init__(self, portfolio, params): """ Right so this is the actual strategy. At least this the most basic form of it, planning on interating up :param portfolio: The portfolio of data in the getOneSector return format :param params: Parameters to the strategy as a dictionary I think """ self.data = portfolio self.format = "%Y-%m-%d" # parameters self.coint_check_length = params['lookback'] self.use_check_for = params['lookforward'] self.critValue = params['critValue'] # Start Date of the data entered self.startPortfolio = portfolio[list(portfolio.keys())[0]].index[0] self.endPortfolio = portfolio[list(portfolio.keys())[0]].index[-1] self.CA = CointAnalysis(self.data) self.start_coint_check = self.startPortfolio self.end_coint_check = self.start_future = add_time( self.start_coint_check, month=self.coint_check_length) self.end_future = add_time(self.start_future, month=self.use_check_for) self.cointPairs = self.CA.checkPortfolioForCoint( critValue=self.critValue, fromDate=self.start_coint_check, toDate=self.end_coint_check)
def create_image( self, data, direction, total_count=0, x_label="Time Series", y_label="Task Count", ): total_count = total_count times = utils.get_time_series( start=utils.add_time(days=self.SPRINT_WEEK * -7), week=self.SPRINT_WEEK) fig, axes = plt.subplots(1) fig.autofmt_xdate() plt.grid(True, axis="x", linestyle="--") plt.plot( times, self.get_ideal_series(times=times, task=total_count, direction=direction), color="red", alpha=0.7, label="Ideal Chart", ) plt.plot( times, data, color="grey", marker=".", alpha=0.3, ) plt.plot( times, data, drawstyle="steps", color="blue", alpha=0.7, label="Actual Chart", ) plt.legend() # 주말 영역은 색칠하기 for time in times[:-1]: if utils.is_weekend(time): plt.axvspan( time, time + timedelta(days=1), facecolor="0.2", alpha=0.1, ) plt.xlabel(x_label) plt.ylabel(y_label) date_format = mdates.DateFormatter("%m-%d") axes.xaxis.set_major_formatter(date_format) plt.savefig("burnchart.png")
def create_order(): params = ['orderedItem', 'acceptedOffer', 'customer', 'broker'] variables, erroring_params, error = utils.request_variables(params) if error: if not variables['orderedItem']: return utils.error_response("incomplete_event_details") if not variables['acceptedOffer']: return utils.error_response("incomplete_offer_details") if not variables['customer']: return utils.error_response("incomplete_customer_details") if not variables['acceptedOffer']: return utils.error_response("incomplete_broker_details") else: event_id = utils.get_identifier( variables['orderedItem'][0]['orderedItem']['id']) offer_id = utils.get_identifier(variables['acceptedOffer'][0]['id']) utils.clean_expired_leases(event_id) event_data, event_error = models.Event(event_id).get() offer_data, offer_error = models.Offer(offer_id).get() if not event_error and not offer_error: quantity_of_order = int( variables['orderedItem'][0]['orderQuantity']) if utils.get_identifier( offer_data['itemOffered']['id']) != utils.get_identifier( event_data['id']): #EVENT DOES NOT MATCH OFFER return utils.error_response("offer_not_valid") if event_data['remainingAttendeeCapacity'] == 0: #EVENT IS FULL return utils.error_response("event_is_full") if event_data['remainingAttendeeCapacity'] < quantity_of_order: #EVENT HAS INSUFFICIENT SPACES return utils.error_response("event_has_insufficient_spaces") if utils.is_date_in_past( utils.from_datestring(event_data['startDate'])): # EVENT IS IN THE PAST return utils.error_response("unavailable_event") if utils.is_date_in_past( utils.from_datestring(offer_data['validThrough'])): # OFFER VALID THROUGH IS IN THE PAST return utils.error_response("offer_expired") if not utils.is_date_in_past( utils.from_datestring(offer_data['validFrom'])): # OFFER VALID FROM IS NOT YET IN THE PAST return utils.error_response("offer_not_yet_valid") order = models.Order() variables['orderDate'] = datetime.now() variables['paymentDueDate'] = utils.add_time( datetime.now(), 15, 'M') value_of_order = offer_data['price'] * quantity_of_order currency_of_offer = offer_data['priceCurrency'] variables['partOfInvoice'] = { "type": "Invoice", "paymentStatus": "https://schema.org/PaymentDue", "totalPaymentDue": { "type": "MonetaryAmount", "value": value_of_order, "currency": currency_of_offer } } order.create(variables) order_data, errors = order.get() order_id = order_data['identifier'] order_summary = { 'leaseExpiresAt': order_data['paymentDueDate'], 'places': quantity_of_order } event_data['remainingAttendeeCapacity'] = event_data[ 'remainingAttendeeCapacity'] - quantity_of_order event_data['orderLeases'][str(order_id)] = order_summary event = models.Event(event_id) event.update(event_data) return utils.json_response( order.as_json_ld(), created=True, created_key=order.as_json_ld()['id'].replace('$HOST$', '')) else: if event_error == 'resource_not_found': # EVENT NOT FOUND return utils.error_response("unavailable_event") if offer_error == 'resource_not_found': # OFFER NOT FOUND return utils.error_response("unavailable_offer")
def get_analysis_data_of_week(self, direction): duration = self.CARD_DURATION status = self.CARD_STATUS done = self.DONE sprint_week = self.SPRINT_WEEK story_points_enabled = self.STORY_POINTS_ENABLED story_points = self.CARD_STORY_POINTS cards = self.board.collection.get_rows() if story_points_enabled: total_count = 0 for card in cards: current_story_point = card.get_property(story_points) if current_story_point == None: continue total_count += current_story_point else: total_count = len(cards) times = utils.get_time_series(start=utils.add_time(days=-sprint_week * 7), week=sprint_week) task_durations = [float(total_count) for _ in range(len(times))] for card in cards: if card.get_property(status) != done: continue notion_date = card.get_property(duration) # 해당 태스크 끝내는 데 걸린 시간 task_duration = notion_date.end - notion_date.start if story_points_enabled: amount_of_task = card.get_property(story_points) else: amount_of_task = 1 # 해당 태스크를 하루에 처리한 양 task_per_day = float(amount_of_task / (task_duration.days + 1)) duration_count = 0 subtracting_start_date = notion_date.start + pd.Timedelta(days=1) subtracting_finish_date = notion_date.end + pd.Timedelta(days=1) for index, time in enumerate(times): if time < subtracting_start_date: continue elif subtracting_start_date <= time <= subtracting_finish_date: duration_count += 1 task_durations[index] = (task_durations[index] - task_per_day * duration_count) else: task_durations[index] = (task_durations[index] - task_per_day * duration_count) if direction == "up": maximum = max(task_durations) task_durations = list(map(lambda x: maximum - x, task_durations)) return {"total_count": total_count, "data": task_durations}