Backtrader Community

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

    Improve n period Sharpe Ratio indicator

    Indicators/Strategies/Analyzers
    1
    1
    167
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • Sumit Pandey
      Sumit Pandey last edited by

      Hi,
      I have written a code to calculate the sharpe ratio of security.

      class sharpe(bt.Indicator):
          lines = ('sharpe',)
          params=dict(period=151)
      
          def __init__(self):
              self.addminperiod(self.p.period)
              #self.roc= self.data(-1) / self.data(-self.p.period) - 1.0
              #self.stdev=bt.ind.StdDev(self.data,period=self.p.period)
              #self.lines.sharpe=self.roc/self.stdev
          def next(self):
              iterdata = self.data.get(size=self.p.period+1)
              returns= [a1 / a2 - 1 for a1, a2 in zip(iterdata[1:], iterdata)]
              avgret= np.average(returns)
              stdev=np.std(returns)
              self.lines.sharpe[0] = (avgret/stdev)
      

      Here I have taken Rf to be zero.
      Can someone optimize this code (write a better version) if possible?

      1 Reply Last reply Reply Quote 0
      • 1 / 1
      • First post
        Last post
      Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors