Untitled
user_6415514
plain_text
9 months ago
2.1 kB
30
No Index
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © TobbySimard //@version=5 indicator("Alpha and Beta Calculation", overlay=false) //alpha < 0: the investment has earned too little for its risk (or, was too risky for the return) //alpha = 0: the investment has earned a return adequate for the risk taken //alpha > 0: the investment has a return in excess of the reward for the assumed risk // User Inputs benchmark_symbol = input.symbol("INDEX:ETHUSD", title="Benchmark Symbol") beta_length = input.int(40, title="Beta Period") alphaPeriod = input.int(40, title="Alpha Period") // Function to calculate return percentage return_percent(src) => ta.change(src) * 100 / src[1] // Function to calculate Beta calc_beta(asset_return, benchmark_return, length) => avg_asset_return = ta.sma(asset_return, length) avg_benchmark_return = ta.sma(benchmark_return, length) sum_covariance = 0.0 for idx = 0 to length - 1 asset_variance = asset_return[idx] - avg_asset_return benchmark_variance = benchmark_return[idx] - avg_benchmark_return sum_covariance += asset_variance * benchmark_variance covariance = sum_covariance / (length - 1) beta = covariance / ta.variance(benchmark_return, length) beta // Fetch Benchmark data benchmark_close = request.security(benchmark_symbol, 'D', close) benchmark_return = return_percent(benchmark_close) // Fetch Asset data and calculate return asset_close = close asset_return = return_percent(asset_close) // Calculate Beta for the asset beta = calc_beta(asset_return, benchmark_return, beta_length) // Calculate Alpha alphaReturn = (close - close[alphaPeriod]) / close[alphaPeriod] benchmarkAlphaReturn = (benchmark_close - benchmark_close[alphaPeriod]) / benchmark_close[alphaPeriod] alpha = alphaReturn - (benchmarkAlphaReturn * beta) // Plot Alpha plot(beta, color=color.purple, style=plot.style_line, transp=40) plot(alpha, color=color.green, style=plot.style_line, transp=40)
Editor is loading...
Leave a Comment