• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python Logger.Logger类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pyswing.utils.Logger.Logger的典型用法代码示例。如果您正苦于以下问题:Python Logger类的具体用法?Python Logger怎么用?Python Logger使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Logger类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: analyseRule

    def analyseRule(self):
        """
        ?
        """

        Logger.log(logging.INFO, "Analysing Rule", {"scope":__name__, "Rule":self._ruleTableName})

        equityCount = self._getEquityCount()
        potentialRuleMatches = self._getPotentialRuleMatches()

        connection = sqlite3.connect(pyswing.database.pySwingDatabase)

        cursor = connection.cursor()

        try:
            query = "select count(1) from '%s' where Match = 1;" % self._ruleTableName
            cursor.execute(query)
            actualRuleMatches = int(cursor.fetchone()[0])

            query = "delete from Rules where Rule = '%s'" % self._ruleTableName
            cursor.execute(query)

            # Unit Testing is easier if the value is stored...
            self._matchesPerDay = actualRuleMatches / potentialRuleMatches * equityCount
            query = "insert into Rules values('%s',%s)" % (self._ruleTableName, self._matchesPerDay)
            cursor.execute(query)

        except sqlite3.OperationalError:
            Logger.log(logging.INFO, "Error Analysing Rule", {"scope":__name__, "Rule":self._ruleTableName})

        connection.commit()

        connection.close()
开发者ID:garyjoy,项目名称:pyswing,代码行数:33,代码来源:rule.py


示例2: getActiveStrategies

def getActiveStrategies():

    connection = sqlite3.connect(pyswing.database.pySwingDatabase)

    query = "select rule1, rule2, exit, type, rule3, meanResultPerTrade, medianResultPerTrade, totalProfit, numberOfTrades, sharpeRatio, maximumDrawdown from ActiveStrategy where active = 1"

    strategies = None

    cursor = connection.cursor()
    try:
        cursor.execute(query)
        strategies = cursor.fetchall()
    except sqlite3.OperationalError:
        Logger.log(logging.INFO, "Error Getting Strategies", {"scope":__name__})

    connection.close()

    strategiesList = []
    for strategyRow in strategies:

        strategy = Strategy(strategyRow[0], strategyRow[1], strategyRow[2], strategyRow[3], strategyRow[4])
        strategiesList.append(strategy)

        strategy.meanResultPerTrade = strategyRow[5]
        strategy.medianResultPerTrade = strategyRow[6]
        strategy.totalProfit = strategyRow[7]
        strategy.numberOfTrades = strategyRow[8]
        strategy.sharpeRatio = strategyRow[9]
        strategy.maximumDrawdown = strategyRow[10]

    return strategiesList
开发者ID:garyjoy,项目名称:pyswing,代码行数:31,代码来源:strategy.py


示例3: askHorse

    def askHorse(self, latestDate):

        self.tradeDetails = []

        connection = sqlite3.connect(pyswing.database.pySwingDatabase)

        query = ("select r1.Code, r1.Date "
            "from '%s' r1 "
            " inner join '%s' r2 on r2.Match = 1 and r1.Date = r2.Date and r1.Code = r2.Code "
            " inner join '%s' r3 on r3.Match = 1 and r1.Date = r3.Date and r1.Code = r3.Code "
            "where r1.Match = 1 and r1.Date = '%s'") % (self._rule1, self._rule2, self._rule3, latestDate)

        trades = None

        cursor = connection.cursor()
        try:
            cursor.execute(query)
            # print(query)
            trades = cursor.fetchall()
        except sqlite3.OperationalError:
            Logger.log(logging.INFO, "Error Getting Trades", {"scope":__name__})

        connection.close()

        for trade in trades:
            tradeSummary = ("%s %s using %s") % (self._type, trade[0], self._exit)
            strategyDetail = ("Strategy: Mean: %s, Median: %s, Total: %s, Trades: %s, Sharpe Ratio: %s, Drawdown: %s") % (str(self.meanResultPerTrade), str(self.medianResultPerTrade), str(self.totalProfit), str(self.numberOfTrades), str(self.sharpeRatio), str(self.maximumDrawdown))
            rulesDetail = ("Rules: '%s', '%s' and '%s'") % (self._rule1, self._rule2, self._rule3)

            tradeDetail = "%s (%s)\n%s" % (tradeSummary, strategyDetail, rulesDetail)
            self.tradeDetails.append(tradeDetail)
            Logger.log(logging.INFO, "Suggested Trade", {"scope":__name__, "tradeDetail":tradeDetail})

        return len(self.tradeDetails) > 0
