Skewness & Kurtosis of Returns
-
Calculations for skewness and Kurtosis for the returns generated
'''
just like standard deviation calculated, is there backtrader function/API ref to calculate Skewness and Kurtosis of the returns? TIA
-
@kk I know this is a lot broader than your question, but I find skewness and kurtosis on the quanstants 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. -
@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
-
@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
-
@run-out thank you. i will give try ...