admin管理员组

文章数量:1386652

I'm developing a custom indicator in Indie Language, but I'm encountering a type error related to initializing a variable with None.

Error: 26:4 cannot initialize `arch_volatility` with `None`; in Indie language optionals are explicit, so to make this assignment, you need to declare `arch_volatility` as `indie.Optional[...]`

I tried following examples from other parts of my code (like returns = MutSeriesF.new(0)) but still can’t resolve this. Here's the problematic code:

# indie:lang_version = 5
import math
from indie import indicator, param, plot, color, SeriesF, MutSeriesF
from indie.algorithms import StdDev, Sma, Ema

@indicator('Advanced Volatility and Risk-Adjusted Return Indicator', overlay_main_pane=True)
@param.int('stddev_length', default=20, min=1, title='Standard Deviation Length')
@param.int('sma_length', default=20, min=1, title='SMA Length for Sharpe Ratio')
@param.float('risk_free_rate', default=0.01, title='Risk-Free Rate')
@param.int('arch_lag', default=1, min=1, title='ARCH Lag')
@plot.line('Standard Deviation', color=color.YELLOW)
@plot.line('Sharpe Ratio', color=color.BLUE)
@plot.line('ARCH Volatility', color=color.RED)
def Main(self, stddev_length, sma_length, risk_free_rate, arch_lag):
    # Calculate Standard Deviation
    stddev = StdDev.new(self.close, stddev_length)[0]

    # Calculate Sharpe Ratio
    returns = MutSeriesF.new(0)
    for i in range(1, sma_length + 1):
        returns[0] += (self.close[i - 1] - self.close[i]) / self.close[i]
    avg_returns = returns[0] / sma_length
    excess_returns = avg_returns - risk_free_rate
    sharpe_ratio = excess_returns / stddev if stddev != 0 else 0

    arch_volatility = None  # This will cause a type error
    
    mean_return = Sma.new(self.close, sma_length)[0]
    for i in range(arch_lag):
        arch_volatility[0] += (self.close[i] - mean_return) ** 2
    arch_volatility[0] = math.sqrt(arch_volatility[0] / arch_lag)

    return (
        plot.Line(stddev),
        plot.Line(sharpe_ratio),
        plot.Line(arch_volatility[0])
    )

The returns variable uses MutSeriesF.new(0), which works. I tried mimicking this for arch_volatility but wasn’t sure how to adapt it for the loop logic.

Question: How do I properly initialize arch_volatility variable to avoid that error?

本文标签: indieHow to Handle MutSeriesF Initialization and Optional TypesStack Overflow