开发者ID:garyjoy,项目名称:pyswing,代码行数:34,代码来源:strategy.py


示例4: sendEmail

def sendEmail(tradeDetails):

    message = "Hello!\n\n"
    for trade in tradeDetails:
        message += trade
        message += "\n\n"

    message += "x"

    subject = None
    if len(tradeDetails) > 0:
        subject = "Horse Says Trade!"
    else:
        subject = "Horse Says Go Back To Bed!"

    header  = 'From: %s\n' % "[email protected]"
    header += 'To: %s\n' % ','.join(["[email protected]"])
    header += 'Subject: %s\n\n' % subject
    message = header + message

    server = smtplib.SMTP("smtp.gmail.com:587")
    server.starttls()
    server.login("[email protected]", "abcABC1234567890")
    problems = server.sendmail("[email protected]", ["[email protected]"], message)
    server.quit()

    if problems:
        Logger.log(logging.ERROR, "Error Sending E-mail", {"scope": __name__, "problems": str(problems)})
开发者ID:garyjoy,项目名称:pyswing,代码行数:28,代码来源:AskHorse.py


示例5: setUpClass

    def setUpClass(self):

        Logger.pushLogData("unitTesting", __name__)
        forceWorkingDirectory()

        pyswing.globals.potentialRuleMatches = None
        pyswing.globals.equityCount = None

        pyswing.database.overrideDatabase("output/TestMarketRule.db")
        pyswing.constants.pySwingStartDate = datetime.datetime(2014, 1, 1)

        deleteFile(pyswing.database.pySwingDatabase)

        args = "-n %s" % ("unitTesting")
        createDatabase(args.split())

        pretendDate = datetime.datetime(2015, 9, 1)
        with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method:

            self._equity = Equity("WOR.AX")
            self._equity.importData()

        indicatorADI = IndicatorADI()
        indicatorADI.updateIndicator()

        self.rule = MarketRule("Indicator_ADI", "ADI > 0")
        self.rule.evaluateRule()
开发者ID:garyjoy,项目名称:pyswing,代码行数:27,代码来源:test_marketRule.py


示例6: setUpClass

    def setUpClass(self):
        Logger.pushLogData("unitTesting", __name__)
        forceWorkingDirectory()

        pyswing.globals.potentialRuleMatches = None
        pyswing.globals.equityCount = None

        pyswing.database.overrideDatabase("output/TestDatabase.db")
        pyswing.constants.pySwingStartDate = datetime.datetime(2015, 1, 1)

        deleteFile(pyswing.database.pySwingDatabase)
        deleteFile(pyswing.database.pySwingTestDatabase)

        args = "-n %s" % ("unitTesting")
        createDatabase(args.split())

        pretendDate = datetime.datetime(2015, 7, 1)
        with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method:
            args = "-n unitTest".split()
            importData(args)

        args = "-n unitTest".split()
        updateIndicators(args)

        args = "-n unitTest".split()
        evaluateRules(args)

        args = "-n unitTest".split()
        analyseRules(args)

        args = "-n unitTest".split()
        calculateExitValues(args)
开发者ID:garyjoy,项目名称:pyswing,代码行数:32,代码来源:test_Helper.py


示例7: importData

    def importData(self):
        """
        Import (New) Data from Yahoo.
        """

        start = self._getLatestDate()
        end = self._getTodaysDate()

        Logger.log(logging.INFO, "Loading Data", {"scope":__name__, "tickerCode":self._tickerCode, "start":str(start), "end":str(end)})
        self._data = DataReader(self._tickerCode, "yahoo", start, end)

        self._data['Code'] = self._tickerCode

        for item in ['Open', 'High', 'Low']:
            self._data[item] = self._data[item] * self._data['Adj Close'] / self._data['Close']

        self._data.drop('Close', axis=1, inplace=True)
        self._data.rename(columns={'Adj Close':'Close'}, inplace=True)
        self._data['Volume'] = self._data['Volume'].astype(float)

        connection = sqlite3.connect(pyswing.database.pySwingDatabase)

        query = "insert or replace into Equities (Date, Open, High, Low, Volume, Close, Code) values (?,?,?,?,?,?,?)"
        connection.executemany(query, self._data.to_records(index=True))
        connection.commit()

        connection.close()
开发者ID:garyjoy,项目名称:pyswing,代码行数:27,代码来源:equity.py


示例8: __init__

    def __init__(self):
        """
        ?
        """

        Logger.log(logging.DEBUG, "Log Object Creation", {"scope": __name__})

        self._rules = self._getRules()
