Beispiel #1
0
def sharpe_ratio_2(returns,
                   riskFreeRate,
                   firstDateTime,
                   lastDateTime,
                   annualized=True):
    ret = 0.0

    # From http://en.wikipedia.org/wiki/Sharpe_ratio:
    # if Rf is a constant risk-free return throughout the period, then stddev(R - Rf) = stddev(R).
    volatility = stats.stddev(returns, 1)

    if volatility != 0:
        # We use 365 instead of 252 becuase we wan't the diff from 1/1/xxxx to 12/31/xxxx to be 1 year.
        yearsTraded = days_traded(firstDateTime, lastDateTime) / 365.0

        riskFreeRateForPeriod = riskFreeRate * yearsTraded
        rfPerReturn = riskFreeRateForPeriod / float(len(returns))

        avgExcessReturns = stats.mean(returns) - rfPerReturn
        ret = avgExcessReturns / volatility

        if annualized:
            ret = ret * math.sqrt(len(returns) / yearsTraded)

    return ret
Beispiel #2
0
def main():
    import coloredlogs
    coloredlogs.install(level='DEBUG',
                        fmt='[%(asctime)s] %(levelname)s %(message)s')

    # Load the yahoo feed from CSV files.
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV("aeti", "./tests/data/aeti-2011-yahoofinance.csv")
    feed.addBarsFromCSV("egan", "./tests/data/egan-2011-yahoofinance.csv")
    feed.addBarsFromCSV("glng", "./tests/data/glng-2011-yahoofinance.csv")
    feed.addBarsFromCSV("simo", "./tests/data/simo-2011-yahoofinance.csv")

    # Evaluate the strategy with the feed's bars.
    myStrategy = MyStrategy(feed)

    # Attach returns and sharpe ratio analyzers.
    retAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(retAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    myStrategy.attachAnalyzer(sharpeRatioAnalyzer)

    # Run the strategy
    myStrategy.run()

    # Print the results.
    print("Final portfolio value: $%.2f" % myStrategy.getResult())
    print("Anual return: %.2f %%" %
          (retAnalyzer.getCumulativeReturns()[-1] * 100))
    print("Average daily return: %.2f %%" %
          (stats.mean(retAnalyzer.getReturns()) * 100))
    print("Std. dev. daily return: %.4f" %
          (stats.stddev(retAnalyzer.getReturns())))
    print("Sharpe ratio: %.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0)))
Beispiel #3
0
def main():
    # 2.读取csv文件.
    feed = GenericBarFeed(Frequency.DAY, None, None)
    feed.addBarsFromCSV("a", "a.csv")
    feed.addBarsFromCSV("b", "b.csv")
    feed.addBarsFromCSV("c", "c.csv")
    feed.addBarsFromCSV("d", "d.csv")

    strat = MyStrategy(feed)

    # 3.加入分析器
    retAnalyzer = returns.Returns()
    strat.attachAnalyzer(retAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    # 4.运行策略
    strat.run()

    # 5.输出结果

    # 最终的投资组合价值
    print("Final portfolio value: $%.2f" % strat.getResult())

    # 年化平均收益率
    print("Anual return: %.2f %%" % (retAnalyzer.getCumulativeReturns()[-1] * 100))

    # 平均日收益
    print("Average daily return: %.2f %%" % (stats.mean(retAnalyzer.getReturns()) * 100))

    # 每日收益标准开发
    print("Std. dev. daily return: %.4f" % (stats.stddev(retAnalyzer.getReturns())))

    # 夏普比率
    print("Sharpe ratio: %.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0)))
Beispiel #4
0
def sharpe_ratio(returns, riskFreeRate, tradingPeriods, annualized=True):
    ret = 0.0

    # From http://en.wikipedia.org/wiki/Sharpe_ratio: if Rf is a constant risk-free return throughout the period,
    # then stddev(R - Rf) = stddev(R).
    volatility = stats.stddev(returns, 1)

    if volatility != 0:
        rfPerReturn = riskFreeRate / float(tradingPeriods)
        avgExcessReturns = stats.mean(returns) - rfPerReturn
        ret = avgExcessReturns / volatility

        if annualized:
            ret = ret * math.sqrt(tradingPeriods)

    return ret
Beispiel #5
0
def main():
    # Load the orders file.
    ordersFile = OrdersFile("./tests/data/orders.csv")

    print("First date", ordersFile.getFirstDate())
    print("Last date", ordersFile.getLastDate())
    print("Symbols", ordersFile.getInstruments())

    # Load the data from QSTK storage. QS environment variable has to be defined.
    if os.getenv("QS") is None:
        raise Exception("QS environment variable not defined")

    feed = yahoofeed.Feed()
    feed.setBarFilter(
        csvfeed.DateRangeFilter(ordersFile.getFirstDate(),
                                ordersFile.getLastDate()))
    feed.setDailyBarTime(
        datetime.time(0, 0, 0)
    )  # This is to match the dates loaded with the ones in the orders file.

    for symbol in ordersFile.getInstruments():
        feed.addBarsFromCSV(
            symbol,
            os.path.join(os.getenv("QS"), "QSData", "Yahoo", symbol + ".csv"))

    # Run the strategy.
    cash = 1000000
    useAdjustedClose = True
    myStrategy = MyStrategy(feed, cash, ordersFile, useAdjustedClose)

    # Attach returns and sharpe ratio analyzers.
    retAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(retAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    myStrategy.attachAnalyzer(sharpeRatioAnalyzer)

    myStrategy.run()

    # Print the results.
    print("Final portfolio value: $%.2f" % myStrategy.getResult())
    print("Anual return: %.2f %%" %
          (retAnalyzer.getCumulativeReturns()[-1] * 100))
    print("Average daily return: %.2f %%" %
          (stats.mean(retAnalyzer.getReturns()) * 100))
    print("Std. dev. daily return: %.4f" %
          (stats.stddev(retAnalyzer.getReturns())))
    print("Sharpe ratio: %.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0)))