コード例 #1
0
def Main(msg):
    """
    获取微信消息,进行处理指令、关键词监听、撤回消息监听的动作
    :param msg: 微信消息
    :return: 无
    """
    # 三大功能之一:处理指令
    itchat.get_friends(update=True)
    if msg['ToUserName'] == "filehelper" and msg['Type'] == "Text":
        try:
            exec_command = Execution()
            exec_command.Execution(msg)
        except BaseException as e:
            mylog.WriteLog(e)

    # 三大功能之二:撤回消息部分
    try:
        rmsg = Revocation()
        rmsg.SaveMsg(msg)
        rmsg.Revocation(msg)
        rmsg.ClearTimeOutMsg()
    except BaseException as e:
        mylog.WriteLog(e)

    # 三大功能之三:关键词监听
    if msg['Type'] in ['Text', 'Sharing', 'Map', 'Card']:
        try:
            listener = KeywordListener()
            listener.Listener(msg)
        except BaseException as e:
            mylog.WriteLog(e)
コード例 #2
0
class ExecutionTestCase(unittest.TestCase):
    """
    Test methods in Execution
    """
    def __init__(self, *args, **kwargs):
        unittest.TestCase.__init__(self, *args, **kwargs)
        self.pkg_dir = os.path.join('..')
        self.execution = Execution(self.pkg_dir)
        self.img_size = 160

    def test_create_wh(self):
        """
        The warehouse should be a dictionary of UID keys and Person values
        :return: None
        """
        directory = os.path.join(self.pkg_dir, 'dataset', 'test')
        warehouse = self.execution.create_wh(directory)

        condition = len(warehouse.get_samples()) > 0
        self.assertEqual(condition, True)

    def test_acquire_data(self):
        """
        This function should create two warehouses and populate them with samples
        :return: None
        """
        self.execution.acquire_data()
        condition0 = len(
            self.execution.data_acquisition.trn_wh.get_samples()) > 0
        condition1 = len(
            self.execution.data_acquisition.tst_wh.get_samples()) > 0
        condition = condition0 and condition1
        self.assertEqual(condition, True)
コード例 #3
0
 def testTestDetailsWithExecution(self):
     t0 = Test(1, "Test 0", "1111")
     t0.description = "This is my test"
     t0.add_parameter("tparam0", "tvalue1")
     t0.add_parameter("tparam1", "tvalue2")
     t0.add_property("tprop0", "tvalue0")
     t0.add_property("tprop1", "tvalue1")
     
     
     
     t1 = Test(2, "Test 2", "2222")
     t1.set_status("error")
     t2 = Test(3, "Test 3", "3333")
     t2.set_status("failure")
     
     s0 = Scenario("Scenario 0")
     s0.add_scenario_property("foo0", "bar0")
     s0.add_scenario_property("foo1", "bar1")
     s0.add_child(t0)
     s0.add_child(t1)
     s0.add_child(t2)
     
     m0 = Machine("Itai's desktop") 
     m0.add_child(s0)
     
     e = Execution()
     e.add_machine(m0)
     print(json.dumps(e.dict()))
コード例 #4
0
 def Initialize(self):
     self.SetStartDate(2003, 1, 1)
     self.SetCash(100000)
     
     # Data resolution
     self.UniverseSettings.Resolution = Resolution.Minute
     
     # Universe selection model
     self.securities = []
     self.CustomUniverseSelectionModel = FactorUniverseSelectionModel(self)
     self.AddUniverse(self.CustomUniverseSelectionModel.SelectCoarse, self.CustomUniverseSelectionModel.SelectFine)
     
     # Alpha model
     self.CustomAlphaModel = ValueAlphaModel()
     
     # Portfolio construction model
     self.CustomPortfolioConstructionModel = OptimisationPortfolioConstructionModel()
     
     # Execution model
     self.CustomExecution = Execution()
     
     # Add SPY for trading days data
     self.AddEquity('SPY', Resolution.Daily)
     
     # Schedule rebalancing
     self.Schedule.On(self.DateRules.EveryDay('SPY'), self.TimeRules.At(13, 0), Action(self.RebalancePortfolio))
     
     # Init charting
     InitCharts(self)
     
     # Schedule charting
     self.Schedule.On(self.DateRules.Every(DayOfWeek.Friday), self.TimeRules.BeforeMarketClose('SPY', 0), Action(self.PlotCharts))