开发者ID:garyjoy,项目名称:pyswing,代码行数:8,代码来源:historicMatches.py


示例9: test_lotsOfLoggers

    def test_lotsOfLoggers(self):

        aLogger = Logger._getLogger()
        anotherLogger = Logger._getLogger()

        self.assertIsNotNone(aLogger, "Check A Logger")
        self.assertIsNotNone(anotherLogger, "Check Another Logger")
        self.assertEqual(len(anotherLogger.handlers), 1, "Check Handlers")
开发者ID:garyjoy,项目名称:pyswing,代码行数:8,代码来源:test_Logger.py


示例10: createDatabase

def createDatabase(argv):
    """
    Create Database.

    :param argv: Command Line Parameters.

    -n = Name

    Example:

    python -m pyswing.CreateDatabase -n asx
    """

    Logger.log(logging.INFO, "Log Script Call", {"scope":__name__, "arguments":" ".join(argv)})
    Logger.pushLogData("script", __name__)

    marketName = ""

    try:
        shortOptions = "n:dh"
        longOptions = ["marketName=", "debug", "help"]
        opts, __ = getopt.getopt(argv, shortOptions, longOptions)
    except getopt.GetoptError as e:
        Logger.log(logging.ERROR, "Error Reading Options", {"scope": __name__, "exception": str(e)})
        usage()
        sys.exit(2)

    for opt, arg in opts:
        if opt in ("-d", "--debug"):
            Logger().setLevel(logging.DEBUG)
        elif opt in ("-h", "--help"):
            print("?")
            usage()
            sys.exit()
        elif opt in ("-n", "--marketName"):
            marketName = arg

    if marketName != "":

        pyswing.database.initialiseDatabase(marketName)
        databaseFilePath = pyswing.database.pySwingDatabase
        scriptFilePath = pyswing.constants.pySwingDatabaseScript

        Logger.log(logging.INFO, "Creating Database", {"scope":__name__, "databaseFilePath":databaseFilePath, "scriptFilePath":scriptFilePath})

        query = open(pyswing.constants.pySwingDatabaseScript, 'r').read()
        connection = sqlite3.connect(databaseFilePath)
        c = connection.cursor()
        c.executescript(query)
        connection.commit()
        c.close()
        connection.close()
        TeamCity.setBuildResultText("Created Database")

    else:
        Logger.log(logging.ERROR, "Missing Options", {"scope": __name__, "options": str(argv)})
        usage()
        sys.exit(2)
开发者ID:garyjoy,项目名称:pyswing,代码行数:58,代码来源:CreateDatabase.py


示例11: importData

def importData(argv):
    """
    Import Share Data.

    :param argv: Command Line Parameters.

    -n = Name

    Example:

    python -m pyswing.ImportData -n asx
    """

    Logger.log(logging.INFO, "Log Script Call", {"scope":__name__, "arguments":" ".join(argv)})
    Logger.pushLogData("script", __name__)

    marketName = ""

    try:
        shortOptions = "n:dh"
        longOptions = ["marketName=", "debug", "help"]
        opts, __ = getopt.getopt(argv, shortOptions, longOptions)
    except getopt.GetoptError as e:
        Logger.log(logging.ERROR, "Error Reading Options", {"scope": __name__, "exception": str(e)})
        usage()
        sys.exit(2)

    for opt, arg in opts:
        if opt in ("-d", "--debug"):
            Logger().setLevel(logging.DEBUG)
        elif opt in ("-h", "--help"):
            print("?")
            usage()
            sys.exit()
        elif opt in ("-n", "--marketName"):
            marketName = arg

    if marketName != "":

        pyswing.database.initialiseDatabase(marketName)

        Logger.log(logging.INFO, "Import Market Data", {"scope":__name__, "market":marketName})

        tickerCodesRelativeFilePath = "resources/%s.txt" % (marketName)

        market = Market(tickerCodesRelativeFilePath)

        for index, row in market.tickers.iterrows():
            equity = Equity(row[0])
            equity.importData()

        TeamCity.setBuildResultText("Imported Data from Yahoo")

    else:
        Logger.log(logging.ERROR, "Missing Options", {"scope": __name__, "options": str(argv)})
        usage()
        sys.exit(2)
开发者ID:garyjoy,项目名称:pyswing,代码行数:57,代码来源:ImportData.py


示例12: setUpClass

    def setUpClass(self):

        Logger.pushLogData("unitTesting", __name__)

        forceWorkingDirectory()

        pyswing.database.pySwingDatabase = None
        pyswing.database.pySwingDatabaseInitialised = False
        pyswing.database.pySwingDatabaseOverridden = False
