def mail_analysis(self, analysis): smtp_fname = '{0:s}/.smtp.cfg'.format(os.getenv('HOME')) with open(smtp_fname, 'r') as f: lines = f.readlines() smtp_server = lines[0].strip() smtp_user = lines[1].strip() smtp_passwd = lines[2].strip() smtp_email = lines[3].strip() smtp_port = 587 res = '' for _, row in analysis.iterrows(): res = '{0:s}\r\n{1:s} {2:6s} {3:12s} {4:6.2f} {5:11d}'.format( res, str(row['date']), row['stk'], row['setup'], row['rg'], int(row['v_50'])) try: try: s = smtplib.SMTP(host=smtp_server, port=smtp_port) s.starttls() s.login(smtp_user, smtp_passwd) msg = MIMEText(res, 'plain') msg['Subject'] = 'IDA {0:s}'.format( stxcal.current_busdate(hr=12)) msg['From'] = smtp_email msg['To'] = smtp_email s.sendmail(smtp_email, smtp_email, msg.as_string()) finally: s.quit() except: print('Failed to send email: {0:s}'.format(traceback.print_exc()))
choices=list(Datafeed), default=Datafeed.stooq) parser.add_argument('-d', '--data_dir', help='download directory for EOD files', type=str, default=os.path.join(os.getenv('HOME'), 'Downloads')) args = parser.parse_args() logging.basicConfig( format='%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] - ' '%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO) logging.info('Getting index (S&P500, Nasdaq, Dow Jones) quotes') si = StxIndex() index_end_date = stxcal.current_busdate(hr=9) index_start_date = stxcal.move_busdays(index_end_date, -5) for idx in ['^GSPC', '^IXIC', '^DJI']: try: si.get_quote(idx, index_start_date, index_end_date) except: logging.error(f'Get index quote failed for {idx}') tb.print_exc() sdf = StxDatafeed() res = stxdb.db_read_cmd("SELECT dt FROM analyses WHERE " "analysis='eod_datafeed'") start_date = str(res[0][0]) if res else '2000-01-01' logging.info('The start date is: {0:s}'.format(start_date)) res = stxdb.db_read_cmd("SELECT MAX(dt) FROM dividends")
def get_opt_spread_leaders(self, ldr_date): next_exp = stxcal.next_expiry(ldr_date) calc_exp = stxcal.next_expiry(ldr_date, 9) crt_date = stxcal.current_busdate() cnx = stxdb.db_get_cnx() stx = self.get_leaders(ldr_date) print('Calculating option spread for {0:d} stocks'.format(len(stx))) num = 0 if ldr_date <= self.last_opt_date: opt_tbl_name = 'options' spot_tbl_name = 'opt_spots' spot_column = 'spot' opt_date_column = 'date' else: opt_tbl_name = 'opt_cache' spot_tbl_name = 'eods' spot_column = 'c' opt_date_column = 'dt' for stk in stx: print('stk = {0:s}'.format(stk)) spot_q = sql.Composed([ sql.SQL('select {} from {} where stk=').format( sql.Identifier(spot_column), sql.Identifier(spot_tbl_name)), sql.Literal(stk), sql.SQL(' and date='), sql.Literal(crt_date) ]) with cnx.cursor() as crs: crs.execute(spot_q.as_string(cnx)) spot_res = crs.fetchone() if spot_res is None: continue spot = float(spot_res[0]) tokens = stk.split('.') und = '.'.join(tokens[:-1]) if tokens[-1].isdigit() else stk opt_q = sql.Composed([ sql.SQL('select * from {} where expiry=').format( sql.Identifier(opt_tbl_name)), sql.Literal(calc_exp), sql.SQL(' and und='), sql.Literal(und), sql.SQL(' and {}=').format(sql.Identifier(opt_date_column)), sql.Literal(crt_date) ]) opt_df = pd.read_sql(opt_q.as_string(cnx), cnx) if len(opt_df) < 6: continue opt_df['strike_spot'] = abs(opt_df['strike'] - spot) opt_df['spread'] = 100 * (1 - opt_df['bid'] / opt_df['ask']) opt_df.sort_values(by=['strike_spot'], inplace=True) opt_df['avg_spread'] = opt_df['spread'].rolling(6).mean() try: avg_spread = int(opt_df.iloc[5].avg_spread * 100) avg_atm_price = round( (opt_df.iloc[0].ask + opt_df.iloc[1].ask) / 2, 2) with cnx.cursor() as crs: crs.execute( 'update leaders set opt_spread=%s, ' 'atm_price=%s where stk=%s and exp=%s', (avg_spread, avg_atm_price, stk, next_exp)) except: print('Failed to calc avg_spread for {0:s}'.format(stk)) num += 1 if num % 100 == 0 or num == len(stx): print('Calculated option spread for {0:d} stocks'.format(num))
def eod_job(self): print('247 end of day job') ana_date = stxcal.current_busdate(hr=10) print(' ana_date = {0:s}'.format(ana_date)) self.eod_analysis(ana_date)
def intraday_analysis(self): ana_date = stxcal.current_busdate(hr=10) self.get_data(ana_date, get_for_all=False, get_eod=True, get_opts=False)
parser.add_argument('-d', '--ldr_date', type=valid_date, help="The date for leaders - format YYYY-MM-DD") parser.add_argument('-e', '--eod', action='store_true', help="Run EOD analysis") parser.add_argument('-i', '--intraday', action='store_true', help="Run Intraday analysis") args = parser.parse_args() if args.leaders: ldr_date = args.ldr_date if args.ldr_date else stxcal.current_busdate() min_act = args.min_act if args.min_act else 80000 min_rcr = args.range_close_ratio if args.range_close_ratio else 0.015 print('Will calculate leaders for {0:s} w/ min act of {1:d} and ' 'min range to close ratio of {2:.3f}'.format( ldr_date, min_act, min_rcr)) s247 = Stx247() s247.get_liq_leaders(ldr_date, min_act, min_rcr) if args.get_options: print('Will retrieve options and calculate spread liquidity') s247.get_opt_spread_leaders(ldr_date) exit(0) if args.eod: s247 = Stx247() s247.eod_job() exit(0)
z.close() logging.info(f'Archived {num_archived_pdfs} PDF reports '\ f'in {zipfile_name}') if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-s', '--max_spread', type=int, default=33, help='Maximum spread for leaders') parser.add_argument('-d', '--date', type=str, default=stxcal.current_busdate(hr=9), help='Date to retrieve setups') parser.add_argument('-e', '--eod', action='store_true', help="Run EOD analysis") parser.add_argument('-i', '--intraday', action='store_true', help="Run Intraday analysis") parser.add_argument('-c', '--cron', action='store_true', help="Flag invocation from cron job") parser.add_argument('-a', '--startdate',