コード例 #5
0
ファイル: main.py プロジェクト: cutefish/PyUtils
def main():
    logging_config()
    cfg_file = sys.argv[1]
    code_dir = os.path.dirname(
        os.path.abspath(inspect.getfile(inspect.currentframe())))
    execution = Execution(code_dir)
    helper = ExecConfHelper()
    helper.build(execution, cfg_file)
    helper = ExecDnsHelper(execution)
    helper.setup_dns()
    execution.run()
コード例 #6
0
    def init_model(self):
        self.execution = Execution()
        machine = Machine(socket.gethostname())
        machine.planned_tests = self.general_conf.get_int("planned.tests")

        self.execution.add_machine(machine)
        self.uid = str(randint(1000, 9999) + time.time() / 1000).replace(
            ".", "")
        self.index = 0
        self.scenario_stack = []
        self.buffered_elements = []
        self.testDetails = None
コード例 #7
0
def create_list_Executions_object(list_metrics, flag):
    list_objects = []
    i = 0
    for each in list_metrics:
        x = Execution(i, each)
        list_objects.append(x)
        if(flag):
            x.show()
        i = i + 1


    return list_objects
コード例 #8
0
 def DBMSMainMenu(username):
     while (True):
         print('User in session: ' + username)
         logging.warning('User in session: ' + username)
         userInput = functions.display_DBMS_options()
         if (userInput == "1"):
             Execution.ExecutionMenu(username)
         elif (userInput == "2"):
             with open(db_log, 'r') as f:
                 for line in f:
                     print(line)
         elif (userInput == "3"):
             db_name = input("Enter a DB Name: ")
             with open(dd_path + db_name + '.json', 'r') as f:
                 for line in f:
                     print(line)
         elif (userInput == "4"):
             dbname = input("Enter a new Database Name: ")
             createDump(dbname)
         elif (userInput == "5"):
             dbname = input("Enter a new Database Name: ")
             generateERD(dbname)
         elif (userInput == "6"):
             isLoggedIn = user_class.User.logOut()
             break
         else:
             print("Please enter a valid option...")
         print("\n")
コード例 #9
0
ファイル: tool.py プロジェクト: MKlauck/qcomp2020
def get_result(benchmark: Benchmark, execution: Execution):
    """
    Returns the result of the given execution on the given benchmark.
    This method is called after executing the commands of the associated invocation.
    One can either find the result in the tooloutput (as done here) or
    read the result from a file that the tool has produced.
    The returned value should be either 'true', 'false', a decimal number, or a fraction.
    """
    invocation = execution.invocation
    log = execution.concatenate_logs()
    pos = log.find("+ Property {}".format(benchmark.get_property_name()))
    if pos < 0:
        return None
    pos = log.find("Probability: ", pos)
    if pos < 0:
        pos = log.find("Value: ")
        if pos < 0:
            pos = log.find("Result: ")
            if pos < 0:
                return None
            else:
                pos = pos + len("Result: ")
                eol_pos = log.find("\n", pos)
                return log[pos:eol_pos].lstrip()
        else:
            pos = pos + len("Value: ")
            eol_pos = log.find("\n", pos)
            return log[pos:eol_pos]
    else:
        pos = pos + len("Probability: ")
        eol_pos = log.find("\n", pos)
        return log[pos:eol_pos]
コード例 #10
0
ファイル: tool.py プロジェクト: MKlauck/qcomp2020
def get_result(benchmark: Benchmark, execution: Execution):
    """
    Returns the result of the given execution on the given benchmark.
    This method is called after executing the commands of the associated invocation.
    One can either find the result in the tooloutput (as done here) or
    read the result from a file that the tool has produced.
    The returned value should be either 'true', 'false', or a decimal number.
    """
    invocation = execution.invocation
    log = execution.concatenate_logs()

    if "PRISM-games" in log:
        # SMC
        pos = log.find("Result (maximum probability): ")
        if pos < 0:
            pos = log.find("Result (minimum probability): ")
            if pos < 0:
                return None
        pos = pos + len("Result (---imum probability): ")
        eol_pos = log.find("\n", pos)
        return log[pos:eol_pos]
    else:
        # PET
        pos = log.find("Output:\n")
        if pos < 0:
            return None
        pos = pos + len("Output:\n")
        eol_pos = log.find("\n", pos)
        if pos == eol_pos:
            return None
        return log[pos:eol_pos]
コード例 #11
0
def check_donaways_eod(date_i):
    while done_away_orders.has_order():
        o = done_away_orders.pop_order()
        day_return.add_transaction(o.qty, o.price)
        e = Execution(o.qty, o.symbol, o.price, date_i)
        executions.append(e)
        trades.add_execution(e)
