def main(): securities = [ Security(30, "$", RiskLevel.LOW, Trend.UP, 0, "Ukraine", "I"), Equity(20, "$", RiskLevel.MEDIUM, Trend.DOWN, 0, "Russia", "I", "Roshen", 0.5), Debt(10, "$", RiskLevel.HIGH, Trend.UP, 0, "Belarus", "I"), Derivative(0, "$", RiskLevel.DANGER, Trend.UP, 0, "Moldova", "I", "house"), Security(0, "$", RiskLevel.LOW, Trend.DOWN, 10, "Ukraine", "I") ] manager = SecuritiesManager(*securities) filteredList = manager.filterByPrice(0) for s in filteredList: print(s) print() sortedList = SecuritiesManager.sortByPriceAscending(securities) for s in sortedList: print(s) print() sortedFilteredList = SecuritiesManager.sortByDurationDescending( filteredList) for s in sortedFilteredList: print(s)
def main(): #setup my_ib = MyIb() Security.set_trading_exchange_information( exchange_info.trading_exchange_timezone, exchange_info.exchange_opening_time, exchange_info.exchange_normal_close_time, exchange_info.exchange_early_close_time, exchange_info.trading_holidays) #create security object my_security = Security(my_ib, symbol='GOOG', secType='STK', exchange='SMART') #Register callbacks my_ib.conn.register(error_handler, 'Error') my_ib.conn.register(my_security.save_historical_data, 'HistoricalData') my_ib.connect_to_ib_servers() #get SMA sma = my_security.get_historical_sma(length=150, barSizeSetting='1 day', ohlc='CLOSE', whatToShow='MIDPOINT', endDateTime='now') print("My SMA: {}".format(sma)) print(sma) my_ib.conn.disconnect()
def showSalePane(self, event): name = self.login.nameText.GetValue() user = Security(name, self.login.passText.GetValue()) connect = DatabaseConn() connect.cur().execute("UPDATE security SET state = 'off'") data = connect.cur().execute( "select name,password,status from security") if user.checkpass(data): if (user.getStatus() == 'admin'): connect.cur().execute( "UPDATE security SET state = 'on' WHERE name = '{name}'". format(name=name)) connect.commit() self.login.nameText.SetValue("") self.login.passText.SetValue("") self.window.Show(True) self.Hide() self.Layout() else: connect.cur().execute( "UPDATE security SET state = 'on' WHERE name = '{name}'". format(name=name)) connect.commit() self.login.nameText.SetValue("") self.login.passText.SetValue("") self.sales.Show() self.Hide() self.Layout() else: self.login.status.SetLabel("Incorrect Username or Password") connect.close()
def __init__(self, ticket, site=None): super(XmlRpcInit,self).__init__() if not site: # if not explicitly set, keep the current site site = Site.get_site() self.set_app_server("xmlrpc") self.ticket = ticket # clear the main container #Container.clear() Environment.set_env_object( self ) # set up the security object security = Security() Environment.set_security(security) if site: Site.set_site(site) self._do_login()
def rsi_bollinger_report(self): df = pd.DataFrame() for w in self.list(): df_signals = Security(w).signals_rsi_bollinger() if df_signals is None: continue row = { 'security': w, 'last_date_overbought': df_signals[df_signals['signal'] == 'OVER-BOUGHT']['date'].max(), 'last_date_underbought': df_signals[df_signals['signal'] == 'UNDER-BOUGHT']['date'].max(), 'current_sma_price': df_signals[df_signals['date'].max() == df_signals['date']]['sma_price_20dy'].tolist()[0], 'current_price': df_signals[df_signals['date'].max() == df_signals['date']] ['close'].tolist()[0], 'last_updated': df_signals['date'].max() } df_new = pd.DataFrame.from_dict([row]) df = pd.concat([df, df_new]) return df.reset_index(drop=True)
def __init__(self, login_name, password=None): super(XmlRpcLogin,self).__init__() self.set_app_server("xmlrpc") # If the tag <force_lowercase_login> is set to "true" # in the TACTIC config file, # then force the login string argument to be lowercase. # This tag is false by default. self.login_name = login_name if Config.get_value("security","force_lowercase_login") == "true": self.login_name = self.login_name.lower() self.password = password # clear the main container #Container.clear() Environment.set_env_object( self ) # set up the security object security = Security() Environment.set_security(security) self._do_login()
def tsla(self): tsla = Security('TSLA') price = tsla.get_price() self.prices.put(price) volume = tsla.security.get_volume() # if volume != self.volume: # print(volume) # self.volume = volume # else: # return # do things necessary for avg and stddev calc # self.price_sum = self.prices.sum() # self.price_sum_sq = self.prices.sum_sq() # self.count = len(self.prices) avg = self.prices.average() var = self.prices.variance() if price < avg * (1 - self.boundary): # low price, want to buy while portfolio.buy(tsla, 1): pass self.holding = True elif price > avg * (1 + self.boundary): # high price, want to sell_all portfolio.sell_all(tsla) self.holding = False print( f'Price: {price:.2f}\tAvg: {avg:.2f}\tvar: {var:.2f} <{time.asctime()}', end='\r')
def add_security(*args): try: name, ticker, country, ir_website, currency = args except ValueError: print(f"{SYNTAX_INPUT_ERROR} Example: {Security.example_input()}") return db.insert_security(Security(" ".join(name.split("-")), ticker, country, ir_website, currency))
def __init__(self, enabled: bool, expirationSeconds: int, blockAfterFailures: int): self.database = {} self.enabled = enabled self.expirationSeconds = expirationSeconds self.blockAfterFailures = blockAfterFailures self.logs = Logs(self.__class__.__name__) self.security = Security()
def dzh2DivRec(dzh_rec): """convert function""" stamp2date = datetime.datetime.fromtimestamp sec = Security(dzh_rec[0]) return [DivRec(sec, stamp2date(rec[0]).date(), rec[1], rec[4], rec[2], rec[3] ) for rec in dzh_rec[1]]
def __init__(self, line): elts = map(elt_parser, line.rstrip().split("\t")) self.raw = raw = self.Raw(*elts) self.security = Security(raw.StockID, account2market(raw.Account), raw.StockName) self.fee = sum( (float(getattr(raw, 'Fee' + str(i))) for i in (1, 2, 3, 4))) self.quantity = float(raw.Quantity) self.date = dt.datetime.strptime(raw.Date[0:8], "%Y%m%d").date() self.amount = float(self.raw.Amount)
def __init__(self, project_code=None, login_code=None, site=None): self.set_app_server("batch") if not site: # if not explicitly set, keep the current site site = Site.get_site() plugin_dir = Environment.get_plugin_dir() if plugin_dir not in sys.path: sys.path.insert(0, plugin_dir) super(Batch,self).__init__() self.login_code = login_code # clear the main container Container.create() if site: Site.set_site(site) # set this as the environment if not project_code: self.context = self.get_default_context() else: self.context = project_code Environment.set_env_object( self ) # set up the security object security = Security() Environment.set_security(security) self._do_login() site_dir = Environment.get_site_dir() if site_dir not in sys.path: sys.path.insert(0, site_dir) # set the project from pyasm.biz import Project if self.context == "batch": Project.set_project("admin") else: Project.set_project(self.context) self.initialize_python_path() # start workflow engine #from pyasm.command import Workflow #Workflow().init() DbContainer.commit_thread_sql()
def __init__(self, objectName): self.level = 'INFO' if "LOG_LEVEL" in environ: self.level = environ["LOG_LEVEL"] self.format = 'TEXT' if "LOG_FORMAT" in environ: self.format = environ["LOG_FORMAT"] self.objectName = objectName self.security = Security()
def __init__(self, _next_partition_name, _public_key=None, _debug=True): self.debug = _debug self.next_partition_name = _next_partition_name self.public_key = _public_key self.security = Security() self.uuid_project = '' self.version = 0 self.date_expiration = '' self.type = '' self.new = {}
def __init__(self, pricePerUnit=0, currency="$", riskLevel=RiskLevel.LOW, trend=Trend.UP, duration=0, emitent="NoEmitent", owner="NoOwner", asset="NoAsset", security=Security()): super(Debt, self).__init__(pricePerUnit, currency, riskLevel, trend, duration, emitent, owner) self.asset = asset self.security = Security
def __init__(self, ticket=None): super(TacticInit,self).__init__() self.ticket = ticket # create the main container Container.create() Environment.set_env_object( self ) # set up the security object security = Security() Environment.set_security(security)
def update_securities(self, force_full_output=False, max_tries=6): priority = ['ALWAYS', 'FILL'] if len(self._watchlist.keys()) > 500: logger.warning( "Too many securities for API Request. Truncating to 500 oldest-updated reports" ) updated = [] for symbol in self._watchlist.keys(): if os.path.exists( os.path.join(Security.STOCK_DIR, f'{symbol}.json')): with open( os.path.join(Security.STOCK_DIR, f'{symbol}.json')) as f: updated.append({ "symbol": symbol, "updated_at": json.load(f)[-1]['date'], 'priority': self._watchlist[symbol]['update_priority'] }) else: updated.append({ "symbol": symbol, "updated_at": '1970-01-01', 'priority': self._watchlist[symbol]['update_priority'] }) updated = sorted(updated, key=lambda x: (priority.index(x['priority']), x['updated_at'])) securities = [u['symbol'] for u in updated][:500] logger.info(f"Collected securities list: {', '.join(securities)}") for symbol in securities: s = Security(symbol) failed = 0 request = 0 while request == 0 and failed < max_tries: if failed != 0: logger.warning( f"Failed {failed} out of {max_tries} times for {symbol}" ) request = s.update(force_full_output) failed += 1 if request == 0: logger.info("Waiting 12 seconds...") time.sleep(12)
def __init__(self, _uuid_project, _id_device, _version, _host_broker, \ _callback_on_receive_update, _private_key=None, _public_key=None, _delivery_type='Push', _debug=True): self.host_broker = _host_broker self.debug = _debug self.delivery_type = _delivery_type self.id_device = _id_device self.private_key = _private_key self.public_key = _public_key self.security = Security() self.message_incoming = bytes() self.do_decrypt = False self.aes_random_key = '' _id_on_broker = "FotaSuit-" + _uuid_project + "-" + self.id_device self.mqtt_client = MQTTClient(_id_on_broker, self.host_broker) self.mqtt_client.DEBUG = self.debug self.mqtt_client.set_callback(self.publish_received) self.update_file_size = 0 self.update_file_index = 0 self.update_file_handle = 0 self.memory = Memory(self.debug) _next_partition = self.memory.get_next_partition_name() self.callback_on_receive_update = _callback_on_receive_update if not (self.delivery_type == 'Push' or self.delivery_type == 'Pull'): raise ValueError("'type' variable not supported. Try 'Pull' or 'Push'.") while not self.connect_on_broker(True): self.print_debug("trying connection with broker...") time.sleep(3) self.manifest = Manifest(_next_partition, _public_key) self.manifest.load(_uuid_project, _version) files = os.listdir() if '_updated.iota' in files: #have an update ? # notify the upgrade _version = str(self.manifest.version) _msg = '{"idDevice":"'+self.id_device+'", "uuidProject":"'+_uuid_project+'"' _msg += ', "version":'+_version+', "date": ""}' #TODO: insert other informations in message like date self.publish_on_topic(_version, "updated", _msg) os.remove('_updated.iota') self.subscribe_task = "manifest" # waiting for manifest file self.print_debug("initialized.")
def getIndicador(): """ Endpoint that is to get data to render reports on platform """ authOk = True response = exception_response # Allow skipping authentication checks only if in debug mode if app.debug: sec = Security() authOk = sec.validate_access(request.authorization) else: print('\n Authentication checks skipped') if authOk: #return True try: response = [] reportfilter = request.json print("\n *************************") obj = MeuDesconto() ret_audiencia = obj.getIndicadores() resp = make_response(jsonify(ret_audiencia), 200) new_resp = json.loads(resp.data) response.append(new_resp) response = make_response(json.dumps(response)) response.headers[ 'Content-Type'] = 'application/json; charset=utf-8' except Exception as e: now = datetime.now() try: f = open("Logchamadas.log", "a") f.write("\n{0} - Erro: {1} - Parametros : {2}".format( now.strftime("%d/%m/%Y %H:%M:%S"), str(e), str(reportfilter))) f.close() except: pass exception_response['Razao'] = str(e) return make_response(jsonify(exception_response), 400) else: print("\n UNAUTHORIZED ACCESS") raise ValueError return response
def update_page(cell, content): """ update method """ cipher = Security('ec2cli') server, user, passwd, parent_id, page_id, title, response, region, product = config( cell) confluence = Confluence(url=server, username=user, password=cipher.decrypt(passwd)) confluence.update_page(parent_id=parent_id, page_id=page_id, title=title, body=content) return response
def __init__(my, ticket): super(XmlRpcInit, my).__init__() my.set_app_server("xmlrpc") my.ticket = ticket # clear the main container #Container.clear() Environment.set_env_object(my) # set up the security object security = Security() Environment.set_security(security) my._do_login()
def __init__(my, project_code=None, login_code=None, site=None): my.set_app_server("batch") plugin_dir = Environment.get_plugin_dir() if plugin_dir not in sys.path: sys.path.insert(0, plugin_dir) super(Batch, my).__init__() my.login_code = login_code # clear the main container Container.create() if site: Site.set_site(site) # set this as the environment if not project_code: my.context = my.get_default_context() else: my.context = project_code Environment.set_env_object(my) # set up the security object security = Security() Environment.set_security(security) my._do_login() site_dir = Environment.get_site_dir() if site_dir not in sys.path: sys.path.insert(0, site_dir) # set the project from pyasm.biz import Project if my.context == "batch": Project.set_project("admin") else: Project.set_project(my.context) my.initialize_python_path() DbContainer.commit_thread_sql()
def makeTrade(self, security, amount): if amount is 0: print("Entered trading amount of 0") return print("Trading " + str(amount) + " of " + security.securityName + " at price of " + str(security.price)) foundFlag = False if self.positions: for p in self.positions: if p.security.securityName == security.securityName: foundFlag = True newAveragePrice = self.calculateNewPositionAveragePrice(p.security, p.amount, security, amount) p.amount += amount p.security.price = newAveragePrice if p.amount is 0: self.positions.remove(p) if foundFlag == False: newSecurity = Security(security.securityName, security.securityType, security.price) self.positions.append(Position(newSecurity, amount)) self.cash -= (security.price * amount) self.calculatePortfolioValue() self.calculateTotalValue()
def login(self): security = Security() security.decrypt_cred() # credentials = self.getCredential() scopes = [ 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive.file' ] global SERVICE_ACCOUNT if SERVICE_ACCOUNT: logging.info( f"SERVICE_ACCOUNT.auth.expired {SERVICE_ACCOUNT.auth.expired}") if SERVICE_ACCOUNT.auth.expired: SERVICE_ACCOUNT = gspread.service_account('./credentials.json', scopes=scopes) logging.info('Service Account successfully refreshed') return SERVICE_ACCOUNT else: SERVICE_ACCOUNT = gspread.service_account('./credentials.json', scopes=scopes) return SERVICE_ACCOUNT
def main(): exchange = connect() write_to_exchange(exchange, {"type": "hello", "team": team_name.upper()}) hello_from_exchange = read_from_exchange(exchange) # A common mistake people make is to call write_to_exchange() > 1 # time for every read_from_exchange() response. # Since many write messages generate marketdata, this will cause an # exponential explosion in pending messages. Please, don't do that! print("The exchange replied:", hello_from_exchange, file=sys.stderr) order_id = OrderID() BOND_book = Security('BOND') #create postion write_to_exchange(exchange, BOND_book.buyOrder(order_id.getOrderID(), 1000, 10)) write_to_exchange(exchange, BOND_book.sellOrder(order_id.getOrderID(), 1001, 10)) while True: message_from_exchange = read_from_exchange(exchange) if message_from_exchange['type'] == 'fill' and message_from_exchange[ 'symbol'] == 'BOND': print(message_from_exchange['size']) BOND_book.fill(message_from_exchange) if (BOND_book.buySize < 10) and (BOND_book.position < 10): write_to_exchange( exchange, BOND_book.buyOrder(order_id.getOrderID(), 1000, 10 - BOND_book.buySize)) print(BOND_book.OrderHist) if (BOND_book.sellSize < 10) and (BOND_book.position > -10): write_to_exchange( exchange, BOND_book.sellOrder(order_id.getOrderID(), 1001, 10 - BOND_book.sellSize)) print(BOND_book.buySize, BOND_book.sellSize)
#TODO - Move all this to a test file. #TODO - Read positions from file on start. #TODO - Write positions to file on start. from security import Security from stockExchange import StockExchange from portfolio import Position from portfolio import Portfolio from interactiveSession import InteractiveSession ftse = StockExchange("FTSE 100") securities = [ Security("IBM", "Equity", 105), Security("VOD", "Equity", 108), Security("UBI", "Equity", 120) ] ftse.addSecurities(securities) uiSession = InteractiveSession(ftse) uiSession.session()
def get_multiple_audience(auth=True): """ # Queries, calculates and returns the audience, or multiple audiences, received by POST request # Parameter auth: Signals if authentication checks ought to be performed """ authOk = True response = exception_response # Allow skipping authentication checks only if in debug mode if auth or not app.debug: sec = Security() authOk = sec.validate_access(request.authorization) else: print('\n Authentication checks skipped') if authOk: try: response = [] audiences = request.json.get('audience') print("\n *************************") for audience in audiences: obj = MeuDesconto() ret_audiencia = obj.calcular_audiencia_industria(audience) resp = make_response(jsonify(ret_audiencia), 200) new_resp = json.loads(resp.data) response.append(new_resp) response = make_response(json.dumps(response)) response.headers[ 'Content-Type'] = 'application/json; charset=utf-8' except L20notfound as el20: now = datetime.now() exception_response['Razao'] = el20.message traceback.print_exc() try: f = open("Logchamadas.log", "a") message_error = ("\n{0} - Erro: {1} - Parametros : {2}".format( now.strftime("%d/%m/%Y %H:%M:%S"), el20.message, str(audiences))) f.write(message_error) f.flush() f.close() except: pass ret = jsonify(exception_response) return make_response(ret, 200) except Exception as e: now = datetime.now() traceback.print_exc() try: f = open("Logchamadas.log", "a") f.write("\n{0} - Erro: {1} - Parametros : {2}".format( now.strftime("%d/%m/%Y %H:%M:%S"), str(e), str(audiences))) f.close() except: pass exception_response['Razao'] = str(e) return make_response(jsonify(exception_response), 400) else: print("\n UNAUTHORIZED ACCESS") raise ValueError return response
Created on Fri Jul 10 15:50:50 2015 simple portfolio from cash flow @author: xuyu """ import datetime import os from collections import defaultdict from security import Security from parse_flow import FlowRecord from tdx_parser.parse_tdx_day import get_dayline from dzh_parser import parse_dzh_div from dump_flow import load_flow import pandas as pd cash = Security('0', 'SZ') def generate_amount_line(flow_file): div_file = "E:\Stock\dzh365\Download\PWR/full.PWR" flow = load_flow(flow_file) div = parse_dzh_div(div_file) closeLines = dict() pf = PF() start_date, end_date = flow[0].date, flow[-1].date dates = pd.date_range(start_date, end_date, freq='B') #current = next(dates) line = list() i = 0 for day in dates:
class Receptionist: """ Receptionist class used to represent an reception py functionality of user registration and login. Objects: __db : Object created for UserDB class naming __db as protected object. __secure : Object created for the Security class naming __secure as protected object. __valid : Object created for the validation class naming __valid as protected object. Methods ------- register Lets a new user to register an account with valid user name, password, Proper name, email. login Lets the existing user login to the system using valid user id and password. """ __db = UserDB() __secure = Security() __valid = Validation() def register(self): """ This method takes in user information as username, password and asks to user to confirm the password if the user name exists already in the system it asks to choose another username. Then the password gets checked if its a valid one or not as well as the inserted password matching the confirmation password. If the password does not match the confirmation password it shows messege as password does not match. Further it prompts the user for first name, last name, email id and then user object gets created using User method of the UserDB class and get those all user inserted data as parameters. Using the methods of the UserDB class the database gets created, the overall data gets inserted as well in this method. """ while True: username = input("Insert your UserName Please: ") if self.__db.isExist( username ) is not True and self.__valid.userName_regex.match(username): username.lower() break print("Sorry the username is exist.") print("Please choose another username") while True: password = getpass.getpass("Insert your Password Please: ") confirmPassword = getpass.getpass("Confirm your Password : "******"password does not match") while True: firstname = str(input("Insert your First Name Please: ")) lastname = str(input("Insert your Last Name Please: ")) if self.__valid.name_regex.match( firstname) and self.__valid.name_regex.match(lastname): break print("You should enter letters only") while True: email = input("Insert Your Email Please: ") if self.__valid.email_regex.match(email): break print("you should enter a vaild email address") self.__db.insert(username, password, firstname, lastname, email) self.__db.displayDB() def login(self): """ This method asks user for user name and password and checks if the user name and password exists in the database if it finds the existing match it lets the user login the system. """ count = 0 while True: self.__db = UserDB() while True: userName = input("Insert Your UserName: "******"Insert Your Password: "******"You are not registered you should register by choose 1 from the menu" ) return False break count += 1 result = self.__db.get_Pass(userName) if count == 4: return False break else: if result is not None: result = result[0] plain_pass = self.__secure.decrypt(result, userName) if bytes.decode(plain_pass) == password: data = self.__db.getUserInformation(userName) return data break else: print("Username or password is wrong") else: print("It is wrong you can try again")
import logging from telegram import InlineKeyboardButton, InlineKeyboardMarkup, KeyboardButton, ReplyKeyboardMarkup from telegram.ext import Updater, CommandHandler, CallbackQueryHandler import time from config import CarRobot from security import Security import os logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s', level=logging.INFO) logger = logging.getLogger(__name__) # Configuracion Token BOT Telegram TOKEN = os.environ["BOT_TOKEN"] carRobot = CarRobot('Demo carrito', 0) sec = Security() def start(bot, update): keyboard = [[InlineKeyboardButton("Encender", callback_data='/encender')], [ InlineKeyboardButton("Acelerar", callback_data='/acelerar'), InlineKeyboardButton("Retroceder", callback_data='/retroceder') ], [ InlineKeyboardButton("Girar a la Derecha", callback_data='/derecha'), InlineKeyboardButton("Girar a la Izquierda", callback_data='/izquierda')