def __init__(self, instr): self.log = logging.getLogger('GDAIS.InstrumentConfig') if type(instr) is str: self.instrument = Instrument(instr) self.init_commands = [] self._operation_mode = self.DEFAULT_OPERATION_MODE self.operation_commands = [] elif type(instr) is dict: self.instrument = Instrument(instr['filename']) self.init_commands = [] if 'init_commands' in instr: for c in instr['init_commands']: self.add_init_command(c) self._operation_mode = instr['operation_mode'] self.operation_commands = [] if 'operation_commands' in instr: for c in instr['operation_commands']: self.add_operation_command(c) else: self.log.error( "Unknown parameter type, can't initialize InstrumentConfig")
def setup(self): self.sax = Instrument("Saxophone") self.guitar = Instrument("Guitar") self.drums = Instrument("Drums") self.m1 = Musician("Evan Parker", self.sax ) self.m2 = Musician("Derek Bailey", self.guitar ) self.m3 = Musician("Han Bennink", self.drums ) self.lungs_band = Band("Lungs Band", [self.m1, self.m2, self.m3])
def main(): pubsub = r.pubsub(ignore_subscribe_messages=True) pubsub.subscribe(['counter', 'commands', 'settings']) instrument = Instrument() for m in pubsub.listen(): if m['channel'] == b'counter': counts = json.loads(m['data'])['counts'] data = instrument.update() # data = fake_data data['counts'] = counts data['concentration'] = int( counts / (data['sample_flow'] * 1000 / 60)) # particles/cm3 print(data) try: services.publish_to_websockets(data) # services.save_to_database(data) # r.publish('aws_iot', json.dumps(data)) except: print('No data published or saved.') elif m['channel'] == b'commands': command = json.loads(m['data'])['command'] if command == 'on': instrument.start() elif command == 'off': instrument.stop() elif m['channel'] == b'settings': if json.loads(m['data'])['update'] == 'on': instrument.reload()
def get_trade(cls, trade_id): """Returns: <Trade> or None Get info about a particular trade. """ trade_info = cls.fetch('{}/v3/accounts/{}/trades/{}'.format( Config.oanda_url, str(Config.account_id), str(trade_id))) try: trade = trade_info['trade'] sl = None tp = None if 'stopLossOrder' in trade: sl = trade['stopLossOrder']['price'] if 'takeProfitOrder' in trade: tp = trade['takeProfitOrder']['price'] return Trade(units=trade['initialUnits'], broker_name=cls.__str__(), instrument=Instrument( Instrument.get_id_from_name(trade['instrument'])), stop_loss=sl, take_profit=tp, strategy=None, trade_id=trade['id']) except Exception: # Oanda returns 404 error if trade closed; don't raise Exception. Log.write('oanda.py get_trade(): Exception:\n{}'.format( sys.exc_info())) Log.write( '"oanda.py" get_trade(): Failed to get trade info for trade with ID ', trade_id, '.') return None
def test_get_time_since_close(self): """ These should be true of the time since close: - less than one week ago - before now - if market open now, > 2 days ago - if market closed now, less than 2 days ago """ now = datetime.datetime.utcnow() zero_delta = datetime.timedelta() time_since_close = Oanda.get_time_since_close() # timedelta print('***********************************************\\') print('time since last close: {}'.format(time_since_close)) print('***********************************************/') # check < 1 week self.assertTrue(now - (now - time_since_close) < datetime.timedelta(days=7)) # Check before now self.assertTrue((now - time_since_close) < now) # Check weekend (2 days) market_open = Oanda.is_market_open(Instrument(4)) # USD/JPY market if market_open: self.assertTrue(time_since_close > datetime.timedelta(days=2)) else: self.assertTrue(time_since_close < datetime.timedelta(days=2))
def run(self, accelerator_power, speedup): for name, use_fraction, rate, count in self.configs: for phase_id, phase in enumerate(self.phases): assert phase <= self.phases[-1] # phases must be ordered, highest pixel count last for power in accelerator_power: reduced_rate = rate*power/5.0*phase/self.phases[-1] run_duration = count/reduced_rate # Typically we have to process a sample run together with a background run. # For now we assume that both have similar size, i.e., the effective number of # events in the reduction is twice that of the run: sample_and_background = 1 + 1 i = Instrument(phase, sample_and_background*reduced_rate, run_duration) output = '{:4.1f} MW {:6} {:7} pixels {:.3f} {:30} {:6.0} n/s {:6.0f} run[s]'.format(power, self.name, phase, use_fraction, name, reduced_rate.value, run_duration.value) reduction_duration = min(max(run_duration/speedup, 30 * u.second), 1200 * u.second) resources = i.required_resources(reduction_duration) # TODO take into account that not 100% of time is measurement time? cores = resources['cores'] actual_duration = resources['actual_duration'] try: # Average cores takes into account reducing data several times. reductions_per_run = 2 average_cores = ceil(use_fraction*reductions_per_run*(actual_duration/run_duration)*cores) output += ' {:6.0f} reduction[s] {:3} cores {:4.0f} average-cores'.format(actual_duration.value, cores, average_cores) output += ' {:4.0f} GByte/core'.format(ceil(memory_requirement(phase, reduced_rate*run_duration, cores).value/2**30/cores)) except: output += ' {:6} reduction[s] {:3} cores {:4} average-cores'.format(' inf', 'inf', ' inf') print(output)
def get_open_trades(cls): """Return type: Instance of <Trades> or None Get info about all open trades """ #Log.write('"oanda.py" get_open_trades(): Entering.') trades_oanda = cls.fetch('{}/v3/accounts/{}/openTrades'.format( Config.oanda_url, str(Config.account_id))) if trades_oanda == None: Log.write( '"oanda.py" get_open_trades(): Failed to get trades from Oanda.' ) return None else: ts = Trades() for t in trades_oanda['trades']: # format into a <Trade> ts.append( Trade(units=t['initialUnits'], broker_name=cls.__str__(), instrument=Instrument( Instrument.get_id_from_name(t['instrument'])), stop_loss=t['stopLossOrder']['price'], strategy=None, take_profit=t['takeProfitOrder']['price'], trade_id=t['id'])) return ts
def script_reduction(self, accelerator_power=2.0): cores = 0 cpu_time_per_real_time = 0 * u.dimensionless_unscaled bandwidth = 0 * u.byte / u.second memory_per_core = [] instrument_resources = {} for name, params in self.instruments.items(): final_accelerator_power = 2.0 accelerator_power_fraction = accelerator_power / final_accelerator_power adjusted_event_rate = params.event_rate * min( 1, params.max_rate_compensation * accelerator_power_fraction) # TODO pixel buildout phases (include coverage and run duration adjustment!) instrument = Instrument(params.num_pixel, adjusted_event_rate, params.run_duration) resources = instrument.required_resources(params.run_duration / self.reduction_speedup) instrument_resources[name] = resources cores += resources[ 'cores'] # is the sum useful? number of cores for running in parallel a single reduction per instrument? cpu_time_per_real_time += self.reductions_per_run * resources[ 'cpu_time'] / params.run_duration bandwidth += self.reductions_per_run * resources[ 'size_on_disk'] / params.run_duration memory_per_core.append(resources['memory_per_core'].value) print('{:9} {:9.0f} {:8.0f} {:7.1f} {:7.1f}'.format( cores, cpu_time_per_real_time, bandwidth.value / 1e6, np.mean(memory_per_core) / 1e9, np.max(memory_per_core) / 1e9)) return instrument_resources
def test_init(self): name = "Myname" base = 10 drift = 3 variance = 2 testobject = Instrument(name, base, drift, variance) assert testobject.name == name
def __init__(self): self.wk_dir = os.path.dirname(os.path.realpath('__file__')) self.instrument = Instrument(self) self.test_start = None self.utils = None self.result_table = [] self.menu()
def main(): desc = "Add noise to a radiance spectrum or image" parser = argparse.ArgumentParser(description=desc) parser.add_argument('config', type=str, metavar='INPUT') args = parser.parse_args(sys.argv[1:]) config = json_load_ascii(args.config, shell_replace=True) configdir, configfile = split(abspath(args.config)) infile = expand_path(configdir, config['input_radiance_file']) outfile = expand_path(configdir, config['output_radiance_file']) instrument = Instrument(config['instrument_model']) geom = Geometry() if infile.endswith('txt'): rdn, wl = spectrumLoad(infile) Sy = instrument.Sy(rdn, geom) rdn_noise = rdn + multivariate_normal(zeros(rdn.shape), Sy) with open(outfile, 'w') as fout: for w, r in zip(wl, rdn_noise): fout.write('%8.5f %8.5f' % (w, r)) else: raise ValueError('image cubes not yet implemented')
def test_instrument(): pretty_print("TESTING INSTRUMENT") amazon_stock = Instrument(Instrument.Type.STOCK, "AMZN") print("Amazon stock " + str(amazon_stock)) print("Amazon stock symbol: " + str(amazon_stock.symbol())) print("Quote for Amazon stock: " + str(amazon_stock.quote())) print("Ask price x size: " + str(amazon_stock.ask_info())) print("Bid price x size: " + str(amazon_stock.bid_info())) print("Fundamental: " + str(amazon_stock.fundamental())) print("Historical data for Amazon: " + str(amazon_stock.historical_quotes("5minute", "week"))) print("News: " + str(amazon_stock.news())) print("Option chain ID: " + str(amazon_stock.option_chain_id())) print("Market data for Amazon: " + str(amazon_stock.market_data())) print( "Popularity of Amazon stock as measured by number of Robinhood users who own it: " + str(amazon_stock.popularity())) print("Last trade price of Amazon stock: " + str(amazon_stock.last_trade_price())) print("Price for Amazon stock last updated at: " + str(amazon_stock.last_updated_at())) print("Previous closing price for Amazon stock, not adjusted: " + str(amazon_stock.previous_close())) print("Previous closing price for Amazon stock, adjusted: " + str(amazon_stock.previous_close(adjusted=True)))
def decode_instrument(data, name): flags, finetune, fixed_note = struct.unpack("<hBB", data[0:4]) voice1 = decode_voice(data[4:20], name) offset1 = voice1["note_offset"] # Second voice? if (flags & FLAG_TWO_VOICE) != 0: voice2 = decode_voice(data[20:], name) offset2 = voice2["note_offset"] else: voice2 = None offset2 = 0 # Null out fixed_note if the fixed pitch flag isn't set: if (flags & FLAG_FIXED_PITCH) == 0: fixed_note = None return Instrument(voice1, voice2, off1=offset1, off2=offset2, note=fixed_note)
def test_market_sell_order(): pretty_print('TESTING MARKET SELL ORDER') zom = Instrument(Instrument.Type.STOCK, 'ZOM') zom_order = Order(zom, Order.Type.MARKET_SELL_ORDER, quantity=1, time_in_force=Order.TimeInForce.GFD) print(zom_order.place())
def test_market_buy_order(): pretty_print('TESTING MARKET BUY ORDER') zom = Instrument(Instrument.Type.STOCK, 'ZOM') zom_order = Order(zom, Order.Type.MARKET_BUY_ORDER, quantity=2, time_in_force=Order.TimeInForce.GTC) print(zom_order.place())
def __init__(self, parent = None): """ Constructor """ QMainWindow.__init__(self, parent) self.setupUi(self) # TODO: temporally load always an instrument self.load_instrument(Instrument(self.INSTRUMENT_PATH + "/gps.json"))
def build_instruments(self): """Reads the indices of instruments used and fills the instruments_sprites with sprites""" all_instruments = self.read_instrumentslist() for i in range(len(self.instruments_used)): self.instruments_sprites.append( Instrument(self.instruments_used[i], i, all_instruments[self.instruments_used[i]]))
def load(self): self.instruments.clear() with open(self._path, "r") as file_in: for line in file_in: name, family, difficulty = line.strip().split(self._delimiter) instrument = Instrument(name, family) instrument.difficulty = difficulty self.instruments.append(instrument)
def on_action_Open_triggered(self): filename = QFileDialog.getOpenFileName( None, self.trUtf8("Select an instrument description file"), QString(self.INSTRUMENT_PATH), self.trUtf8(self.FILEDIALOG_FILTER), None) if filename: self.load_instrument(Instrument(str(filename)))
def test_limit_sell_order(): pretty_print('TESTING LIMIT SELL ORDER') zom = Instrument(Instrument.Type.STOCK, 'ZOM') zom_order = Order(zom, Order.Type.LIMIT_SELL_ORDER, quantity=1, time_in_force=Order.TimeInForce.GTC, price=0.275) print(zom_order.place())
def add_instrument(): content = request.form new_instrument = Instrument(content) instrument_id = create_id() instruments_db[instrument_id] = new_instrument response = {"instrumentId": instrument_id} return app.response_class(response=json.dumps(response), status=200, mimetype='application/json')
def test_stop_loss_sell_order(): pretty_print('TESTING STOP LOSS SELL ORDER') zom = Instrument(Instrument.Type.STOCK, 'ZOM') zom_order = Order(zom, Order.Type.STOP_LOSS_SELL_ORDER, quantity=2, time_in_force=Order.TimeInForce.GTC, stop_price=0.200) print(zom_order.place())
def test_limit_buy_order(): pretty_print('TESTING LIMIT BUY ORDER') zom = Instrument(Instrument.Type.STOCK, 'ZOM') zom_order = Order(zom, Order.Type.LIMIT_BUY_ORDER, quantity=2, time_in_force=Order.TimeInForce.GTC, price=0.25) print(zom_order.place())
def add_instrument(self, programno): all_instruments = self.read_instrumentslist() programname = all_instruments[programno] # print("Read from all_instruments", programname) self.instruments_used.append(programno) self.instruments_sprites.append( Instrument(programno, len(self.instruments_used) - 1, programname))
def decode_referential(self, encoded_referential): referential = Referential() tokens = list(filter(None, encoded_referential.split(self.separator))) for x in range(0, len(tokens), 4): referential.add_instrument(Instrument(identifier=int(tokens[x]), name=tokens[x + 1], isin=tokens[x + 2], currency_identifier=int(tokens[x + 3]))) return referential
def instrument(prog_name: str): pass preFileName = prog_name + '.ii' sourceFileName = prog_name + '.cu' inst = Instrument(preFileName, sourceFileName) inst.deprocess() inst.findDeviceDeclarations() inst.findAssigments() inst.produceInstrumentedLines() inst.instrument()
def test_get_time_until_close(self): zero_delta = datetime.timedelta() result = Oanda.get_time_until_close() # timedelta api_open = Oanda.is_market_open(Instrument(4)) if api_open: self.assertTrue(result != zero_delta) else: self.assertTrue(result == zero_delta) print('*****************************************\\') print('time until market close: {}'.format(result)) print('*****************************************/')
def instruments(self): if not self._instruments: self._instruments = [ Instrument(sample, song=weakref.ref(self)) if sample else None for sample in self.samples ] for n, pattern in enumerate(self.arranged_patterns()): for pos, note in pattern.enumerate_notes(n): if note.sample and self.samples[note.sample]: self._instruments[note.sample].add_note(note, pos) return self._instruments
def get_instruments(data): item = {} instruments = [] for row in range(2, data.max_row): for col in range(1, data.max_column): key = data.cell(1, col).value value = data.cell(row, col).value result = {key: value} item.update(result) instruments.append(Instrument(item)) return instruments
def decode_referential(self, encoded_referential): referential = Referential() referential_message = referential_pb2.Referential() referential_message.ParseFromString(encoded_referential) for decoded_instrument in referential_message.instruments: instrument = Instrument(identifier=decoded_instrument.identifier, name=decoded_instrument.name, isin=decoded_instrument.isin, currency_identifier=decoded_instrument.currency_identifier) referential.add_instrument(instrument) return referential