コード例 #12
0
class TradingBot(QCAlgorithm):
    def Initialize(self):
        self.SetStartDate(2019, 1, 1)
        self.SetEndDate(2020, 1, 1)
        self.SetCash(100000)

        # Data resolution
        # By default, assets selected by universe selection are requested with minute resolution data.
        # https://www.quantconnect.com/docs/algorithm-reference/universes
        self.UniverseSettings.Resolution = Resolution.Minute
        self.UniverseSettings.Leverage = 1

        # Universe selection model
        self.securities = []
        self.CustomUniverseSelectionModel = FactorUniverseSelectionModel(self)
        self.AddUniverse(self.CustomUniverseSelectionModel.SelectCoarse,
                         self.CustomUniverseSelectionModel.SelectFine)

        # Alpha model
        self.CustomAlphaModel = ValueAlphaModel()

        # Portfolio construction model
        self.CustomPortfolioConstructionModel = OptimisationPortfolioConstructionModel(
            turnover=0.05, max_wt=0.05, longshort=True)

        # Execution model
        self.CustomExecution = Execution(liq_tol=0.005)

        # Add SPY for trading days data
        self.AddEquity('SPY', Resolution.Daily)

        # Schedule rebalancing
        self.Schedule.On(self.DateRules.EveryDay('SPY'),
                         self.TimeRules.At(13, 0),
                         Action(self.RebalancePortfolio))

        # Init charting
        InitCharts(self)

        # Schedule charting
        self.Schedule.On(self.DateRules.Every(DayOfWeek.Friday),
                         self.TimeRules.BeforeMarketClose('SPY', 0),
                         Action(self.PlotCharts))

    def OnData(self, data):
        pass

    def RebalancePortfolio(self):
        alpha_df = self.CustomAlphaModel.GenerateAlphaScores(
            self, self.securities)
        portfolio = self.CustomPortfolioConstructionModel.GenerateOptimalPortfolio(
            self, alpha_df)
        self.CustomExecution.ExecutePortfolio(self, portfolio)

    def PlotCharts(self):
        PlotPerformanceChart(self)
        PlotPosConcentrationChart(self)
        PlotStockCountChart(self)
        PlotExposureChart(self)
コード例 #13
0
class TradingBot(QCAlgorithm):
    def Initialize(self):
        self.SetStartDate(2020, 1, 1)
        self.SetEndDate(datetime.now() - timedelta(10))
        self.SetCash(100000)

        # *Data Resolution
        self.UniverseSettings.Resolution = Resolution.Minute

        # *Universe selection model; runs with the above data resolution
        # custom universe selection model class created -- from universe_selection -->UniverseSelectionModel()
        self.securities = []
        self.CustomUniverseSelectionModel = FactorUniverseSelectionModel(self)
        self.AddUniverse(self.CustomUniverseSelectionModel.SelectCoarse,
                         self.CustomUniverseSelectionModel.SelectFine)

        # *Alpha model; A
        self.CustomAlphaModel = ValueAlphaModel()

        # *Portfolio construction model; B
        self.CustomPortfolioConstructionModel = OptimisationPortfolioConstructionModel(
            turnover=0.05, max_wt=0.05, longshort=True)

        #Eexecution model; C
        self.CustomExecution = Execution(liq_tol=0.005)

        # *Add SPY for trading days data; a
        self.AddEquity('SPY', Resolution.Daily)

        # *Scheduling rebalancing; b ; we take the a daily resloution and at 2 oclock we execute a rebalance
        self.Schedule.On(self.DateRules.EveryDay('SPY'),
                         self.TimeRules.At(13, 0),
                         Action(self.RebalancePortfolio))

        # Init charting
        InitCharts(self)

        # Schedule charting
        self.Schedule.On(self.DateRules.Every(DayOfWeek.Friday),
                         self.TimeRules.BeforeMarketClose('SPY', 0),
                         Action(self.PlotCharts))

    def OnData(self, data):
        pass

    # this controls the A B C ; we chose when we rebalance; we generate our alpha scores ;we pass the alpha scores into our portfolio construction
    #next we execute orders based on our portfolio construction
    def RebalancePortfolio(self):
        alpha_df = self.CustomAlphaModel.GenerateAlphaScores(
            self, self.securities)
        portfolio = self.CustomPortfolioConstructionModel.GenerateOptimalPortfolio(
            self, alpha_df)
        self.CustomExecution.ExecutePortfolio(self, portfolio)

    def PlotCharts(self):
        PlotPerformanceChart(self)
        PlotPosConcentrationChart(self)
        PlotStockCountChart(self)
        PlotExposureChart(self)
