def setUp(self): self.user = User.objects.create(email='*****@*****.**', username='******') self.other_user = User.objects.create(email='*****@*****.**', username='******') self.competition = Competition.objects.create(creator=self.user, modified_by=self.user) self.participant_1 = CompetitionParticipant.objects.create( user=self.user, competition=self.competition, status=ParticipantStatus.objects.get_or_create(name='approved', codename=ParticipantStatus.APPROVED)[0] ) self.participant_2 = CompetitionParticipant.objects.create( user=self.other_user, competition=self.competition, status=ParticipantStatus.objects.get_or_create(name='approved', codename=ParticipantStatus.APPROVED)[0] ) self.phase_1 = CompetitionPhase.objects.create( competition=self.competition, phasenumber=1, start_date=datetime.datetime.now() - datetime.timedelta(days=30), ) self.phase_2 = CompetitionPhase.objects.create( competition=self.competition, phasenumber=2, start_date=datetime.datetime.now() - datetime.timedelta(days=15), auto_migration=True ) submission_finished = CompetitionSubmissionStatus.objects.create(name="finished", codename="finished") self.submission_1 = CompetitionSubmission.objects.create( participant=self.participant_1, phase=self.phase_1, status=submission_finished, submitted_at=datetime.datetime.now() - datetime.timedelta(days=29) ) self.submission_2 = CompetitionSubmission.objects.create( participant=self.participant_1, phase=self.phase_1, status=submission_finished, submitted_at=datetime.datetime.now() - datetime.timedelta(days=28) ) self.submission_3 = CompetitionSubmission.objects.create( participant=self.participant_2, phase=self.phase_1, status=submission_finished, submitted_at=datetime.datetime.now() - datetime.timedelta(days=28) ) self.leader_board = PhaseLeaderBoard.objects.create(phase=self.phase_1) self.leader_board_entry_1 = PhaseLeaderBoardEntry.objects.create( board=self.leader_board, result=self.submission_2 ) self.leader_board_entry_2 = PhaseLeaderBoardEntry.objects.create( board=self.leader_board, result=self.submission_3 ) self.client = Client()
def save(self): if self.price == None: self.price = 0.00 if not self.adjusted: self.start = self.start + datetime.timedelta(days=-1) self.end = self.end + datetime.timedelta(days=-1) self.adjusted = True return super(LocalEvent, self).save()
def setUp(self): self.user = User.objects.create(email='*****@*****.**', username='******') self.other_user = User.objects.create(email='*****@*****.**', username='******') self.competition = Competition.objects.create(creator=self.user, modified_by=self.user) self.participant_1 = CompetitionParticipant.objects.create( user=self.user, competition=self.competition, status=ParticipantStatus.objects.get_or_create( name='approved', codename=ParticipantStatus.APPROVED)[0]) self.participant_2 = CompetitionParticipant.objects.create( user=self.other_user, competition=self.competition, status=ParticipantStatus.objects.get_or_create( name='approved', codename=ParticipantStatus.APPROVED)[0]) self.phase_1 = CompetitionPhase.objects.create( competition=self.competition, phasenumber=1, start_date=datetime.datetime.now() - datetime.timedelta(days=30), ) self.phase_2 = CompetitionPhase.objects.create( competition=self.competition, phasenumber=2, start_date=datetime.datetime.now() - datetime.timedelta(days=15), auto_migration=True) submission_finished = CompetitionSubmissionStatus.objects.create( name="finished", codename="finished") self.submission_1 = CompetitionSubmission.objects.create( participant=self.participant_1, phase=self.phase_1, status=submission_finished, submitted_at=datetime.datetime.now() - datetime.timedelta(days=29)) self.submission_2 = CompetitionSubmission.objects.create( participant=self.participant_1, phase=self.phase_1, status=submission_finished, submitted_at=datetime.datetime.now() - datetime.timedelta(days=28)) self.submission_3 = CompetitionSubmission.objects.create( participant=self.participant_2, phase=self.phase_1, status=submission_finished, submitted_at=datetime.datetime.now() - datetime.timedelta(days=28)) self.leader_board = PhaseLeaderBoard.objects.create(phase=self.phase_1) self.leader_board_entry_1 = PhaseLeaderBoardEntry.objects.create( board=self.leader_board, result=self.submission_2) self.leader_board_entry_2 = PhaseLeaderBoardEntry.objects.create( board=self.leader_board, result=self.submission_3) self.client = Client()
def get_wdty_info(request): """获取网贷天眼数据信息并存入数据库""" if request.method == "GET": headers = {"User-Agent": random.choice(utils.user_agent)} response = requests.get("http://www.p2peye.com/shuju/ptsj/", headers=headers) ret = response.content.decode("GBK") tbody = re.findall('<tbody[\s\S]*</tbody>', ret, re.S) # 获取tbody内容 name = re.findall('>(.{2,10})<\/a', tbody[0], re.S) # 获取平台名称 name = [i for i in name if i != "添加关注"] total = re.findall('<td class="total">(\d*.\d*)万</td>', tbody[0], re.S) # 获取平台成交额(万) rate = re.findall('<td class="rate">(\d*.\d*)%</td>', tbody[0], re.S) # 获取平台综合利率(%) pnum = re.findall('<td class="pnum">(\d*)人</td>', tbody[0], re.S) # 获取平台投资人数(人) cycle = re.findall('<td class="cycle">(\d*.\d*)月</td>', tbody[0], re.S) # 获取平台借款周期(月) p1num = re.findall('<td class="p1num">(\d*)人</td>', tbody[0], re.S) # 获取平台借款人(人) fuload = re.findall('<td class="fuload">(\d*.\d*)分钟</td>', tbody[0], re.S) # 获取平台满标速度(分钟) alltotal = re.findall('<td class="alltotal">(-?\d*.\d*)万</td>', tbody[0], re.S) # 获取平台累计贷款余额(万) capital = re.findall('<td class="capital">(-?\d*.\d*)万</td>', tbody[0], re.S) # 获取平台资金净流入(万) data_list = [] # 存放500万及以上平台数据信息包括人众金服 for index, temp_name in enumerate(name): if float(total[index]) >= 500 or temp_name == "人众金服": # 存放每一个平台的信息 temp_dict = {} temp_dict["name"] = temp_name # 平台名称 temp_dict["total"] = float(total[index]) # 平台成交额(万) temp_dict["rate"] = float(rate[index]) # 平台综合利率(%) temp_dict["pnum"] = int(pnum[index]) # 平台投资人数(人) temp_dict["cycle"] = float(cycle[index]) # 平台借款周期(月) temp_dict["p1num"] = int(p1num[index]) # 平台借款人(人) temp_dict["fuload"] = float(fuload[index]) # 平台满标速度(分钟) temp_dict["alltotal"] = float(alltotal[index]) # 平台累计贷款余额(万) temp_dict["capital"] = float(capital[index]) # 平台资金净流入(万) data_list.append(temp_dict) # 循环存入每个平台的信息 qdate = datetime.datetime.strftime(datetime.datetime.now() + datetime.timedelta(-1), "%Y-%m-%d") # 获取昨天日期 for msg_dict in data_list: models.WDTY_Info.objects.using("default").create( qdate=qdate, # 日期 name=msg_dict.get("name"), # 平台名称 total=msg_dict.get("total"), # 平台成交额(万) rate=msg_dict.get("rate"), # 平台综合利率(%) pnum=msg_dict.get("pnum"), # 平台投资人数(人) cycle=msg_dict.get("cycle"), # 平台借款周期(月) p1num=msg_dict.get("p1num"), # 平台借款人(人) fuload=msg_dict.get("fuload"), # 平台满标速度(分钟) alltotal=msg_dict.get("alltotal"), # 平台累计贷款余额(万) capital=msg_dict.get("capital") # 平台资金净流入(万) ) settings.action_logger.info("%s网贷天眼数据已经更新!" % (qdate, )) return HttpResponse("网贷天眼数据填入完毕!")
def since(self, days): return self.filter( order_date__gte=datetime.datetime.combine( datetime.date.today() - datetime.timedelta(days=days), datetime.time.min ) )
def all_tags(request): count = request.GET.get('count', 10) category = request.GET.get('category', Category.ADDICTAF) try: count = int(count) except: count = 10 if count > 100: count = 100 list_all = [] now = datetime.now() start = now - datetime.timedelta(days=2) for post in Post.objects.filter(created__gte=start): list_all.extend(post.tags) list_all = set(list_all) obj = {} for item in list_all: item = item.lower() if not item in obj: obj[item] = 1 continue obj[item] += 1 sorted_by_value = OrderedDict(sorted(obj.items(), key=lambda x: x[1])) resp_items = [] i = 0 for item in sorted_by_value: if i >= count: break resp_items.append(item) i += 1 return Response(sorted_by_value)
def save(self): if self.price == None: self.price = 0.00 if not self.tweet_scheduled and self.tweet_time: from local_settings import BUFFER_CLIENT_ID, BUFFER_CLIENT_SECRET, BUFFER_ACCESS_TOKEN from buffpy.api import API from buffpy.managers.profiles import Profiles api = API(client_id=BUFFER_CLIENT_ID, client_secret=BUFFER_CLIENT_SECRET, access_token=BUFFER_ACCESS_TOKEN) twitter = Profiles(api=api).filter(service='twitter')[0] if self.custom_tweet: text = self.custom_tweet else: text_time = date(self.start, 'P') if self.start.date() == self.tweet_time.date(): text_date = 'Tonight' elif self.start.date() == self.tweet_time.date() + datetime.timedelta(days=1): text_date = 'Tomorrow' else: text_date = date(self.start, 'N j') text = ' ',join([self.title, text_time, text_date,]) if len(text) > 140: text = text[:140] new_tweet = twitter.updates.new(text=text, when=self.tweet_time.isoformat()) self.custom_tweet = text self.tweet_scheduled = True return super(JackpotEvent, self).save()
def report_week(request): import datetime end_date = datetime.datetime.today() start_date = end_date - datetime.timedelta(days=7) sales = Order.objects.filter(created__range=(start_date, end_date)) # sales = Order.objects.filter(created__datoday=month) orders = RequestOrder.objects.filter(created__range=(start_date, end_date)) expenses = Expense.objects.filter(created__range=(start_date, end_date)) report_list = sorted(chain(sales, orders, expenses), key=lambda instance: instance.created) context = { 'transactions': report_list, 'report_type': 'weekly', } return render(request, 'report.html', context)
def get_filtering(self): """ Return filering as a dict for submissions queryset """ self.select_date_form = SelectDateForm(self.request.GET) result = dict() if self.select_date_form.is_valid(): date_from = self.select_date_form.cleaned_data.get('date_from') date_to = self.select_date_form.cleaned_data.get('date_to') if date_to: date_to += datetime.timedelta(days=1) if date_from: result['submit_time__range'] = [date_from, date_to] else: result['submit_time__lte'] = date_to elif date_from: result['submit_time__gte'] = date_from return result
def words(request): now = datetime.now() start = now - datetime.timedelta(days=10) posts = Post.objects.filter(created__gte=start) obj = {} for post in posts: for k in post.caption.split(): k = k.lower() if not k in obj: obj[k] = 1 continue obj[k] += 1 keys = list(obj.keys()) for key in keys: del obj[key] sorted_by_value = OrderedDict(sorted(obj.items(), key=lambda x: x[1])) return Response(sorted_by_value)
def get_wdzj_info(request): """获取网贷之家数据信息并存入数据库""" if request.method == "GET": headers = {"User-Agent": random.choice(utils.user_agent)} # 访问网贷之家数据接口,获取昨天各平台数据信息 response = requests.post("http://shuju.wdzj.com/plat-data-custom.html", headers=headers) data = response.json() # 用json解析数据 qdate = datetime.datetime.strftime(datetime.datetime.now() + datetime.timedelta(-1), "%Y-%m-%d") # 获取昨天日期 # 循环在数据库创建每个平台信息 for msg_dic in data: models.WDZJ_Info.objects.using("default").create( qdate=qdate, # 日期 platName=msg_dic.get("platName"), # 平台名称 amount=msg_dic.get("amount"), # 成交量(万元) incomeRate=msg_dic.get("incomeRate"), # 平均预期收益率(%) loanPeriod=msg_dic.get("loanPeriod"), # 平均借款期限(月) regCapital=msg_dic.get("regCapital"), # 注册资本(万元) fullloanTime=msg_dic.get("fullloanTime"), # 满标用时(分) stayStillOfTotal=msg_dic.get("stayStillOfTotal"), # 待还余额(万元) netInflowOfThirty=msg_dic.get( "netInflowOfThirty"), # 资金净流入(万元) timeOperation=msg_dic.get("timeOperation"), # 运营时间(月) bidderNum=msg_dic.get("bidderNum"), # 投资人数(人) borrowerNum=msg_dic.get("borrowerNum"), # 借款人数(人) totalLoanNum=msg_dic.get("totalLoanNum"), # 借款标数(个) top10DueInProportion=msg_dic.get( "top10DueInProportion"), # 前十大土豪待收金额占比(%) avgBidMoney=msg_dic.get("avgBidMoney"), # 人均投资金额(万元) top10StayStillProportion=msg_dic.get( "top10StayStillProportion"), # 前十大借款人待还金额占比(%) avgBorrowMoney=msg_dic.get("avgBorrowMoney"), # 人均借款金额(万元) developZhishu=msg_dic.get("developZhishu") # 发展指数排名 ) settings.action_logger.info("%s网贷之家数据已经更新!" % (qdate, )) return HttpResponse("网贷之家数据填入完毕!")
def report_print(request, report_name): import datetime end_date = datetime.datetime.today() target = '/tmp/%s.pdf' % report_name if report_name == 'week': start_date = end_date - datetime.timedelta(days=7) sales = Order.objects.filter(created__range=(start_date, end_date)) orders = RequestOrder.objects.filter(created__range=(start_date, end_date)) expenses = Expense.objects.filter(created__range=(start_date, end_date)) report_list = sorted(chain(sales, orders, expenses), key=lambda instance: instance.created) # printing template html_string = render_to_string( 'report_print.html', { 'transactions': report_list, 'total_credit': sum(item.amount_paid for item in sales), 'total_debit': sum(item.amount for item in expenses) + sum(item.requested_price for item in orders) }) html = HTML(string=html_string) html.write_pdf(target=target) elif report_name == 'month': import datetime end_date = datetime.datetime.today() start_date = end_date - datetime.timedelta(days=7) sales = Order.objects.filter(created__range=(start_date, end_date)) orders = RequestOrder.objects.filter(created__range=(start_date, end_date)) expenses = Expense.objects.filter(created__range=(start_date, end_date)) report_list = sorted(chain(sales, orders, expenses), key=lambda instance: instance.created) html_string = render_to_string( 'report_print.html', { 'transactions': report_list, 'total_credit': sum(item.amount_paid for item in sales), 'total_debit': sum(item.amount for item in expenses) + sum(item.requested_price for item in orders) }) html = HTML(string=html_string) html.write_pdf(target=target) elif report_name == 'all': sales = Order.objects.all() orders = RequestOrder.objects.all() expenses = Expense.objects.all() report_list = sorted(chain(sales, orders, expenses), key=lambda instance: instance.created) html_string = render_to_string( 'report_print.html', { 'transactions': report_list, 'total_credit': sum(item.amount_paid for item in sales), 'total_debit': sum(item.amount for item in expenses) + sum(item.requested_price for item in orders) }) html = HTML(string=html_string) html.write_pdf(target=target) else: sales = Order.objects.filter(created__date=end_date) orders = RequestOrder.objects.filter(created__date=end_date) expenses = Expense.objects.filter(created__date=end_date) report_list = sorted(chain(sales, orders, expenses), key=lambda instance: instance.created) html_string = render_to_string( 'report_print.html', { 'transactions': report_list, 'total_credit': sum(item.amount_paid for item in sales), 'total_debit': sum(item.amount for item in expenses) + sum(item.requested_price for item in orders) }) html = HTML(string=html_string) html.write_pdf(target=target) fs = FileSystemStorage('/tmp') file_name = '{}.pdf'.format(report_name) with fs.open(file_name) as pdf: response = HttpResponse(pdf, content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename="{}.pdf"'.format( report_name) return response
def isTriggered(self, **kwargs): isTriggered = False if not self.isValid(): return False if self.indicator_class == 'Manual Indicator': if 'manual_check' in kwargs: manual_check = kwargs['manual_check'] if manual_check == True: isTriggered = True # 5 variables: self.treshold_to_volume (self.lowest_volume), self.volume_interval #last_successful, current_volume, average_volume elif self.indicator_class == 'Volume Indicator': if 'last_successful' in kwargs and 'current_volume' in kwargs and 'average_volume' in kwargs: last_successful = kwargs['last_successful'] current_volume = kwargs['current_volume'] average_volume = kwargs['average_volume'] if current_volume < self.getLowestVolume(): isTriggered = False else: interval = self.getVolumeInterval( average_volume=average_volume) if current_volume - last_successful >= interval: isTriggered = True # Making the assumption that. I'm within market trading hours and outside blackout times # specified in the RobotWindowTime Management. The Robot is responsible for that. elif self.indicator_class == 'Time Indicator': if 'last_successful' in kwargs and 'current_time' in kwargs: last_successful = kwargs['last_successful'] current_time = kwargs['current_time'] interval = current_time - last_successful #now_time = current_time actual_interval = datetime.timedelta( minutes=self.time_interval) #self.time_interval #Know market opening time. #Know my own blackout time if interval > actual_interval: isTriggered = False else: #TODO:Henri now_time - last_successful >= self.time_interval: isTriggered = True elif self.indicator_class == 'Circuit Breaker': if 'circuit_breaker_check' in kwargs: circuit_breaker = kwargs['circuit_breaker_check'] if circuit_breaker: isTriggered = True elif self.indicator_class == 'Immediate Indicator': if 'immediate_check' in kwargs: immediate_check = kwargs['immediate_check'] if immediate_check: isTriggered = True #2 scenarios TQQQ + SQQQ. # 1. First Sale: Profit_exit (TQQQ or SQQQ) # 2. Second Sale Exit_to_close() elif self.indicator_class == 'Profit Indicator': if 'current_stock_price' in kwargs and 'acquisition_stock_price' in kwargs \ and 'number_of_shares' in kwargs and 'minimum_profit' in kwargs: current_stock_price = kwargs['current_stock_price'] acquisition_stock_price = kwargs['acquisition_stock_price'] number_of_shares = kwargs['number_of_shares'] minimum_profit = kwargs['minimum_profit'] if (current_stock_price - acquisition_stock_price ) * number_of_shares > minimum_profit: isTriggered = True elif self.indicator_class == 'Technical Indicator': if 'indicator' in kwargs: indicator = kwargs['indicator'] if indicator == 'macd' and 'volume' in kwargs and 'timeframe' in kwargs: algo = 'macd' volume = kwargs['volume'] timeframe = kwargs['timeframe'] isTriggered = True return isTriggered