Navigation

    Backtrader Community

    • Register
    • 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/

    Skewness & Kurtosis of Returns

    General Code/Help
    2
    5
    231
    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.
    • K
      KK last edited by

      Calculations for skewness and Kurtosis for the returns generated

      '''
      310aa271-2e94-4ea2-acba-431cbb39cc15-image.png

      just like standard deviation calculated, is there backtrader function/API ref to calculate Skewness and Kurtosis of the returns? TIA

      1 Reply Last reply Reply Quote 0
      • run-out
        run-out last edited by

        @kk I know this is a lot broader than your question, but I find skewness and kurtosis on the quanstants tearsheet.

        Tearsheet

        Here is the function I run at the end of the test. scene is a dictionary I use to track parameters. results is the backtest strategy object returned from running cerebro.

        import quanstats as qs
        def tearsheet(scene, results):
           
            # Get the stats auto ordered nested dictionary
            value = results[0].analyzers.getbyname("cash_market").get_analysis()
        
            columns = [
                "Date",
                "Cash",
                "Value",
            ]
        
            if scene["save_tearsheet"]:
                # Save tearsheet
                df = pd.DataFrame(value)
                df = df.T
                df = df.reset_index()
                df.columns = columns
        
                df_value = df.set_index("Date")["Value"]
                df_value.index = pd.to_datetime(df_value.index)
                df_value = df_value.sort_index()
                value_returns = qs.utils.to_returns(df_value)
                value_returns = pd.DataFrame(value_returns)
        
                value_returns["diff"] = value_returns["Value"].diff().dropna()
                value_returns["diff"] = value_returns["diff"].abs().cumsum()
                value_returns = value_returns.loc[value_returns["diff"] > 0, "Value"]
                value_returns.index = pd.to_datetime(value_returns.index.date)
        
                # Get the benchmark
                benchmark = None
                bm_title = None
                bm = scene["benchmark"]
                if bm:
                    df_benchmark = yf.download(
                        bm,
                        start=value_returns.index[0],
                        end=value_returns.index[-1],
                        auto_adjust=True,
                    )["Close"]
        
                    df_benchmark = qs.utils.rebase(df_benchmark)
                    benchmark = qs.utils.to_returns(df_benchmark)
                    benchmark.name = bm
                    benchmark.index = pd.to_datetime(benchmark.index.date)
                    bm_title = f"  (benchmark: {bm})"
        
        
        
                # Set up file path.
                Path(scene["save_path"]).mkdir(parents=True, exist_ok=True)
                dir = Path(scene["save_path"])
                filename = (
                        scene["save_name"]
                        + "-"
                        + scene["batchname"]
                        + "-"
                        + scene["batch_runtime"].replace("-", "").replace(":", "").replace(" ", "_")
                        + ".html"
                )
                filepath = dir / filename
        
                title = f"{scene['batchname']}{bm_title if bm_title is not None else ''}"
                qs.reports.html(
                    value_returns,
                    benchmark=benchmark,
                    title=title,
                    output=filepath,
                )
        

        If you need help making the analyzer to track cash_market, look at this post.

        RunBacktest.com

        K 1 Reply Last reply Reply Quote 2
        • K
          KK @run-out last edited by

          @run-out thank you very much, its really useful as i can use it for alternate to pyfolio (struggling with some references). Regarding my question i am trying to find skewness & kurtosis from daily returns to use it in the strategy (like in the given program where variances calculated on daily returns, i want to see if i can find skewness and kurtosis from daily returns - not the strategy results. Thanks again

          1 Reply Last reply Reply Quote 0
          • run-out
            run-out last edited by

            @kk Give this a try. You can call the quantstats utilities independently. So you create an array in next of whatever length you want. You have to use pandas Series. Then call skew and kertosis from quanstants.

               def next(self):
                    n = 30
                    if len(self) < n:
                        return
                    close_slice = pd.Series(self.datas[0].close.get(ago=0, size=n))
                    kurtosis = qs.stats.kurtosis(close_slice)
                    skew = qs.stats.skew(close_slice)
                    self.log(f"close: {self.datas[0].close[0]}, kurtosis: {kurtosis}, skew: {skew}")
            

            I would make this a custom indicator for sure. Also don't forget import quantstats as qs

            RunBacktest.com

            1 Reply Last reply Reply Quote 1
            • K
              KK last edited by

              @run-out thank you. i will give try ...

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