コード例 #14
0
def build_workout_sample():
    workout1 = Workout()
    workout1.date = '2018-02-19'
    execution1 = Execution()
    execution1.exercise = build_exercise_sample()
    set1, set2, set3 = Set(), Set(), Set()
    set1.start_time = '2018-02-19T16:10:35Z'
    set1.repetitions = 10
    set1.weight = 40
    set2.start_time = '2018-02-19T16:12:35Z'
    set2.repetitions = 9
    set2.weight = 42
    set3.start_time = '2018-02-19T16:14:35Z'
    set3.repetitions = 8
    set3.weight = 42
    execution1.sets = [set1, set2, set3]
    workout1.executions = [execution1]
    return workout1
コード例 #15
0
    def Initialize(self):
        self.SetStartDate(2017, 1, 1)  # Set Start Date
        self.SetEndDate(2020, 5, 20)
        self.SetCash(100000)  # Set Strategy Cash

        # Weighting style - normalise or alpha_max (alpha maximisation w/ optimisation)
        self.weighting_style = 'normalise'

        # Market neutral
        self.mkt_neutral = True

        # Audio feature to use
        self.audio_feature = 'valence'

        # Get data
        self.data, self.etf_list, self.etf_country = self.DataSetup()

        # Add ETFs
        for etf in self.etf_list:
            self.AddEquity(etf, Resolution.Minute)

        # Portfolio construction model
        self.CustomPortfolioConstructionModel = OptimisationPortfolioConstructionModel(
            turnover=1,
            max_wt=0.2,
            longshort=True,
            mkt_neutral=self.mkt_neutral)

        # Execution model
        self.CustomExecution = Execution(liq_tol=0.005)

        # Schedule rebalancing
        self.Schedule.On(self.DateRules.Every(DayOfWeek.Wednesday),
                         self.TimeRules.BeforeMarketClose('IVV', 210),
                         Action(self.RebalancePortfolio))

        # Init charting
        InitCharts(self)

        # Schedule charting
        self.Schedule.On(self.DateRules.Every(DayOfWeek.Wednesday),
                         self.TimeRules.BeforeMarketClose('IVV', 5),
                         Action(self.PlotCharts))
コード例 #16
0
ファイル: algo.py プロジェクト: lamhochit/FutuAlgo
    def initialize(self,
                   initial_capital: float,
                   mq_ip: str,
                   hook_ip: str,
                   trading_environment: str,
                   trading_universe: list,
                   datatypes: list,
                   txn_cost: float = 30,
                   cache_rows: int = 3000,
                   test_mq_con=True,
                   hook_name: str = 'FUTU',
                   prefill_period='1Y',
                   **kwargs):
        assert trading_environment in (
            'BACKTEST', 'SIMULATE',
            'REAL'), f'Invalid trading environment {trading_environment}'
        assert initial_capital > 0, 'Initial Capital cannot be 0'
        assert cache_rows > 1, 'No of cached data must be > 0 rows'

        self._account = Account(logger=self._logger,
                                initial_capital=initial_capital,
                                txn_cost=txn_cost)
        self._data = Data(mq_ip=mq_ip,
                          logger=self._logger,
                          hook_ip=hook_ip,
                          trading_universe=trading_universe,
                          datatypes=datatypes,
                          cache_rows=cache_rows,
                          test_mq_con=test_mq_con,
                          hook_name=hook_name,
                          prefill_period=prefill_period,
                          add_pos_func=self._account.add_new_position)
        self._execution = Execution(account=self._account,
                                    data=self._data,
                                    trading_environment=trading_environment,
                                    logger=self._logger)
        self._webapp = AlgoApp(algo=self)

        self._initialized_date = datetime.datetime.today()
        self._running = False
        self._logger.debug('Initialized sucessfully.')
        self._initialized = True
コード例 #17
0
    def __init__(self,
                 challenger,
                 champion,
                 placementRule,
                 placementOption,
                 existRule,
                 existOption,
                 actionRule,
                 actionOption,
                 endingRule,
                 endingOption,
                 objectCount,
                 gameBoard,
                 dataBoard,
                 scriptPath=None,
                 problemIndex='scriptTemplate'):
        if type(challenger) is not UserProgram and type(
                champion) is not UserProgram:
            raise TypeError

        if scriptPath:
            sys.path.insert(0, scriptPath)
        exec 'from {0} import UserRule'.format(problemIndex)

        # parameter setting
        self.challenger = challenger
        self.champion = champion

        self.data = GameData(objectCount, placementRule, placementOption,
                             existRule, existOption, actionRule, actionOption,
                             endingRule, endingOption, gameBoard, dataBoard)

        self.limitTime = 2000

        self.positionData = ''
        self.boardData = ''

        # make rule and execution object
        self.rules = UserRule()
        self.execution = Execution()

        self.changePlayerNBoard(True, '  ')