开发者ID:garyjoy,项目名称:pyswing,代码行数:9,代码来源:test_Database.py


示例13: generateHistoricTradesForActiveStrategies

def generateHistoricTradesForActiveStrategies(argv):
    """
    Generate (in the HistoricTrades database table) Historic Trades for the Active Strategies.

    Empty the database table and then fill it with the historic trades for all the active strategies.

    :param argv: Command Line Parameters.

    -n = Name

    Example:

    python -m pyswing.GenerateHistoricTradesForActiveStrategies -n asx
    """

    Logger.log(logging.INFO, "Log Script Call", {"scope":__name__, "arguments":" ".join(argv)})
    Logger.pushLogData("script", __name__)

    marketName = ""

    try:
        shortOptions = "n:dh"
        longOptions = ["marketName=", "debug", "help"]
        opts, __ = getopt.getopt(argv, shortOptions, longOptions)
    except getopt.GetoptError as e:
        Logger.log(logging.ERROR, "Error Reading Options", {"scope": __name__, "exception": str(e)})
        usage()
        sys.exit(2)

    for opt, arg in opts:
        if opt in ("-d", "--debug"):
            Logger().setLevel(logging.DEBUG)
        elif opt in ("-h", "--help"):
            print("?")
            usage()
            sys.exit()
        elif opt in ("-n", "--marketName"):
            marketName = arg

    if marketName != "":

        pyswing.database.initialiseDatabase(marketName)

        Logger.log(logging.INFO, "Generate Historic Trades for Active Strategies", {"scope":__name__, "market":marketName})

        emptyHistoricTradesTable()

        strategies = getActiveStrategies()

        for strategy in strategies:
            strategy.generateHistoricTrades()

    else:
        Logger.log(logging.ERROR, "Missing Options", {"scope": __name__, "options": str(argv)})
        usage()
        sys.exit(2)
开发者ID:garyjoy,项目名称:pyswing,代码行数:56,代码来源:GenerateHistoricTradesForActiveStrategies.py


示例14: analyseRules

def analyseRules(argv):
    """
    Analyse Rules.

    :param argv: Command Line Parameters.

    -n = Name

    Example:

    python -m pyswing.AnalyseRules -n asx
    """

    Logger.log(logging.INFO, "Log Script Call", {"scope":__name__, "arguments":" ".join(argv)})
    Logger.pushLogData("script", __name__)

    marketName = ""

    try:
        shortOptions = "n:dh"
        longOptions = ["marketName=", "debug", "help"]
        opts, __ = getopt.getopt(argv, shortOptions, longOptions)
    except getopt.GetoptError as e:
        Logger.log(logging.ERROR, "Error Reading Options", {"scope": __name__, "exception": str(e)})
        usage()
        sys.exit(2)

    for opt, arg in opts:
        if opt in ("-d", "--debug"):
            Logger().setLevel(logging.DEBUG)
        elif opt in ("-h", "--help"):
            print("?")
            usage()
            sys.exit()
        elif opt in ("-n", "--marketName"):
            marketName = arg

    if marketName != "":

        pyswing.database.initialiseDatabase(marketName)

        Logger.log(logging.INFO, "Analyse Rules", {"scope":__name__, "market":marketName})

        rules = getRules()
        for ruleString in rules:
            rule = Rule(ruleString)
            rule.analyseRule()

        TeamCity.setBuildResultText("Analysed Rules")

    else:
        Logger.log(logging.ERROR, "Missing Options", {"scope": __name__, "options": str(argv)})
        usage()
        sys.exit(2)
开发者ID:garyjoy,项目名称:pyswing,代码行数:54,代码来源:AnalyseRules.py


示例15: setUpClass

    def setUpClass(self):
        Logger.pushLogData("unitTesting", __name__)
        forceWorkingDirectory()

        pyswing.database.overrideDatabase("output/TestCalculateExitValues.db")
        pyswing.constants.pySwingStartDate = datetime.datetime(2015, 1, 1)

        deleteFile(pyswing.database.pySwingDatabase)

        args = "-n %s" % ("unitTesting")
        createDatabase(args.split())
开发者ID:garyjoy,项目名称:pyswing,代码行数:11,代码来源:test_CalculateExitValues.py


示例16: __init__

    def __init__(self, tickerCode):
        """
        Constructor.

        There isn't much to see here. It just makes a note of the Ticker Code.

        :param tickerCode: Ticker Code.
        """

        Logger.log(logging.DEBUG, "Log Object Creation", {"scope":__name__, "arguments":" ".join({tickerCode})})

        self._tickerCode = tickerCode
