def calc_time(self, date, place, timezone): """Return time of rise and set of object in a place and date :param date: date of day for observation in format [year, month, day] e.c. [2020, 3, 8] :param place: place of observation in format [latitude (°), longitude (°)] e.c. [+49.84, +24.03] :param timezone: timezone, including summer/winter time e.c. +3 """ year, month, day = date lat, lon = place c = -tan(radians(self.decl)) * tan(radians(lat)) if c < -1 or c > 1: self.rise = None self.set = None return None, None delta_time = (Date(year, month, day) - Date(year, 9, 21)).days / 365.24219 * 360 delta = hours_to_degree( self.r_a) - delta_time + hours_to_degree(timezone) - lon hour_angle = degrees(acos(c)) if hour_angle < 180: rise_HA = 360 - hour_angle set_HA = hour_angle else: rise_HA = hour_angle set_HA = 360 - hour_angle rise_time = degree_to_hours((rise_HA + delta) % 360) set_time = degree_to_hours((set_HA + delta) % 360) self.rise = rise_time self.set = set_time return rise_time, set_time
def test_nested_rowset(self): r = [None for x in range(2)] r[0] = row.RowData("-13", Date(1971, 2, 6), "comment7") # noqa r[1] = row.RowData("12", Date(1971, 1, 5), "comment8") # noqa self.rows.append(r) self.assertEqual(self.rows.value, -46)
def match_day_num(today, day): if today.day < int(day): return Date(today.year, today.month, int(day)) else: year = today.year + (today.month // 12) month = (today.month % 12) + 1 return Date(year, month, int(day))
def _iter_month_interest(start_date, end_date, year_interest): year_interest = Decimal(year_interest) / 100 prev = None day_interest = None for cur in _iter_months(start_date, end_date): if prev is None: day_interest = year_interest / year_days(cur.year) prev = cur continue if cur.year == prev.year: interest = day_interest * (cur - prev).days else: assert prev.month == 12 assert cur.month == 1 prev_days = (Date(prev.year, prev.month, 31) - prev).days cur_days = (cur - Date(cur.year, cur.month, 1)).days + 1 assert prev_days + cur_days == (cur - prev).days interest = day_interest * prev_days day_interest = year_interest / year_days(cur.year) interest += day_interest * cur_days yield MonthInterest(cur, interest) prev = cur
def test_iter_month_interest(): assert list(_iter_month_interest("31.12.2012", "28.02.2013", str(365 * 2))) == [ MonthInterest(Date(2013, 1, 31), Decimal("0.62")), MonthInterest(Date(2013, 2, 28), Decimal("0.56")) ]
def test_value(self): self.assertEqual(self.rows.value, -45) self.rows.append(row.RowData("-0.5", Date(1970, 3, 12), "comment9")) # noqa self.rows.append(row.RowData("-0.5", Date(1970, 3, 13), "comment10")) # noqa self.assertEqual(str(self.rows.value), '-46')
def populated_table(): samples = [ Game('Ohio State', 'Michigan', 100, 0, Date(2020, 11, 3)), Game('Penn State', 'Rutgers', 100, 0, Date(2020, 11, 2)), Game('Clemson', 'Alabama', 23, 20, Date(2020, 11, 3)), Game('Ohio State', 'Michigan State', 17, 7, Date(2020, 11, 3)), ] return ScorigamiTable(samples)
def sample_games(): samples = [ Game('Ohio State', 'Michigan', 100, 0, Date(2020, 11, 3)), Game('Penn State', 'Rutgers', 100, 0, Date(2020, 11, 2)), Game('Clemson', 'Alabama', 23, 20, Date(2020, 11, 3)), Game('Ohio State', 'Michigan State', 17, 7, Date(2020, 11, 3)), ] return samples
def absolute_date(info): if isinstance(info, Date): return info elif isinstance(info, tuple): return Date(*info) elif isinstance(info, str) and FORMAT.match(info): return Date(*(int(x) for x in FORMAT.match(info).groups())) raise RuntimeError("Invalid date %s" % info)
def test_forecast_column(self): # TODO: should there be a public accessor for this _headings_x dict? column = self.grid._headings_x[Date(1970, 3, 1)] self.assertEqual(column.isforecast, True) column = self.grid._headings_x[Date(1970, 1, 1)] self.assertEqual(column.isforecast, False)
def test_init(): text = 'オカダ・カズチカ 内藤 哲也' begin_date = Date(2020, 10, 13) end_date = Date(2020, 10, 13) actual = SearchCondition(text=text, begin_date=begin_date, end_date=end_date) assert actual.keywords == ["オカダ", "カズチカ", "内藤", "哲也"] assert actual.begin_date == DateTime(2020, 10, 13) assert actual.end_date == DateTime(2020, 10, 13, 23, 59, 59)
def dateIncrement(date, frequency): if frequency == 'Daily': return date + timedelta(days=1) if frequency == 'Weekly': return date + timedelta(days=7) if frequency == 'Monthly': if date.month == 12: return Date(date.year + 1, 1, date.day) else: return Date(date.year, date.month + 1, date.day) if frequency == 'Yearly': return Date(date.year + 1, date.month, date.day)
def test_extract_games_useless_games(populated_table): expected = [ Game('Ohio State', 'Rutgers', 100, 0, Date(2020, 11, 5)), Game('Penn State', 'Rutgers', 100, 0, Date(2020, 11, 2)), Game('Clemson', 'Alabama', 23, 20, Date(2020, 11, 3)), Game('Ohio State', 'Michigan State', 17, 7, Date(2020, 11, 3)), ] newest_game = Game('Ohio State', 'Rutgers', 100, 0, Date(2020, 11, 5)) updated_table = populated_table updated_table.add_games([newest_game]) result = updated_table.extract_games() assert sorted(result) == sorted(expected)
def test_fields(self): obj = row.RowData(10, Date(1970, 10, 20), "A Comment") self.assertIsInstance(obj, row.RowData) self.assertEqual(obj.value, 10) self.assertEqual(obj.date, Date(1970, 10, 20)) self.assertEqual(obj.comment, "A Comment") self.assertEqual(obj.isforecast, False) self.assertEqual(obj.location, None) with self.assertRaises(ValueError): row.RowData(10, 'notadate', "A Comment")
def test_get_games_1869_correct(): fake_cache = get_fake_cache() result, years = scrape.get_games(fake_cache) expected = [ Game("Rutgers", "Princeton", 6, 4, Date(1869, 11, 6)), Game("Princeton", "Rutgers", 8, 0, Date(1869, 11, 13)) ] current_year = datetime.datetime.now().year expected_years = [i for i in range(1869, current_year + 1)] assert sorted(years) == sorted(expected_years) assert result[1869] == expected
def test_parsing(self): self.assert_parse(None, None) self.assert_parse(None, 'nil') self.assert_parse(XSDDate(2012, 10, 26), '2012-10-26') self.assert_parse(XSDDate(2016, 2, 29, tzinfo=UTC), '2016-02-29Z') parsed_date = self._parse('2012-02-29+01:00') assert_equals(Date(2012, 2, 29), parsed_date.as_datetime_date()) self.assert_same_tz(FixedOffset(1, 0, '+01:00'), parsed_date.tzinfo) parsed_date = self._parse('2012-02-29-02:30') assert_equals(Date(2012, 2, 29), parsed_date.as_datetime_date()) self.assert_same_tz(FixedOffset(-2, -30, '-02:30'), parsed_date.tzinfo)
def year(cls, year: PositiveInteger) -> "DateRange": """ Returns a full year date range for the given year. :param year: The year. :return: Year date range. >>> DateRange.year(PositiveInteger(2019)) DateRange(since=datetime.date(2019, 1, 1), until=datetime.date(2019, 12, 31)) >>> DateRange.year(PositiveInteger(2020)) DateRange(since=datetime.date(2020, 1, 1), until=datetime.date(2020, 12, 31)) """ return cls(Date(year, 1, 1), Date(year, 12, 31))
def list(): return { "items": [ { "title": "Hunky Dory", "release_date": Date(1971, 12, 17), }, { "title": "Spiders From Mars", "release_date": Date(1973, 11, 10), }, ], }
def parse_vox_data(vox_path, measure): vox_data = pd.read_csv(vox_path) periods = [] measure_rates = [] for _, row in vox_data.iterrows(): start = row['start'] start = Date(2020, start // 100, start % 100) end = row['end'] end = Date(2020, end // 100, end % 100) periods.append((start, end)) measure_rates.append(row[measure]) return periods, measure_rates
def test_group_by(self): # TODO - should construct the expected dict and all its rows and # compare to that self.assertEqual(sorted(self.rows.group_by('month').keys()), [ Date(1970, 1, 1), Date(1970, 2, 1), Date(1970, 3, 1), ]) # TODO - should construct the expected dict and all its rows and # compare to that self.assertEqual(sorted(self.rows.group_by('hashtag').keys()), [ 'bills:rent', 'bills:water', 'unknown', ])
def update(self): self.ax.grid() for unit in self.scenario.units: X = [] Y = [] if unit in self.not_units: for contract in self.scenario.list_of_contracts: if contract['Единица измерения'] == unit: price = float(contract['Цена']) if price < self.scenario.max_price and price > self.scenario.min_price: Y.append(price) a = [int(i) for i in contract['date'].split('-')] date = Date(a[0], a[1], a[2]) X.append(date) if len(X) != 0: if self.regr_flag: x = mdates.date2num(X) a = np.array([x, Y]).T df = pd.DataFrame(data=a, columns=['date', 'val']) df = df.sort_values('date') p = np.polyfit(df['date'], df['val'], 2) f = np.poly1d(p) self.ax.plot(df['date'], f(df['date'])) self.ax.scatter(X, Y, label=unit) self.ax.legend() plt.ylabel('Руб.') plt.xticks(rotation=45) plt.savefig('loc_.jpg', bbox_inches='tight') plt.cla() return 'loc_.jpg'
def saleTable(): file = open("sku_sales.csv", 'r', encoding='utf-8') lines = file.readlines() file.close() global saleDict, saleDict_avrday, saleDict_cate3 saleDict = [[[(-1,-1,-1,-1) for i in range(MaxLen)] for dc in range(NumDc)] for sku in range(NumSku+1)] for line in lines[1:]: item_sku_id,dc_id,date,quantity,vendibility,original_price,discount = line.strip().split(',') date = [int(x) for x in date.split('-')] date = (Date(date[0],date[1],date[2])- DayBegin).days item_sku_id,dc_id,quantity,vendibility = int(item_sku_id),int(dc_id),float(quantity),float(vendibility) if(original_price == ''): original_price = -1 else: original_price = float(original_price) if(discount == ''): discount = 10 else: discount = float(discount) saleDict[item_sku_id][dc_id][date] = (int(quantity),int(vendibility),original_price,discount) saleDict_avrday = [[[-1,-1,-1] for i in range(NumDc+1)] for sku in range(NumSku+1)] for sku_id in range(1, NumSku+1): tot_vec = [] cate3 = infoDict[sku_id][2] for dc_id in range(NumDc): vec = [x[:3] for x in saleDict[sku_id][dc_id] if x[0] != -1] tot_vec += vec if(len(vec) == 0): saleDict_avrday[sku_id][dc_id] = [-1,-1,-1]; continue;# (avr_quan, num_vend, avr_ori_price) saleDict_avrday[sku_id][dc_id] = [sum([x[0] for x in vec])/len(vec), len([x[1] for x in vec if x[1] == 0]), -1] vec = [x[2] for x in vec if x[2] != -1] if(len(vec) != 0): saleDict_avrday[sku_id][dc_id][2] = sum(vec) / len(vec) if(len(tot_vec) == 0): saleDict_avrday[sku_id][NumDc] = [-1,-1,-1]; continue; saleDict_avrday[sku_id][NumDc] = [sum([x[0] for x in tot_vec])/len(tot_vec), len([x[1] for x in tot_vec if x[1] == 0]),-1] tot_vec = [x[2] for x in tot_vec if x[2] != -1] if(len(tot_vec) != 0): saleDict_avrday[sku_id][NumDc][2] = sum(tot_vec) / len(tot_vec) saleDict_cate3[cate3][0] += len(tot_vec); saleDict_cate3[cate3][1] += sum(tot_vec); saleDict_cate3 = {key: val[1]/val[0] for key,val in saleDict_cate3.items() if val[0] != 0} print("sale table finished")
def getDate(self): if self.year.get().isdigit() and self.month.get().isdigit() and \ self.day.get().isdigit(): return Date(int(self.year.get()), int(self.month.get()), \ int(self.day.get())) else: return False
def as_datetime_date(self): """ Return a datetime.date instance which represents the same date as this instance (silently ignores the time zone information if present). Raises a ValueError if the date is not representable by datetime.date. """ return Date(self.year, self.month, self.day)
def test_run_two_days_two_traders(self): stock_exchange = StockExchange() stock_market_data = StockMarketData([Company.A, Company.B], [Period.TESTING]).deepcopy_first_n_items(2) trader1 = BuyAndHoldTrader() trader2 = BuyAndHoldTrader() result = stock_exchange.run(stock_market_data, [trader1, trader2]) # test final day final_day = stock_market_data.get_most_recent_trade_day() self.assertEqual(final_day, Date(2012, 1, 4)) # test final portfolio1 final_portfolio1 = result[trader1][final_day] self.assertIsNotNone(final_portfolio1) self.assertEqual(final_portfolio1.cash, 24.807061999999974) self.assertEqual(final_portfolio1.get_stock(Company.A), 14) self.assertEqual(final_portfolio1.get_stock(Company.B), 3) self.assertEqual(final_portfolio1.get_value(stock_market_data), 1005.0684910000001) # test final portfolio2 final_portfolio2 = result[trader2][final_day] self.assertIsNotNone(final_portfolio2) self.assertEqual(final_portfolio2.cash, 24.807061999999974) self.assertEqual(final_portfolio2.get_stock(Company.A), 14) self.assertEqual(final_portfolio2.get_stock(Company.B), 3) self.assertEqual(final_portfolio2.get_value(stock_market_data), 1005.0684910000001)
def DateToTicks(value): """Converts a Date object to ticks.""" timeStruct = Date(value.year, value.month, value.day).timetuple() try: return int(time.mktime(timeStruct)) except: raise DataError("Year out of range")
def meetup_day(year, month, weekday, condition, condition_dict=DEFAULT_CONDITIONS): """ calculates the date of meetups year (int): year month (int): month weekday (str): day of week, e.g. 'Monday' condition (str): e.g. '1st', '2nd', '3rd', '4th', 'last', 'teenth' """ # initialization and error handling weekday_names = [day for day in list(calendar.day_name)] weekday_dict = dict(zip(weekday_names, range(0, 7))) date = Date(year, month, 1) # convert to Date object weekday = weekday_dict[weekday] # swap value to numeric weekday condition = condition_dict[condition] # swap value to numeric condition # call get_weekdays() to get list of weekdays weekdays = get_weekdays(date, weekday) # return either the teenth or the i-th index of weekdays if condition == 'teenth': for day in weekdays: if 13 <= day.day <= 19: return day else: return weekdays[condition]
def update_data(): date = Date(2020, 1, 27) cases_history = {} while date < Date.today(): date_str = date.strftime('%m-%d-%Y') print(URL_BASE + "daily/" + date_str) datas = requests.get(URL_BASE + "daily/" + date_str) datas = json.loads(datas.text) for data in datas: countryRegion = data['countryRegion'] if countryRegion == "Mainland China": countryRegion = "China" countryRegion = countryRegion.lower() if not countryRegion in cases_history: cases_history[countryRegion] = {} #print(type(cases_history[countryRegion])) if not date_str in cases_history[countryRegion]: cases_history[countryRegion][date_str] = int(data["confirmed"]) else: cases_history[countryRegion][date_str] += int( data["confirmed"]) date = date + timedelta(days=1) file = open(join(PATH, 'data', 'cases_history.json'), 'w') file.writelines(json.dumps(cases_history, indent=4)) file.close() print("done.")
def test_bangtags(self): self.assertEqual(self.rows[0].bangtags, dict()) self.assertIn('test_bangtag', self.rows[2].bangtags) with self.assertRaises(ValueError): row.RowData("100", Date(1970, 1, 1), "!test_bangtag !test_bangtag")
def test_get_credit_info(): credit_config = { "amount": "2000000", "interest": "12.25", "start_date": "28.05.2013", "end_date": "28.05.2033", "payments": { "28.06.2013": "110000", "28.07.2013": "21394.54", "28.08.2013": "21394.54", "28.09.2013": "1195000", } } def check(info_date, current_amount, month_pay): assert get_credit_info(info_date, **credit_config) == Credit( get_date(credit_config["start_date"]), get_date(credit_config["end_date"]), Decimal(credit_config["amount"]), Decimal(current_amount), Decimal(credit_config["interest"]), None if month_pay is None else Decimal(month_pay), _calculate(credit_config["start_date"], credit_config["end_date"], credit_config["amount"], credit_config["interest"], credit_config["payments"])) check(Date(1, 1, 1), 2000000, None) check("30.05.2013", 2000000, 110000) check("27.06.2013", 2000000, 110000) check("18.10.2013", "731957.77", "8220.05") check("1.1.2100", 0, None)