コード例 #18
0
ファイル: tool.py プロジェクト: MKlauck/qcomp2020
def get_result(benchmark: Benchmark, execution: Execution):
    """
    Returns the result of the given execution on the given benchmark.
    This method is called after executing the commands of the associated invocation.
    One can either find the result in the tooloutput (as done here) or
    read the result from a file that the tool has produced.
    The returned value should be either 'true', 'false', a decimal number, or a fraction.
    """
    invocation = execution.invocation
    log = execution.concatenate_logs()
    return grep_for_result(benchmark, log)
コード例 #19
0
class TradingBot(QCAlgorithm):
    def Initialize(self):
        self.SetStartDate(2003, 1, 1)
        self.SetCash(100000)

        # Data resolution
        self.UniverseSettings.Resolution = Resolution.Minute

        # Universe selection model
        self.securities = []
        self.CustomUniverseSelectionModel = FactorUniverseSelectionModel(self)
        self.AddUniverse(self.CustomUniverseSelectionModel.SelectCoarse,
                         self.CustomUniverseSelectionModel.SelectFine)

        # Alpha model
        self.CustomAlphaModel = ValueAlphaModel()

        # Portfolio construction model
        self.CustomPortfolioConstructionModel = OptimisationPortfolioConstructionModel(
        )

        # Execution model
        self.CustomExecution = Execution()

        # Add SPY for trading days data
        self.AddEquity('SPY', Resolution.Daily)

        # Schedule rebalancing
        self.Schedule.On(self.DateRules.EveryDay('SPY'),
                         self.TimeRules.At(13, 0),
                         Action(self.RebalancePortfolio))

        # Init charting
        InitCharts(self)

        # Schedule charting
        self.Schedule.On(self.DateRules.Every(DayOfWeek.Friday),
                         self.TimeRules.BeforeMarketClose('SPY', 0),
                         Action(self.PlotCharts))

    def OnData(self, data):
        pass

    def RebalancePortfolio(self):
        alpha_df = self.CustomAlphaModel.GenerateAlphaScores(
            self, self.securities)
        portfolio = self.CustomPortfolioConstructionModel.GenerateOptimalPortfolio(
            self, alpha_df)
        self.CustomExecution.ExecutePortfolio(self, portfolio)

    def PlotCharts(self):
        PlotPerformanceChart(self)
        PlotPosConcentrationChart(self)
コード例 #20
0
    def Initialize(self):
        self.SetStartDate(2020, 1, 1)
        self.SetEndDate(datetime.now() - timedelta(10))
        self.SetCash(100000)

        # *Data Resolution
        self.UniverseSettings.Resolution = Resolution.Minute

        # *Universe selection model; runs with the above data resolution
        # custom universe selection model class created -- from universe_selection -->UniverseSelectionModel()
        self.securities = []
        self.CustomUniverseSelectionModel = FactorUniverseSelectionModel(self)
        self.AddUniverse(self.CustomUniverseSelectionModel.SelectCoarse,
                         self.CustomUniverseSelectionModel.SelectFine)

        # *Alpha model; A
        self.CustomAlphaModel = ValueAlphaModel()

        # *Portfolio construction model; B
        self.CustomPortfolioConstructionModel = OptimisationPortfolioConstructionModel(
            turnover=0.05, max_wt=0.05, longshort=True)

        #Eexecution model; C
        self.CustomExecution = Execution(liq_tol=0.005)

        # *Add SPY for trading days data; a
        self.AddEquity('SPY', Resolution.Daily)

        # *Scheduling rebalancing; b ; we take the a daily resloution and at 2 oclock we execute a rebalance
        self.Schedule.On(self.DateRules.EveryDay('SPY'),
                         self.TimeRules.At(13, 0),
                         Action(self.RebalancePortfolio))

        # Init charting
        InitCharts(self)

        # Schedule charting
        self.Schedule.On(self.DateRules.Every(DayOfWeek.Friday),
                         self.TimeRules.BeforeMarketClose('SPY', 0),
                         Action(self.PlotCharts))