开发者ID:garyjoy,项目名称:pyswing,代码行数:12,代码来源:equity.py


示例17: __init__

    def __init__(self, relativeFilePath):
        """
        Read the Ticker Codes in the specified file into a data set (pandas.DataFrame).

        :param relativeFilePath: Relative file path (String) for the (file) list of ticker codes.
        """

        Logger.log(logging.DEBUG, "Log Object Creation", {"scope":__name__, "arguments":" ".join({relativeFilePath})})

        self._relativeFilePath = relativeFilePath

        self.tickers = pandas.read_csv(relativeFilePath)
开发者ID:garyjoy,项目名称:pyswing,代码行数:12,代码来源:market.py


示例18: deleteDirectory

def deleteDirectory(relativeDirectoryPath):
    """
    Delete the specified directory.

    :param relativeDirectoryPath: Relative (from the working directory) path to a directory (i.e. that we want to delete).
    """

    try:
        if os.path.exists(relativeDirectoryPath):
            shutil.rmtree(relativeDirectoryPath)
    except OSError as osError:
        Logger.log(logging.ERROR, "Cannot Delete Directory", {"scope":__name__, "directory":relativeDirectoryPath})
        Logger.log(logging.DEBUG, "Caught Exception", {"scope":__name__, "exception":str(osError)})
开发者ID:garyjoy,项目名称:pyswing,代码行数:13,代码来源:FileHelper.py


示例19: setUpClass

    def setUpClass(self):
        Logger.pushLogData("unitTesting", __name__)
        forceWorkingDirectory()

        pyswing.globals.potentialRuleMatches = None
        pyswing.globals.equityCount = None

        pyswing.database.overrideDatabase("output/TestAskHorse.db")
        pyswing.constants.pySwingStartDate = datetime.datetime(2015, 1, 1)

        deleteFile(pyswing.database.pySwingDatabase)

        copyFile(pyswing.database.pySwingTestDatabase, pyswing.database.pySwingDatabase)
开发者ID:garyjoy,项目名称:pyswing,代码行数:13,代码来源:test_AskHorse.py


示例20: forceWorkingDirectory

def forceWorkingDirectory():
    """
    forceWorkingDirectory() will ensure that the working directory is set to the project root (i.e. /Users/Gary/PycharmProjects/pyswing).

    There is a discrepancy between TeamCity (which always forces the working directory to be the project root) and IDEs
    (e.g. Eclipse, PyCharm) (which, by default, set the working directory to be the directory containing the script being run).
    """

    Logger.log(logging.DEBUG, "Log Method Call", {"scope":__name__, "arguments":""})

    workingDirectory = os.path.abspath(os.path.curdir)
    if (os.path.exists("pyswing") and os.path.exists("test")):
        Logger.log(logging.DEBUG, "Working Directory", {"scope":__name__, "workingDirectory":workingDirectory})
    else:
        newWorkingDirectory = None

        if os.path.exists("../pyswing") and os.path.exists("../test"):
            newWorkingDirectory = os.path.abspath("../")
        elif os.path.exists("../../pyswing") and os.path.exists("../../test"):
            newWorkingDirectory = os.path.abspath("../../")
        elif os.path.exists("../../../pyswing") and os.path.exists("../../../test"):
            newWorkingDirectory = os.path.abspath("../../../")
        elif os.path.exists("../../../../pyswing") and os.path.exists("../../../../test"):
            newWorkingDirectory = os.path.abspath("../../../../")
        elif os.path.exists("../../../../../pyswing") and os.path.exists("../../../../../test"):
            newWorkingDirectory = os.path.abspath("../../../../../")
        elif os.path.exists("../../../../../../pyswing") and os.path.exists("../../../../../../test"):
            newWorkingDirectory = os.path.abspath("../../../../../../")

        if newWorkingDirectory is not None:
            os.chdir(newWorkingDirectory)
            Logger.log(logging.DEBUG, "Changed Working Directory", {"scope":__name__, "old":workingDirectory,"new":newWorkingDirectory})

        else:
            Logger.log(logging.WARN, "Cannot Change Working Directory", {"scope":__name__, "workingDirectory":workingDirectory})
开发者ID:garyjoy,项目名称:pyswing,代码行数:35,代码来源:FileHelper.py



注:本文中的pyswing.utils.Logger.Logger类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pyswip.Prolog类代码示例发布时间:2022-05-27
下一篇:
Python pyswagger.SwaggerApp类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap