def save_json(): try: resp = requests.get( 'https://stockdweebs.com/pick_categories/weekly-picks/', headers=headers) soup = bs.BeautifulSoup(resp.text, 'html.parser') table = soup.find('div', {'class': 'archive-feed-pick'}) symbols = [] for row in table.findAll('article'): symbol = row.get('data-stock-symbol') buy_zones_parent = row.findAll('span', {'class', 'data-value'})[-2] buy_zones = buy_zones_parent.findAll('span', {'class', 'buy-zone'}) entry = buy_zones[0].text[1:] stop = buy_zones[-1].text[1:] single_symbol = dict(entry=entry, symbol=symbol, stop=stop) symbols.append(single_symbol) now = datetime.datetime.now() time = now.strftime("%Y-%m-%d %H:%M:%S") symbols_json = dict(symbols=symbols, time=time) fo = open(data_path, "w") json.dump(symbols_json, fo) fo.close() except Exception as ex: global failed_times failed_times += 1 if failed_times > max_failed_times: content = "EXCEPTION FORMAT PRINT:\n{}".format(ex) mailsender = MailSender(my_sender, my_pass, sender_name, receiver_addr, subject, content, None) mailsender.send_it() else: save_json()
def get_single_stock_price(ticker): try: stockdweebs_headers = { 'origin': 'https://stockdweebs.com', 'referer': 'https://stockdweebs.com/' } # base_url = 'https://api.polygon.io/v2/aggs/ticker/'+ticker + '/prev?unadjusted=true&apiKey=' base_url = 'https://api.polygon.io/v2/snapshot/locale/us/markets/stocks/tickers/' + ticker + '?&apiKey=' # apiKey = '87JHdFHMBgtgmldFUQMN1qHeyxNw5UpN' apiKey = 'b1i5IanrlvBLGCAUDGhGepd924yDRXuX' url = base_url + apiKey resp = requests.get(url, headers=stockdweebs_headers) status = resp.status_code print(status, resp) if status == 429: time.sleep(60) return get_single_stock_price(ticker) if status != 200: content = "polygon 异常" + status mailsender = MailSender(my_sender, my_pass, sender_name, receiver_addr, subject, content, None) mailsender.send_it() else: resp_json = json.loads(resp.text) return float(resp_json.get('ticker').get('day').get('c')) # return float(resp_json.get('results')[0].get('c')) except Exception as ex: time.sleep(5) print(ex) return get_single_stock_price(ticker)
def get_monthly_report(): d = GetPublicData() jjc = d.getJjCode() content = [] jj_zhangfu_list = [] for i in jjc: jjcode = i.strip().split(',')[0] data = i.strip().split(',') sell_point = None is_hold = False if len(data) == 3: sell_point = float(data[2]) if data[2] else None if len(data) > 1: is_hold = True if data[1] else False print(sell_point, is_hold, jjcode) jj, jj_jin = getJijin(jjcode.strip()) name = '' if jj != False: name, guzhi, gutime = jj['name'], jj['gszzl'] + '%', jj['gztime'] jj_content, zhangfu_list = get_single_monthly_report( jjcode, name, sell_point) content.append(jj_content) if is_hold: zhangfu_list.reverse() jj_zhangfu_list.append( dict(label=name if name else jjcode, data=zhangfu_list)) content = '\n\n\n'.join(content) attachment = './result.png' jj_zhangfu_list.reverse() write_plot(jj_zhangfu_list, attachment) mailsender = MailSender(my_sender, my_pass, sender_name, receiver_addr, subject, content, attachment) mailsender.send_it() if os.path.exists(attachment): os.remove(attachment)
def send_mail(self, price): if price < float(self.low_limit.value): # 黄金价格一旦低于self.low_limit.value subject = 'GoldPrice' content = '黄金的价格目前为%s,价格较低,可以买入' % (price) MS = MailSender(self.my_sender, self.my_pass, self.sender_name, self.receiver_addr, subject, content) MS.send_it() if price > float( self.high_limit.value): # 黄金价格一旦高于self.high_limit.value subject = 'GoldPrice' content = '黄金的价格目前为%s,价格较高,可以卖出' % (price) MS = MailSender(self.my_sender, self.my_pass, self.sender_name, self.receiver_addr, subject, content) MS.send_it()
def init(): symbols = load_json() content = '' for single_symbol in symbols: symbol = single_symbol.get('symbol') entry = float(single_symbol.get('entry')) stop = float(single_symbol.get('stop')) current_price = get_single_stock_price(symbol) if current_price < entry and current_price > stop: single_content = 'symbol:' + symbol + '\n entry price: ' + str( entry) + '\n current price: ' + str( current_price) + '\n stop price:' + str(stop) + '\n' content += single_content if len(content) > 0: mailsender = MailSender(my_sender, my_pass, sender_name, receiver_addr, subject, content, None) mailsender.send_it()
def exec(): print('start to calculate the ranks') global exec_count exec_count += exec_count if exec_count < 100: try: init() except Exception as ex: print(ex) logger.error(ex) time.sleep(5) exec() else: now = datetime.datetime.now() subject = 'tipranks exeception ' + now.strftime("%Y-%m-%d %H:%M:%S") attachment = './error.log' content = "got exeception" mailsender = MailSender(my_sender, my_pass, sender_name, receiver_addr, subject, content, attachment) mailsender.send_it()
def get_buy_and_sell_etf(): d = GetETFData() jjc = d.getJjCode() content = [] for i in jjc: jjcode = i.strip().split(',')[0] is_hold = len(i.strip().split(',')) > 1 jj, jj_jin = getJijin(i.strip()) name = '' if jj != False: name = jj['name'] jj_content = get_single_etf_report(jjcode, name, is_hold) if is_hold: content.append(jj_content) else: if '可买' in jj_content: content.append(jj_content) sorted(content, key=functools.cmp_to_key(cmp)) content = '\n\n\n'.join(content) mailsender = MailSender(my_sender, my_pass, sender_name, receiver_addr, subject, content, None) mailsender.send_it()
for amount in amounts: amounts[i] = dc.get_fund_amount(funds[i]) i += 1 i = 0 for fund in funds: fund_price[i], result[i] = get_daily_result(funds[i], amounts[i]) new_amount = float(amounts[i]) + float(result[i]) amounts[i] = new_amount print('开始保存...') dc.update_data(funds[i], fund_price[i], amounts[i]) i += 1 finalresult = sum(result) print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + '合计:' + str(round(finalresult, 2))) if finalresult > 0: content = ("今日收涨,盈利%s元" % round((finalresult), 2) else: content=("今日收跌,亏损%s元" % round((-finalresult), 2)) mailsender=MailSender(my_sender, my_pass, sender_name, receiver_addr, subject, content) if wechat_switch == 1: itchat.send((time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + content), 'filehelper') print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + '微信消息发送成功') else: print((time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))) + '微信消息开关为关,仅发送邮件') mailsender.send_it() print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + '一天后重发') time.sleep(86400) else: print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + '当前为星期%s非交易日,六小时后重试' % (CurrentWeek)) time.sleep(21600) print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + '程序终止')
' 程序运行中...') while 1: price = price_getter.get_price() beginning_price = 265.74 # 265.74为购买价格 percent = ( (float(price) - float(beginning_price)) / float(beginning_price)) * 100 print( time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + '数据获取成功:' + price + ',涨跌幅为' + str(round(percent, 3)) + '%' + '盈亏为' + str((round(percent, 3) * 75))) if price < 265: # 黄金价格一旦低于265.5 subject = 'Goldprice' content = '黄金的价格目前为%s,价格较低,可以买入' % (price) MS = MailSender(my_sender, my_pass, sender_name, receiver_addr, subject, content) MS.send_it() time.sleep(7200) # 两小时至多发一次 # 微信发送消息至文件传输助手 # itchat.send((time.strftime('%Y-%m-%d%H:%M:%S',time.localtime(time.time()))+Content),'filehelper') MailSender(SenderName, ReceiverAddr, Subject, Content) if price > 280: # 黄金价格一旦高于275 Subject = 'Goldprice' Content = '黄金的价格目前为%s,价格较高,可以卖出' % (price) # itchat.send((time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+Content),'filehelper') MS = MailSender(my_sender, my_pass, sender_name, receiver_addr, subject, content) MS.send_it() time.sleep(7200) # 两小时至多发一次 time.sleep(23) # 每隔一定时间爬取一次黄金价格 print(('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + '程序终止')
def init(): existing_ticker = [] init_result_csv() if os.path.exists(result_csv): existing_stock_list = pd.read_csv(result_csv) existing_ticker_series = existing_stock_list['stock_ticker'] for t in existing_ticker_series: existing_ticker.append(t) for ticker in stocks: if isinstance(ticker, str) and ticker not in existing_ticker: logger.info('start fech data:') logger.info('ticker') logger.info(ticker) print('start fech data:') print('ticker') print(ticker) stock_ticker = [] stock_name = [] curr_price = [] pred_low = [] pred_avg = [] pred_high = [] num_analyst = [] s_curr_price = get_curr_price(ticker) if not s_curr_price: continue data = get_target_price(ticker) if not data: continue [companyName, high, low, priceTarget, s_num_analyst] = data if s_num_analyst and priceTarget and low and high: curr_price.append(s_curr_price) pred_low.append(low) pred_high.append(high) num_analyst.append(s_num_analyst) pred_avg.append(priceTarget) stock_ticker.append(ticker) stock_name.append(companyName) info = companyName + ' created' logger.info(info) df = pd.DataFrame() df['stock_ticker'] = stock_ticker df['stock_name'] = stock_name df['curr_price'] = curr_price df['pred_low'] = pred_low df['pred_avg'] = pred_avg df['pred_high'] = pred_high df['# of Analyst'] = num_analyst df['% low/curr'] = [ get_gain(x, y) for x, y in zip(pred_low, curr_price) ] df['% avg/curr'] = [ get_gain(x, y) for x, y in zip(pred_avg, curr_price) ] df['% high/curr'] = [ get_gain(x, y) for x, y in zip(pred_high, curr_price) ] df.to_csv(result_csv, index=None, mode='a+', header=False) if os.path.exists(result_csv): attachment = result_csv content = 'ripranks' now = datetime.datetime.now() subject = 'tipranks result ' + now.strftime("%Y-%m-%d %H:%M:%S") mailsender = MailSender(my_sender, my_pass, sender_name, receiver_addr, subject, content, attachment) mailsender.send_it()