コード例 #21
0
 def testSimpleModel(self):
     expected = {'machines': [{'status': 'success', 'type': 'machine', 'name': "Itai's desktop", 'children': [{'status': 'success', 'children': [{'status': 'success', 'index': 1, 'uid': '1111', 'parameters': {'tparam0': 'tvalue1', 'tparam1': 'tvalue2'}, 'timestamp': '', 'name': 'Test 0', 'className': '', 'duration': 0, 'type': 'test', 'properties': {'tprop1': 'tvalue1', 'tprop0': 'tvalue0'}, 'description': 'This is my test'}, {'status': 'error', 'index': 2, 'uid': '2222', 'parameters': {}, 'timestamp': '', 'name': 'Test 2', 'className': '', 'duration': 0, 'type': 'test', 'properties': {}, 'description': ''}, {'status': 'failure', 'index': 3, 'uid': '3333', 'parameters': {}, 'timestamp': '', 'name': 'Test 3', 'className': '', 'duration': 0, 'type': 'test', 'properties': {}, 'description': ''}], 'type': 'scenario', 'name': 'Scenario 0', 'scenarioProperties': {'foo0': 'bar0', 'foo1': 'bar1'}}]}]}
     t0 = Test(1, "Test 0", "1111")
     t0.description = "This is my test"
     t0.add_parameter("tparam0", "tvalue1")
     t0.add_parameter("tparam1", "tvalue2")
     t0.add_property("tprop0", "tvalue0")
     t0.add_property("tprop1", "tvalue1")
     t1 = Test(2, "Test 2", "2222")
     t1.set_status("error")
     t2 = Test(3, "Test 3", "3333")
     t2.set_status("failure")
     
     s0 = Scenario("Scenario 0")
     s0.add_scenario_property("foo0", "bar0")
     s0.add_scenario_property("foo1", "bar1")
     s0.add_child(t0)
     s0.add_child(t1)
     s0.add_child(t2)
     
     m0 = Machine("Itai's desktop") 
     m0.add_child(s0)
     
     e = Execution()
     e.add_machine(m0)
     print (e.dict())
     self.assertDictEqual(expected, e.dict())
コード例 #22
0
def start():
    global project, tracer, inspector
    try:
        project = Project.from_directory(find_project_directory(os.getcwd()))
        execution = Execution(project)
        inspector = Inspector(execution)
        tracer = Tracer(inspector)
        tracer.btracer.setup()
        sys.settrace(tracer.tracer)
    except PythoscopeDirectoryMissing:
        print "Can't find .pythoscope/ directory for this project. " \
            "Initialize the project with the '--init' option first. " \
            "Pythoscope tracing disabled for this run."
コード例 #23
0
ファイル: main.py プロジェクト: marcosvsilva/AlgoCenterPupil
    def run(self):
        number_of_process = int(os.cpu_count() / 2)

        print(self._path_out)
        print(os.listdir(self._path_out))

        exams_exists = ['{}.mp4'.format(x) for x in os.listdir(self._path_out)]
        if len(self._list_available) > 0:
            list_exams = [
                x for x in self._list_available
                if ('.mp4' in x) and (x not in exams_exists)
            ]
        else:
            list_exams = [
                x for x in os.listdir(self._path_dataset)
                if ('.mp4' in x) and (x not in exams_exists)
            ]

        list_exams = ['benchmark_final.avi']

        process = []
        while len(list_exams) > 0:
            end_list = number_of_process if len(
                list_exams) > number_of_process else len(list_exams)
            list_process = list_exams[0:end_list]
            list_exams = list_exams[end_list:len(list_exams)]

            for exam in list_process:
                title = exam.replace('.avi', '')

                paths = {
                    'path_exam':
                    '{}/{}'.format(self._path_dataset, exam),
                    'path_information':
                    '{}/{}.log'.format(self._path_information, title),
                    'path_out':
                    '{}/{}'.format(self._path_out, title),
                    'path_label':
                    '{}/{}_label.csv'.format(self._path_label, title)
                }

                self._make_path(paths['path_out'])

                execution = Execution()
                thread = Process(target=execution.pupil_process,
                                 args=(paths, ))
                process.append(thread)
                thread.start()

            for thread in process:
                thread.join()
コード例 #24
0
def check_fills(row):

    while done_away_orders.has_order():
        o = done_away_orders.pop_order()
        day_return.add_transaction(o.qty, o.price)
        e = Execution(o.qty, o.symbol, o.price, row.name)
        executions.append(e)
        trades.add_execution(e)

    orders = open_orders.get_open_orders(row['symbol'])
    if orders is not None:
        for o in orders[:]:
            if is_fill(o, row):
                record_fill(o, row)
                orders.remove(o)
