# Enhancing Trading Strategies with the Weekly Seasonality Dynamic Kelly Criterion Indicator
Amidst this pursuit to chase price, a common pitfall emerges: an overemphasis on price movements without adequate attention to risk management, probabilistic analysis, and strategic position sizing. To address these challenges, I developed the **Weekly Seasonality with Dynamic Kelly Criterion Indicator**. It is designed to refocus traders on essential aspects of trading, such as risk management and probabilistic returns, thereby catering to both short-term swing traders and long-term investors aiming for tax-efficient positions.
## The Motivation Behind the Indicator
### Overemphasis on Price: A Common Trading Pitfall
Many traders concentrate heavily on price charts and technical indicators, often neglecting the underlying principles of risk management and probabilistic analysis. This overemphasis on price can lead to:
- **Overtrading:** Making frequent trades based solely on price movements without considering the associated risks.
- **Poor Risk Management:** Failing to set appropriate stop-loss levels or position sizes, increasing the potential for significant losses.
- **Emotional Trading:** Letting emotions drive trading decisions rather than objective analysis, which can result in impulsive and irrational trades.
### The Need for Balanced Focus
To achieve sustained trading success, it is crucial to balance price analysis with robust risk management and probabilistic strategies. Key areas of focus include:
1. **Risk Management:** Implementing strategies to protect capital, such as setting stop-loss orders and determining appropriate position sizes based on risk tolerance.
2. **Probabilistic Analysis:** Assessing the likelihood of various market outcomes to make informed trading decisions.
3. **Swing Trading Percent Returns:** Capitalizing on short- to medium-term price movements by buying assets below their average return and selling them above.
## Introducing the Weekly Seasonality with Dynamic Kelly Criterion Indicator
The **Weekly Seasonality with Dynamic Kelly Criterion Indicator** is designed to integrate these essential elements into a comprehensive tool that aids traders in making informed, risk-aware decisions. Below, we explore the key components and functionalities of this indicator.
### Key Components of the Indicator
1. **Average Return (%)**
- **Definition:** The mean percentage return for each week across multiple years.
- **Purpose:** Serves as a benchmark to identify weeks with above or below-average performance, guiding buy and sell decisions.
2. **Positive Percentage (%)**
- **Definition:** The proportion of weeks that yielded positive returns.
- **Purpose:** Indicates the consistency of positive returns, helping traders gauge the reliability of certain weeks for trading.
3. **Volatility (%)**
- **Definition:** The standard deviation of weekly returns.
- **Purpose:** Measures the variability of returns, providing insights into the risk associated with trading during specific weeks.
4. **Kelly Ratio**
- **Definition:** A mathematical formula used to determine the optimal size of a series of bets to maximize the logarithmic growth of capital.
- **Purpose:** Balances potential returns against risks, guiding traders on the appropriate position size to take.
5. **Adjusted Kelly Fraction**
- **Definition:** The Kelly Ratio adjusted based on user-defined risk tolerance and external factors like Federal Reserve (Fed) stance.
- **Purpose:** Personalizes the Kelly Criterion to align with individual risk preferences and market conditions, enhancing risk management.
6. **Position Size ($)**
- **Definition:** The calculated amount to invest based on the Adjusted Kelly Fraction.
- **Purpose:** Ensures that position sizes are aligned with risk management strategies, preventing overexposure to any single trade.
7. **Max Drawdown (%)**
- **Definition:** The maximum observed loss from a peak to a trough of a portfolio, before a new peak is attained.
- **Purpose:** Assesses the worst-case scenario for losses, crucial for understanding potential capital erosion.
### Functionality and Benefits
- **Weekly Data Aggregation:** Aggregates weekly returns across multiple years to provide a robust statistical foundation for decision-making.
- **Quarterly Filtering:** Allows users to filter weeks based on quarters, enabling seasonality analysis and tailored strategies aligned with specific timeframes.
- **Dynamic Risk Adjustment:** Incorporates the Dynamic Kelly Criterion to adjust position sizes in real-time based on changing risk profiles and market conditions.
- **User-Friendly Visualization:** Presents all essential metrics in an organized Summary Table, facilitating quick and informed decision-making.
## The Origin of the Kelly Criterion and Addressing Its Limitations
### Understanding the Kelly Criterion
The Kelly Criterion, developed by John L. Kelly Jr. in 1956, is a formula used to determine the optimal size of a series of bets to maximize the long-term growth of capital. The formula considers both the probability of winning and the payout ratio, balancing potential returns against the risk of loss.
**Kelly Formula:**
\[ \text{Kelly Ratio} = \frac{bp - q}{b} \]
Where:
- \( b \) = the net odds received on the wager ("b to 1")
- \( p \) = probability of winning
- \( q \) = probability of losing ( \( q = 1 - p \) )
### The Risk of Ruin
While the Kelly Criterion is effective in optimizing growth, it carries inherent risks:
- **Overbetting:** If the input probabilities or payout ratios are misestimated, the Kelly Criterion can suggest overly aggressive position sizes, leading to significant losses.
- **Assumption of Constant Probabilities:** The criterion assumes that probabilities remain constant, which is rarely the case in dynamic markets.
- **Ignoring External Factors:** Traditional Kelly implementations do not account for external factors such as Federal Reserve rates, margin requirements, or market volatility, which can impact risk and returns.
### Addressing Traditional Limitations
Recognizing these limitations, the **Weekly Seasonality with Dynamic Kelly Criterion Indicator** introduces enhancements to the traditional Kelly approach:
- **Incorporation of Fed Stance:** Adjusts the Kelly Fraction based on the current stance of the Federal Reserve (neutral, dovish, or hawkish), reflecting broader economic conditions that influence market behavior.
- **Margin and Leverage Considerations:** Accounts for margin rates and leverage, ensuring that position sizes remain within manageable risk parameters.
- **Dynamic Adjustments:** Continuously updates position sizes based on real-time risk assessments and probabilistic analyses, mitigating the risk of ruin associated with static Kelly implementations.
## How the Indicator Aids Traders
### For Short-Term Swing Traders
Short-term swing traders thrive on capitalizing over weekly price movements. The indicator aids them by:
- **Identifying Favorable Weeks:** Highlights weeks with above-average returns and favorable volatility, guiding entry and exit points.
- **Optimal Position Sizing:** Utilizes the Adjusted Kelly Fraction to determine the optimal amount to invest, balancing potential returns with risk exposure.
- **Probabilistic Insights:** Provides metrics like Positive Percentage (%) and Kelly Ratio to assess the likelihood of favorable outcomes, enhancing decision-making.
### For Long-Term Tax-Free Investors
This is effectively a drop-in replacement for DCA which uses fixed position size that doesn't change based on market conditions, as a result, it's like catching multiple falling knifes by the blade and smiling with blood on your hand... I don't know about you, but I'd rather juggle by the hilt and look like an actual professional...
Long-term investors, especially those seeking tax-free positions (e.g., through retirement accounts), benefit from:
- **Consistent Risk Management:** Ensures that position sizes are aligned with long-term capital preservation strategies.
- **Seasonality Analysis:** Allows for strategic positioning based on historical performance trends across different weeks and quarters.
- **Dynamic Adjustments:** Adapts to changing market conditions, maintaining optimal risk profiles over extended investment horizons.
### Developers
Please double check the logic and functionality because I think there are a few issue and I need to crowd source solutions and be responsible about the code I publish. If you have corrections, please DM me or leave a respectful comment.
I want to publish this by the end of the year and include other things like highlighting triple witching weeks, adding columns for volume % stats, VaR and CVaR, alpha, beta (to see the seasonal alpha and beta based off a benchmark ticker and risk free rate ticker and other little goodies.
Pine Script®
Amidst this pursuit to chase price, a common pitfall emerges: an overemphasis on price movements without adequate attention to risk management, probabilistic analysis, and strategic position sizing. To address these challenges, I developed the **Weekly Seasonality with Dynamic Kelly Criterion Indicator**. It is designed to refocus traders on essential aspects of trading, such as risk management and probabilistic returns, thereby catering to both short-term swing traders and long-term investors aiming for tax-efficient positions.
## The Motivation Behind the Indicator
### Overemphasis on Price: A Common Trading Pitfall
Many traders concentrate heavily on price charts and technical indicators, often neglecting the underlying principles of risk management and probabilistic analysis. This overemphasis on price can lead to:
- **Overtrading:** Making frequent trades based solely on price movements without considering the associated risks.
- **Poor Risk Management:** Failing to set appropriate stop-loss levels or position sizes, increasing the potential for significant losses.
- **Emotional Trading:** Letting emotions drive trading decisions rather than objective analysis, which can result in impulsive and irrational trades.
### The Need for Balanced Focus
To achieve sustained trading success, it is crucial to balance price analysis with robust risk management and probabilistic strategies. Key areas of focus include:
1. **Risk Management:** Implementing strategies to protect capital, such as setting stop-loss orders and determining appropriate position sizes based on risk tolerance.
2. **Probabilistic Analysis:** Assessing the likelihood of various market outcomes to make informed trading decisions.
3. **Swing Trading Percent Returns:** Capitalizing on short- to medium-term price movements by buying assets below their average return and selling them above.
## Introducing the Weekly Seasonality with Dynamic Kelly Criterion Indicator
The **Weekly Seasonality with Dynamic Kelly Criterion Indicator** is designed to integrate these essential elements into a comprehensive tool that aids traders in making informed, risk-aware decisions. Below, we explore the key components and functionalities of this indicator.
### Key Components of the Indicator
1. **Average Return (%)**
- **Definition:** The mean percentage return for each week across multiple years.
- **Purpose:** Serves as a benchmark to identify weeks with above or below-average performance, guiding buy and sell decisions.
2. **Positive Percentage (%)**
- **Definition:** The proportion of weeks that yielded positive returns.
- **Purpose:** Indicates the consistency of positive returns, helping traders gauge the reliability of certain weeks for trading.
3. **Volatility (%)**
- **Definition:** The standard deviation of weekly returns.
- **Purpose:** Measures the variability of returns, providing insights into the risk associated with trading during specific weeks.
4. **Kelly Ratio**
- **Definition:** A mathematical formula used to determine the optimal size of a series of bets to maximize the logarithmic growth of capital.
- **Purpose:** Balances potential returns against risks, guiding traders on the appropriate position size to take.
5. **Adjusted Kelly Fraction**
- **Definition:** The Kelly Ratio adjusted based on user-defined risk tolerance and external factors like Federal Reserve (Fed) stance.
- **Purpose:** Personalizes the Kelly Criterion to align with individual risk preferences and market conditions, enhancing risk management.
6. **Position Size ($)**
- **Definition:** The calculated amount to invest based on the Adjusted Kelly Fraction.
- **Purpose:** Ensures that position sizes are aligned with risk management strategies, preventing overexposure to any single trade.
7. **Max Drawdown (%)**
- **Definition:** The maximum observed loss from a peak to a trough of a portfolio, before a new peak is attained.
- **Purpose:** Assesses the worst-case scenario for losses, crucial for understanding potential capital erosion.
### Functionality and Benefits
- **Weekly Data Aggregation:** Aggregates weekly returns across multiple years to provide a robust statistical foundation for decision-making.
- **Quarterly Filtering:** Allows users to filter weeks based on quarters, enabling seasonality analysis and tailored strategies aligned with specific timeframes.
- **Dynamic Risk Adjustment:** Incorporates the Dynamic Kelly Criterion to adjust position sizes in real-time based on changing risk profiles and market conditions.
- **User-Friendly Visualization:** Presents all essential metrics in an organized Summary Table, facilitating quick and informed decision-making.
## The Origin of the Kelly Criterion and Addressing Its Limitations
### Understanding the Kelly Criterion
The Kelly Criterion, developed by John L. Kelly Jr. in 1956, is a formula used to determine the optimal size of a series of bets to maximize the long-term growth of capital. The formula considers both the probability of winning and the payout ratio, balancing potential returns against the risk of loss.
**Kelly Formula:**
\[ \text{Kelly Ratio} = \frac{bp - q}{b} \]
Where:
- \( b \) = the net odds received on the wager ("b to 1")
- \( p \) = probability of winning
- \( q \) = probability of losing ( \( q = 1 - p \) )
### The Risk of Ruin
While the Kelly Criterion is effective in optimizing growth, it carries inherent risks:
- **Overbetting:** If the input probabilities or payout ratios are misestimated, the Kelly Criterion can suggest overly aggressive position sizes, leading to significant losses.
- **Assumption of Constant Probabilities:** The criterion assumes that probabilities remain constant, which is rarely the case in dynamic markets.
- **Ignoring External Factors:** Traditional Kelly implementations do not account for external factors such as Federal Reserve rates, margin requirements, or market volatility, which can impact risk and returns.
### Addressing Traditional Limitations
Recognizing these limitations, the **Weekly Seasonality with Dynamic Kelly Criterion Indicator** introduces enhancements to the traditional Kelly approach:
- **Incorporation of Fed Stance:** Adjusts the Kelly Fraction based on the current stance of the Federal Reserve (neutral, dovish, or hawkish), reflecting broader economic conditions that influence market behavior.
- **Margin and Leverage Considerations:** Accounts for margin rates and leverage, ensuring that position sizes remain within manageable risk parameters.
- **Dynamic Adjustments:** Continuously updates position sizes based on real-time risk assessments and probabilistic analyses, mitigating the risk of ruin associated with static Kelly implementations.
## How the Indicator Aids Traders
### For Short-Term Swing Traders
Short-term swing traders thrive on capitalizing over weekly price movements. The indicator aids them by:
- **Identifying Favorable Weeks:** Highlights weeks with above-average returns and favorable volatility, guiding entry and exit points.
- **Optimal Position Sizing:** Utilizes the Adjusted Kelly Fraction to determine the optimal amount to invest, balancing potential returns with risk exposure.
- **Probabilistic Insights:** Provides metrics like Positive Percentage (%) and Kelly Ratio to assess the likelihood of favorable outcomes, enhancing decision-making.
### For Long-Term Tax-Free Investors
This is effectively a drop-in replacement for DCA which uses fixed position size that doesn't change based on market conditions, as a result, it's like catching multiple falling knifes by the blade and smiling with blood on your hand... I don't know about you, but I'd rather juggle by the hilt and look like an actual professional...
Long-term investors, especially those seeking tax-free positions (e.g., through retirement accounts), benefit from:
- **Consistent Risk Management:** Ensures that position sizes are aligned with long-term capital preservation strategies.
- **Seasonality Analysis:** Allows for strategic positioning based on historical performance trends across different weeks and quarters.
- **Dynamic Adjustments:** Adapts to changing market conditions, maintaining optimal risk profiles over extended investment horizons.
### Developers
Please double check the logic and functionality because I think there are a few issue and I need to crowd source solutions and be responsible about the code I publish. If you have corrections, please DM me or leave a respectful comment.
I want to publish this by the end of the year and include other things like highlighting triple witching weeks, adding columns for volume % stats, VaR and CVaR, alpha, beta (to see the seasonal alpha and beta based off a benchmark ticker and risk free rate ticker and other little goodies.
//@version=5
indicator("Weekly Seasonality with Dynamic Kelly Criterion", overlay=false, max_labels_count=500)
////////////
// Inputs //
////////////
// User Inputs
int startYearInput = input.int(2015, "Starting Year for Analysis", minval=1900)
float capitalInput = input.float(10000, "Available Capital ($)", minval=0)
// User-defined inputs
float riskToleranceInput = input.float(1.0, "Risk Tolerance (0-1)", minval=0, maxval=1)
float maxDrawdownInput = input.float(20.0, "Maximum Drawdown (%)", minval=0)
float marginRateInput = input.float(0.5, "Margin Rate (0-1)", minval=0.01, maxval=1)
float maintenanceRateInput = input.float(0.25, "Maintenance Rate (0-1)", minval=0, maxval=1)
string fedStanceInput = input.string("neutral", "Fed Stance", options=["neutral", "dovish", "hawkish"])
// Options to display the results
bool showTableInput = input.bool(true, "Show Weekly Summary Table")
// Quarter Inputs
// Options to filter returns by specific quarters
bool q1Input = input.bool(true, "Q1")
bool q2Input = input.bool(false, "Q2")
bool q3Input = input.bool(false, "Q3")
bool q4Input = input.bool(false, "Q4")
/////////////////////////
// Function Definitions //
/////////////////////////
// Function to calculate adjusted Kelly Fraction based on Kelly Ratio, risk tolerance, and Fed stance
calculateAdjustedKellyFraction(float kellyRatio, float riskTolerance, string fedStance) =>
// Adjust Kelly Fraction based on risk tolerance
float adjustedKellyFraction = kellyRatio * riskTolerance
// Adjust based on Fed stance
float kellyAdjustment = fedStance == "dovish" ? 0.1 : fedStance == "hawkish" ? -0.1 : 0.0
adjustedKellyFraction := adjustedKellyFraction + kellyAdjustment
// Ensure Kelly fraction is within bounds [-1, 1]
adjustedKellyFraction := math.max(math.min(adjustedKellyFraction, 1), -1)
adjustedKellyFraction
// Custom function to sum over an array
sumArray(float[] arr) =>
float total = 0.0
for i = 0 to array.size(arr) - 1
total += array.get(arr, i)
total
// Function to calculate standard deviation for returns
calculateStdDev(float[] returns) =>
int count = array.size(returns)
if count > 1
float avg = sumArray(returns) / count
float sumSqDiffs = 0.0
for i = 0 to count - 1
float val = array.get(returns, i)
float diff = val - avg
sumSqDiffs += diff * diff
float variance = sumSqDiffs / (count - 1)
math.sqrt(variance)
else
0.0
// Function to calculate Kelly Ratio
calculateKellyRatio(float[] returns) =>
float winCount = 0.0
float lossCount = 0.0
float totalWinReturn = 0.0
float totalLossReturn = 0.0
int n = array.size(returns)
for i = 0 to n - 1
float ret = array.get(returns, i)
if ret > 0
winCount += 1
totalWinReturn += ret
else if ret < 0
lossCount += 1
totalLossReturn += math.abs(ret)
float winProb = (winCount + lossCount) > 0 ? winCount / (winCount + lossCount) : 0.0
float lossProb = 1 - winProb
float avgWinReturn = winCount > 0 ? totalWinReturn / winCount : 0.0
float avgLossReturn = lossCount > 0 ? totalLossReturn / lossCount : 0.0
float kellyRatio = 0.0
if avgLossReturn != 0 and avgWinReturn != 0
float odds = avgWinReturn / avgLossReturn
if odds != 0
kellyRatio := winProb - (lossProb / odds)
kellyRatio
// Function to calculate Max Drawdown
calculateMaxDrawdown(float[] returns) =>
if array.size(returns) == 0
0.0
else
float peak = array.get(returns, 0) // Updated to use array.get
float maxDD = 0.0
float cumulativeReturn = 0.0
for i = 0 to array.size(returns) - 1
cumulativeReturn += array.get(returns, i) // Updated to use array.get
if cumulativeReturn > peak
peak := cumulativeReturn
float drawdown = peak - cumulativeReturn
if drawdown > maxDD
maxDD := drawdown
maxDDPercent = peak != 0 ? (maxDD / peak) * 100 : 0.0
maxDDPercent
/////////////////////////////////
// Data Retrieval and Processing //
/////////////////////////////////
// Initialize variables
var float[] weekReturnSums = array.new_float(52, 0.0)
var int[] weekReturnCounts = array.new_int(52, 0)
var int[] weekPositiveCounts = array.new_int(52, 0)
var float[] weekReturnSquares = array.new_float(52, 0.0)
var float[] allWeekReturns = array.new_float()
var int[] allWeekNums = array.new_int()
// Get weekly data using request.security
[weeklyClose, weeklyTime] = request.security(syminfo.tickerid, 'W', [close, time])
// Detect new week
isNewWeek = ta.change(weeklyTime)
if isNewWeek
int weekNum = weekofyear(weeklyTime[1]) // Previous week number
int yearNum = year(weeklyTime[1])
if yearNum >= startYearInput
float prevWeeklyClose = weeklyClose[1]
float currWeeklyClose = weeklyClose
float ret = (currWeeklyClose - prevWeeklyClose) / prevWeeklyClose * 100
// Update the arrays
int idx = weekNum - 1 // index in arrays
if idx >= 0 and idx < 52
// Sum of returns
sum = array.get(weekReturnSums, idx) + ret
array.set(weekReturnSums, idx, sum)
// Count of returns
count = array.get(weekReturnCounts, idx) + 1
array.set(weekReturnCounts, idx, count)
// Sum of squared returns
sumSq = array.get(weekReturnSquares, idx) + ret * ret
array.set(weekReturnSquares, idx, sumSq)
// Positive counts
posCount = array.get(weekPositiveCounts, idx)
if ret > 0
posCount += 1
array.set(weekPositiveCounts, idx, posCount)
// Store all returns and week numbers
array.push(allWeekReturns, ret)
array.push(allWeekNums, weekNum)
////////////////
// Visualization //
////////////////
if showTableInput and barstate.islast
// Prepare data for the table
var int[] selectedWeekNumbers = array.new_int()
var float[] avgReturnsArray = array.new_float()
var float[] stdDevArray = array.new_float()
var float[] posPercentsArray = array.new_float()
var float[] kellyRatiosArray = array.new_float()
var float[] adjustedKellyFractionsArray = array.new_float()
var float[] positionSizesArray = array.new_float()
var float[] maxDrawdownsArray = array.new_float()
for idx = 0 to 51
int weekNum = idx + 1
// Check if the week number is in the specified quarters
bool isInQuarter = (weekNum >= 1 and weekNum <= 13 and q1Input) or
(weekNum >= 14 and weekNum <= 26 and q2Input) or
(weekNum >= 27 and weekNum <= 39 and q3Input) or
(weekNum >= 40 and weekNum <= 52 and q4Input)
if isInQuarter
int count = array.get(weekReturnCounts, idx)
if count > 0
array.push(selectedWeekNumbers, weekNum)
float sum = array.get(weekReturnSums, idx)
float avgRet = sum / count
array.push(avgReturnsArray, avgRet)
float sumSq = array.get(weekReturnSquares, idx)
float variance = (sumSq - (sum * sum) / count) / (count - 1)
float stdDev = variance > 0 ? math.sqrt(variance) : 0.0
array.push(stdDevArray, stdDev)
// Positive percentage
int posCount = array.get(weekPositiveCounts, idx)
float posPercent = posCount / count * 100
array.push(posPercentsArray, posPercent)
// Extract returns for this week
float[] returnsArray = array.new_float()
for i = 0 to array.size(allWeekReturns) - 1
if array.get(allWeekNums, i) == weekNum
array.push(returnsArray, array.get(allWeekReturns, i))
// Kelly Ratio
float kellyRatio = calculateKellyRatio(returnsArray)
array.push(kellyRatiosArray, kellyRatio)
// Adjusted Kelly Fraction
float adjustedKellyFraction = calculateAdjustedKellyFraction(kellyRatio, riskToleranceInput, fedStanceInput)
array.push(adjustedKellyFractionsArray, adjustedKellyFraction)
// Leverage factor
float leverageFactor = marginRateInput > 0 ? 1 / marginRateInput : 1.0
// Max position size
float maxPositionSize = capitalInput * leverageFactor
// Position size
float positionSize = maxPositionSize * adjustedKellyFraction
// Ensure position size does not exceed max position size
positionSize := math.min(positionSize, maxPositionSize)
// Max Drawdown
float maxDD = calculateMaxDrawdown(returnsArray)
// Adjust position size if max drawdown exceeds maxDrawdownInput
if maxDD > maxDrawdownInput and maxDD != 0
positionSize := positionSize * (maxDrawdownInput / maxDD)
array.push(positionSizesArray, positionSize)
array.push(maxDrawdownsArray, maxDD)
// Limit the number of rows to fit within the table size limit
int maxRows = 49 // 49 data rows + 1 header row = 50 total rows
int totalRows = array.size(selectedWeekNumbers)
int numRows = math.min(totalRows, maxRows)
int startIndex = 0 // Display from the first selected week
// Create table
var table returnsTable = table.new(position.top_right, 8, numRows + 1, border_width=1)
// Set table headers
table.cell(returnsTable, 0, 0, "Week", bgcolor=color.gray, text_color=color.white)
table.cell(returnsTable, 1, 0, "Avg Return (%)", bgcolor=color.gray, text_color=color.white)
table.cell(returnsTable, 2, 0, "Volatility (%)", bgcolor=color.gray, text_color=color.white)
table.cell(returnsTable, 3, 0, "Pos %", bgcolor=color.gray, text_color=color.white)
table.cell(returnsTable, 4, 0, "Kelly Ratio", bgcolor=color.gray, text_color=color.white)
table.cell(returnsTable, 5, 0, "Adj Kelly Frac", bgcolor=color.gray, text_color=color.white)
table.cell(returnsTable, 6, 0, "Position Size ($)", bgcolor=color.gray, text_color=color.white)
table.cell(returnsTable, 7, 0, "Max Drawdown (%)", bgcolor=color.gray, text_color=color.white)
// Populate table
for idx = startIndex to numRows - 1
int row = idx + 1 // Adjust row index for the table
int weekNum = array.get(selectedWeekNumbers, idx)
float avgRet = array.get(avgReturnsArray, idx)
float stdDev = array.get(stdDevArray, idx)
float posPercent = array.get(posPercentsArray, idx)
float kellyRatio = array.get(kellyRatiosArray, idx)
float adjustedKellyFraction = array.get(adjustedKellyFractionsArray, idx)
float posSize = array.get(positionSizesArray, idx)
float maxDD = array.get(maxDrawdownsArray, idx)
// Week Number
table.cell(returnsTable, 0, row, str.tostring(weekNum))
// Avg Return (%)
table.cell(returnsTable, 1, row, str.format("{0,number,#.##}", avgRet))
// Volatility (%)
table.cell(returnsTable, 2, row, str.format("{0,number,#.##}", stdDev))
// Pos %
table.cell(returnsTable, 3, row, str.format("{0,number,#.##}", posPercent))
// Kelly Ratio
table.cell(returnsTable, 4, row, str.format("{0,number,#.####}", kellyRatio))
// Adj Kelly Frac
table.cell(returnsTable, 5, row, str.format("{0,number,#.####}", adjustedKellyFraction))
// Position Size ($)
table.cell(returnsTable, 6, row, str.format("{0,number,#.##}", posSize))
// Max Drawdown (%)
table.cell(returnsTable, 7, row, str.format("{0,number,#.##}", maxDD))
免責聲明
這些資訊和出版物並不意味著也不構成TradingView提供或認可的金融、投資、交易或其他類型的意見或建議。請在使用條款閱讀更多資訊。
免責聲明
這些資訊和出版物並不意味著也不構成TradingView提供或認可的金融、投資、交易或其他類型的意見或建議。請在使用條款閱讀更多資訊。