def test_configuration_file(): config = Config() config_obj = config.get_config() assert type(config_obj) is dict assert type(config_obj['bridge']['ip']) is str assert type(config_obj['bridge']['user']) is str assert type(config_obj['lights']) is list
def get_config(self): """ Get the config JSON :return: tuple(response in bytes, content type string) """ config = Config.get_config() json_bytes = json.dumps(config).encode("utf-8") return json_bytes, "application/json", None, None
def __init__(self, filename): if not hasattr(self, "config"): self.config = {} self.config = EasyDict(self.config) module_name = Path(filename).name.strip(".py") self.config.update(Config.get_config(name=module_name)) self.config = EasyDict(self.config) logging.info("\n\tModule: {} \n\tConfig: {}".format( module_name, self.config))
class Sync: def __init__(self, verbose, fullscreen, transition, interval, ignore_white, ignore_black): self.config = Config() # Get config from config.yaml self.config_obj = self.config.get_config() self.ip = self.config_obj['bridge']['ip'] self.user = self.config_obj['bridge']['user'] self.lights_list = self.config_obj['lights'] # Use CLI args self.verbose = verbose self.fullscreen = fullscreen self.transition = transition self.interval = interval self.ignore_white = ignore_white self.ignore_black = ignore_black # Instantiate qHue Bridge self.bridge = Bridge(self.ip, self.user) def sync(self): try: # Instantiate DominantColor dc = DominantColor(self.fullscreen, self.ignore_white, self.ignore_black) # Get the dominant color on the primary display rgb_color = dc.get_dominant_color() # Instantiate the rgb to xy color Converter class color_converter = Converter(GamutC) # Convert the dominant color from rgb to xy xy_color = color_converter.rgb_to_xy(rgb_color[0], rgb_color[1], rgb_color[2]) # Be verbose about what we're doing if self.verbose is True: print(f'RGB{rgb_color} -- XY{xy_color}') print( f'Fullscreen: {self.fullscreen}\nInterval: {self.interval}\nTransition: {self.transition}\n' f'Ignore White Pixels: {self.ignore_white}\nIgnore Black Pixels: {self.ignore_black}\n' ) # Change the color of the light(s) for light in self.lights_list: self.bridge.lights[light].state(xy=[xy_color[0], xy_color[1]], transitiontime=int( self.transition * 0.001)) except TypeError: # Not enough non-black or non-white pixels to update pass
def main(args): Config.load_config(filename=args.config) config = Config.get_config() if args.debug: logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') updater = Updater(token=config.token) dispatcher = updater.dispatcher for name in config.command: module = importlib.import_module('{}.{}'.format("command", name)) cls = getattr(module, get_package_class(name)) cls().active(dispatcher) for ith, name in enumerate(["command_unknown"] + config.message_filter): module = importlib.import_module('{}.{}'.format("message", name)) cls = getattr(module, get_package_class(name)) cls().active(dispatcher, ith) logging.info("Running... Press `Ctrl+C` to stop") updater.start_polling() updater.idle() logging.info("Stoped")
class StrategyEngine(object): DEFAULT_STRATEGY = 'macd_strategy' DEFAULT_BAR_PERIOD = 30 def __init__(self): self.__mq_server = None self.__data_db = DB(Constants.HIST_DATA_DB_NAME) self.__config = Config() self.__tick_db = FileDB(self.__config.get_config('persistent', 'hist_tick_dir')) self.__trading_strategy = None self.__tick_collector = None def start(self): Util.set_token() self.__mq_server = MqServer() self.__mq_server.set_callback(self.__process) self.__mq_server.start() def __process(self, msg, server): content = json.loads(msg) if not content: _logger.warn("request msg(%r) is illegal." % msg) return stock_code = content.get('stock', None) if not stock_code: _logger.warn("stock code(%r) is invalid." % stock_code) return start = content.get('start', None) end = content.get('end', None) if not start or not end: _logger.warn("start date(%r) or end date(%r) is null." % (start, end)) return strategy = content.get('strategy', self.DEFAULT_STRATEGY) buy_percent = content.get('buy_ratio', 0.5) sell_percent = content.get('sell_ratio', 1) context = Context() history_data = self.__get_data(stock_code, start, end) context.set_history_data(stock_code, history_data) self.__tick_collector = HistTickCollector(stock_code, self.__tick_db) self.__trading_strategy = StrategyFactory.create_strategy(strategy, self.__price_generator) deal_strategy = DealStrategy() sugestions = self.__trading_strategy.decide(context, stock_code, start) _logger.info(sugestions) deals = deal_strategy.deal(context, stock_code, sugestions) _logger.info(deals) server.send(json.dumps(deals)) def __get_data(self, stock_code, start, end): collection = Collection(stock_code, self.__data_db) start_date = datetime.strptime(start, '%Y-%m-%d') end_date = datetime.strptime(end, '%Y-%m-%d') result = {} for record in collection.find().sort('date', pymongo.ASCENDING): record_date = datetime.strptime(record['date'], '%Y-%m-%d') if record_date >= (start_date - timedelta(days=self.DEFAULT_BAR_PERIOD)) and record_date <= end_date : result[record['date']] = record if record_date > end_date: break return OrderedDict(sorted(result.items(), key= lambda t: t[0])) def __price_generator(self, date): return self.__tick_collector.get_middle_price(date) def stop(self): self.__mq_server.stop()
class StrategyEngine(object): DEFAULT_STRATEGY = 'macd_strategy' DEFAULT_BAR_PERIOD = 30 def __init__(self): self.__mq_server = None self.__data_db = DB(Constants.HIST_DATA_DB_NAME) self.__config = Config() self.__tick_db = FileDB( self.__config.get_config('persistent', 'hist_tick_dir')) self.__trading_strategy = None self.__tick_collector = None def start(self): Util.set_token() self.__mq_server = MqServer() self.__mq_server.set_callback(self.__process) self.__mq_server.start() def __process(self, msg, server): content = json.loads(msg) if not content: _logger.warn("request msg(%r) is illegal." % msg) return stock_code = content.get('stock', None) if not stock_code: _logger.warn("stock code(%r) is invalid." % stock_code) return start = content.get('start', None) end = content.get('end', None) if not start or not end: _logger.warn("start date(%r) or end date(%r) is null." % (start, end)) return strategy = content.get('strategy', self.DEFAULT_STRATEGY) buy_percent = content.get('buy_ratio', 0.5) sell_percent = content.get('sell_ratio', 1) context = Context() history_data = self.__get_data(stock_code, start, end) context.set_history_data(stock_code, history_data) self.__tick_collector = HistTickCollector(stock_code, self.__tick_db) self.__trading_strategy = StrategyFactory.create_strategy( strategy, self.__price_generator) deal_strategy = DealStrategy() sugestions = self.__trading_strategy.decide(context, stock_code, start) _logger.info(sugestions) deals = deal_strategy.deal(context, stock_code, sugestions) _logger.info(deals) server.send(json.dumps(deals)) def __get_data(self, stock_code, start, end): collection = Collection(stock_code, self.__data_db) start_date = datetime.strptime(start, '%Y-%m-%d') end_date = datetime.strptime(end, '%Y-%m-%d') result = {} for record in collection.find().sort('date', pymongo.ASCENDING): record_date = datetime.strptime(record['date'], '%Y-%m-%d') if record_date >= (start_date - timedelta( days=self.DEFAULT_BAR_PERIOD)) and record_date <= end_date: result[record['date']] = record if record_date > end_date: break return OrderedDict(sorted(result.items(), key=lambda t: t[0])) def __price_generator(self, date): return self.__tick_collector.get_middle_price(date) def stop(self): self.__mq_server.stop()