コード例 #25
0
def record_fill(o, row):
    fill_price = 0.0
    if o.price == 0:
        fill_price = float(row['open'])
    else:
        if o.qty > 0:

            fill_price = min(o.price, row['open'])
        elif o.qty < 0:

            fill_price = max(o.price, row['open'])

    day_return.add_transaction(o.qty, fill_price)
    e = Execution(o.qty, o.symbol, fill_price, row.name)
    executions.append(e)
    trades.add_execution(e)
コード例 #26
0
ファイル: tool.py プロジェクト: MKlauck/qcomp2020
def get_result(benchmark: Benchmark, execution: Execution):
    """
	Returns the result of the given execution on the given benchmark.
	This method is called after executing the commands of the associated invocation.
	One can either find the result in the tooloutput (as done here) or
	read the result from a file that the tool has produced.
	The returned value should be either 'true', 'false', a decimal number, or a fraction.
	"""
    invocation = execution.invocation
    log = execution.concatenate_logs()
    RESULT_MARKER = "point estimate: "
    pos = log.find(RESULT_MARKER)
    if pos < 0:
        return None
    pos = pos + len(RESULT_MARKER)
    eol_pos = log.find(",", pos)
    return log[pos:eol_pos]
コード例 #27
0
ファイル: tool.py プロジェクト: MKlauck/qcomp2020
def get_result(benchmark: Benchmark, execution: Execution):
    """
    Returns the result of the given execution on the given benchmark.
    This method is called after executing the commands of the associated invocation.
    One can either find the result in the tooloutput (as done here) or
    read the result from a file that the tool has produced.
    The returned value should be either 'true', 'false', a decimal number, or a fraction.
    """
    invocation = execution.invocation
    log = execution.concatenate_logs()
    pos = log.find("command-check-result-is ")
    if pos < 0:
        return None
    pos += len("command-check-result-is ")
    eol_pos = log.find("\n", pos)
    space_pos = log.find(" ", pos)
    if (eol_pos < space_pos):
        return log[pos:eol_pos].rstrip()
    else:
        return log[pos:space_pos].rstrip()
コード例 #28
0
ファイル: tool.py プロジェクト: MKlauck/qcomp2020
def get_result(benchmark: Benchmark, execution: Execution):
    """
    Returns the result of the given execution on the given benchmark.
    This method is called after executing the commands of the associated invocation.
    One can either find the result in the tooloutput (as done here) or
    read the result from a file that the tool has produced.
    The returned value should be either 'true', 'false', a decimal number, or a fraction.
    """
    invocation = execution.invocation
    log = execution.concatenate_logs()
    if "Storm-dft" in log:
        pos = log.find("Result: [")
        if pos >= 0:
            pos = pos + len("Result: [")
            pos_e = log.find("]\n", pos)
            if pos_e >= 0:
                return log[pos:pos_e]

    pos1 = log.find("Model checking property \"{}\":".format(
        benchmark.get_property_name()))
    if pos1 < 0:
        return None
    for pre_result_str in [
            "Result (for initial states): ",
            "Result till abort (for initial states): "
    ]:
        pos2 = log.find(pre_result_str, pos1)
        if pos2 < 0: continue
        pos2 += len(pre_result_str)
        eol_pos = log.find("\n", pos2)
        result = log[pos2:eol_pos]
        pos_appr = result.find("(approx. ")
        if pos_appr >= 0:
            result = result[:pos_appr]
        return result
    return None
コード例 #29
0
def newInteration(lines, learnFactor, logger):
  execution = Execution(learnFactor, logger);

  linesTraining, linesTeste = execution.separateTrainingTestesLines(lines);


  execution.training(linesTraining);
  results = execution.testing(linesTeste);
  print(results);

  tableResults = Measures.getTableResults(results);
  
  accuracy = Measures.accuracy(tableResults)
  precision = Measures.precision(tableResults)
  recall = Measures.recall(tableResults)
  f1_score = Measures.f1_score(precision, recall)
  
  print('\naccuracy: ' + str(accuracy) + '% ' + 'precision: ' + str(precision) 
        + '% ' + 'recall: ' + str(recall) + '% ' + 'f1_score: ' + str(f1_score) + '%');
  
  return accuracy, precision, recall, f1_score;
コード例 #30
0
    # Trade GBP/USD
    instrument = "GBP_USD"

    # Create the OANDA market price streaming class
    # making sure to provide authentication commands
    prices = StreamingForexPrices(STREAM_DOMAIN, ACCESS_TOKEN, ACCOUNT_ID,
                                  instrument, events)

    # Create the strategy/signal generator, passing the
    # instrument and the events queue
    strategy = TestStrategy(instrument, events)

    # Create the portfolio object that will be used to
    # compare the OANDA positions with the local, to
    # ensure backtesting integrity.
    portfolio = Portfolio(prices, events, equity=100000.0)

    # Create the execution handler making sure to
    # provide authentication commands
    execution = Execution(API_DOMAIN, ACCESS_TOKEN, ACCOUNT_ID)

    # Create two separate threads: One for the trading loop
    # and another for the market price streaming class
    trade_thread = threading.Thread(target=trade,
                                    args=(events, strategy, portfolio,
                                          execution))
    price_thread = threading.Thread(target=prices.stream_to_queue, args=[])

    # Start both threads
    trade_thread.start()
    price_thread.start()
コード例 #31
0
ファイル: invocation.py プロジェクト: MKlauck/qcomp2020
 def execute(self):
     execution = Execution(self)
     execution.run()
     return execution
コード例 #32
0
    RESTaccess.socketIO = SocketIO(RESTaccess.TRADING_API_URL, RESTaccess.WEBSOCKET_PORT, params={'access_token': RESTaccess.ACCESS_TOKEN})
    RESTaccess.socketIO.on('connect', RESTaccess.on_connect)
    RESTaccess.socketIO.on('disconnect', RESTaccess.on_close)
    RESTaccess.bearer_access_token = RESTaccess.create_bearer_token(RESTaccess.ACCESS_TOKEN, RESTaccess.socketIO._engineIO_session.id)
    # Create the FXCM market price streaming class
    # making sure to provide authentication commands
    prices = StreamingForexPrices(RESTaccess, instrument, events)

    # Create the portfolio object that will be used to
    # compare the OANDA positions with the local, to
    # ensure backtesting integrity.
    portfolio = Portfolio(prices, events, backtest = False, equity=1000000.0)

    # Create the execution handler making sure to
    # provide authentication commands
    execution = Execution(RESTaccess)

    # Create the strategy/signal generator, passing the
    # instrument, quantity of units and the events queue
    #strategy = TestRandomStrategy(instrument, events)
    strategy = MovingAverageCrossStrategy(instrument,events)
    #strategy = NewsDrivenStrategy(instrument,events)

    # Create two separate threads: One for the trading loop
    # and another for the market price streaming class
    trade_thread = threading.Thread(target=trade, args=(events, strategy, portfolio, execution, heartbeat))
    price_thread = threading.Thread(target=prices.stream_to_queue, args=[])
    # Start both threads
    logger.info("Starting trading thread")
    trade_thread.start()
    logger.info("Starting price streaming thread")
コード例 #33
0
ファイル: timey.py プロジェクト: DarthLorenzo/TimeyWimey
from tokenize import tokenize
from execution import Execution
import errors
import sys

infile = open('test.tw')

print("Reading File...")

root = Execution(None)

try:
	lines = tokenize(infile, root)
except errors.ParsingException as e:
	print("Error parsing line %d:\n>>> %s\n%s" % (e.lnum, e.line.strip(), str(e)))
	sys.exit(1)

print("Executing Timestream...")
root.run()
コード例 #34
0
ファイル: fullTrade.py プロジェクト: mattlerner/forex
				longQueue = strategy.doQueue(longQueue,strategySettings["longQueuePeriod"],row)	# add current price to queue, along with stats

			#CHECK OPEN POSITIONS
			tradeOpen = strategy.checkOpen(connection.positions())
			print "tradeOpen: ", tradeOpen

			# 2.A: STRATEGY:
			signal = strategy.maCrossAnticipate(row, priceQueue, longQueue, backtestSettings, tradeOpen)	# check for buy/sell signals

			print signal["signal"]
			print connection.orders()

			if signal["signal"] and not tradeOpen and not connection.orders():
				#event = tradeEvent("EUR_USD", 100000, signal["signal"], signal["stopLoss"], signal["takeProfit"])
				threeMinutes = dt.utcnow() + datetime.timedelta(minutes=3)
				event = tradeEventLimit("EUR_USD", 100000, signal["signal"], signal["stopLoss"], signal["takeProfit"],signal["tradePrice"],threeMinutes.isoformat("T"),signal["upperBound"],signal["lowerBound"])
				try:
					# PREPARE TRADE EXECUTION
					execution = Execution(API_DOMAIN, ACCESS_TOKEN, ACCOUNT_ID)
					execute = execution.execute_order(event)
					print execute
				except Exception, e:
					print "there was an error!\n"
					print repr(e)
					print str(e)
			else:
				pass

			time.sleep(60)

		#print " *** LIVE TRADING ***"					# live trading