Spaces:
Paused
Paused
Tonic commited on
Commit ·
165a173
1
Parent(s): 1c92324
improves error handling by improving none value error handling
Browse files
app.py
CHANGED
|
@@ -142,6 +142,13 @@ def get_historical_data(symbol: str, timeframe: str = "1d", lookback_days: int =
|
|
| 142 |
if df.empty:
|
| 143 |
raise Exception(f"No data available for {symbol} in {timeframe} timeframe")
|
| 144 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
# Get additional info for structured products with retry mechanism
|
| 146 |
def fetch_info():
|
| 147 |
info = ticker.info
|
|
@@ -151,17 +158,17 @@ def get_historical_data(symbol: str, timeframe: str = "1d", lookback_days: int =
|
|
| 151 |
|
| 152 |
try:
|
| 153 |
info = retry_yfinance_request(fetch_info)
|
| 154 |
-
df['Market_Cap'] = info.get('marketCap',
|
| 155 |
-
df['Sector'] = info.get('sector',
|
| 156 |
-
df['Industry'] = info.get('industry',
|
| 157 |
-
df['Dividend_Yield'] = info.get('dividendYield',
|
| 158 |
except Exception as e:
|
| 159 |
print(f"Warning: Could not fetch company info for {symbol}: {str(e)}")
|
| 160 |
# Set default values for missing info
|
| 161 |
-
df['Market_Cap'] =
|
| 162 |
-
df['Sector'] =
|
| 163 |
-
df['Industry'] =
|
| 164 |
-
df['Dividend_Yield'] =
|
| 165 |
|
| 166 |
# Calculate technical indicators with adjusted windows based on timeframe
|
| 167 |
if timeframe == "1d":
|
|
@@ -202,7 +209,7 @@ def get_historical_data(symbol: str, timeframe: str = "1d", lookback_days: int =
|
|
| 202 |
df['Avg_Daily_Volume'] = df['Volume'].rolling(window=vol_window, min_periods=1).mean()
|
| 203 |
df['Volume_Volatility'] = df['Volume'].rolling(window=vol_window, min_periods=1).std()
|
| 204 |
|
| 205 |
-
# Fill NaN values using forward fill then backward fill
|
| 206 |
df = df.ffill().bfill()
|
| 207 |
|
| 208 |
# Ensure we have enough data points
|
|
@@ -222,6 +229,9 @@ def get_historical_data(symbol: str, timeframe: str = "1d", lookback_days: int =
|
|
| 222 |
if len(df) < 2:
|
| 223 |
raise Exception(f"Insufficient data points for {symbol} in {timeframe} timeframe")
|
| 224 |
|
|
|
|
|
|
|
|
|
|
| 225 |
return df
|
| 226 |
|
| 227 |
except Exception as e:
|
|
@@ -229,6 +239,8 @@ def get_historical_data(symbol: str, timeframe: str = "1d", lookback_days: int =
|
|
| 229 |
|
| 230 |
def calculate_rsi(prices: pd.Series, period: int = 14) -> pd.Series:
|
| 231 |
"""Calculate Relative Strength Index"""
|
|
|
|
|
|
|
| 232 |
delta = prices.diff()
|
| 233 |
gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
|
| 234 |
loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
|
|
@@ -237,6 +249,8 @@ def calculate_rsi(prices: pd.Series, period: int = 14) -> pd.Series:
|
|
| 237 |
|
| 238 |
def calculate_macd(prices: pd.Series, fast: int = 12, slow: int = 26, signal: int = 9) -> Tuple[pd.Series, pd.Series]:
|
| 239 |
"""Calculate MACD and Signal line"""
|
|
|
|
|
|
|
| 240 |
exp1 = prices.ewm(span=fast, adjust=False).mean()
|
| 241 |
exp2 = prices.ewm(span=slow, adjust=False).mean()
|
| 242 |
macd = exp1 - exp2
|
|
@@ -245,6 +259,8 @@ def calculate_macd(prices: pd.Series, fast: int = 12, slow: int = 26, signal: in
|
|
| 245 |
|
| 246 |
def calculate_bollinger_bands(prices: pd.Series, period: int = 20, std_dev: int = 2) -> Tuple[pd.Series, pd.Series, pd.Series]:
|
| 247 |
"""Calculate Bollinger Bands"""
|
|
|
|
|
|
|
| 248 |
middle_band = prices.rolling(window=period).mean()
|
| 249 |
std = prices.rolling(window=period).std()
|
| 250 |
upper_band = middle_band + (std * std_dev)
|
|
|
|
| 142 |
if df.empty:
|
| 143 |
raise Exception(f"No data available for {symbol} in {timeframe} timeframe")
|
| 144 |
|
| 145 |
+
# Ensure all required columns are present and numeric
|
| 146 |
+
required_columns = ['Open', 'High', 'Low', 'Close', 'Volume']
|
| 147 |
+
for col in required_columns:
|
| 148 |
+
if col not in df.columns:
|
| 149 |
+
raise Exception(f"Missing required column: {col}")
|
| 150 |
+
df[col] = pd.to_numeric(df[col], errors='coerce')
|
| 151 |
+
|
| 152 |
# Get additional info for structured products with retry mechanism
|
| 153 |
def fetch_info():
|
| 154 |
info = ticker.info
|
|
|
|
| 158 |
|
| 159 |
try:
|
| 160 |
info = retry_yfinance_request(fetch_info)
|
| 161 |
+
df['Market_Cap'] = float(info.get('marketCap', 0))
|
| 162 |
+
df['Sector'] = info.get('sector', 'Unknown')
|
| 163 |
+
df['Industry'] = info.get('industry', 'Unknown')
|
| 164 |
+
df['Dividend_Yield'] = float(info.get('dividendYield', 0))
|
| 165 |
except Exception as e:
|
| 166 |
print(f"Warning: Could not fetch company info for {symbol}: {str(e)}")
|
| 167 |
# Set default values for missing info
|
| 168 |
+
df['Market_Cap'] = 0.0
|
| 169 |
+
df['Sector'] = 'Unknown'
|
| 170 |
+
df['Industry'] = 'Unknown'
|
| 171 |
+
df['Dividend_Yield'] = 0.0
|
| 172 |
|
| 173 |
# Calculate technical indicators with adjusted windows based on timeframe
|
| 174 |
if timeframe == "1d":
|
|
|
|
| 209 |
df['Avg_Daily_Volume'] = df['Volume'].rolling(window=vol_window, min_periods=1).mean()
|
| 210 |
df['Volume_Volatility'] = df['Volume'].rolling(window=vol_window, min_periods=1).std()
|
| 211 |
|
| 212 |
+
# Fill NaN values using forward fill then backward fill
|
| 213 |
df = df.ffill().bfill()
|
| 214 |
|
| 215 |
# Ensure we have enough data points
|
|
|
|
| 229 |
if len(df) < 2:
|
| 230 |
raise Exception(f"Insufficient data points for {symbol} in {timeframe} timeframe")
|
| 231 |
|
| 232 |
+
# Final check for any remaining None values
|
| 233 |
+
df = df.fillna(0)
|
| 234 |
+
|
| 235 |
return df
|
| 236 |
|
| 237 |
except Exception as e:
|
|
|
|
| 239 |
|
| 240 |
def calculate_rsi(prices: pd.Series, period: int = 14) -> pd.Series:
|
| 241 |
"""Calculate Relative Strength Index"""
|
| 242 |
+
# Handle None values by forward filling
|
| 243 |
+
prices = prices.fillna(method='ffill').fillna(method='bfill')
|
| 244 |
delta = prices.diff()
|
| 245 |
gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
|
| 246 |
loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
|
|
|
|
| 249 |
|
| 250 |
def calculate_macd(prices: pd.Series, fast: int = 12, slow: int = 26, signal: int = 9) -> Tuple[pd.Series, pd.Series]:
|
| 251 |
"""Calculate MACD and Signal line"""
|
| 252 |
+
# Handle None values by forward filling
|
| 253 |
+
prices = prices.fillna(method='ffill').fillna(method='bfill')
|
| 254 |
exp1 = prices.ewm(span=fast, adjust=False).mean()
|
| 255 |
exp2 = prices.ewm(span=slow, adjust=False).mean()
|
| 256 |
macd = exp1 - exp2
|
|
|
|
| 259 |
|
| 260 |
def calculate_bollinger_bands(prices: pd.Series, period: int = 20, std_dev: int = 2) -> Tuple[pd.Series, pd.Series, pd.Series]:
|
| 261 |
"""Calculate Bollinger Bands"""
|
| 262 |
+
# Handle None values by forward filling
|
| 263 |
+
prices = prices.fillna(method='ffill').fillna(method='bfill')
|
| 264 |
middle_band = prices.rolling(window=period).mean()
|
| 265 |
std = prices.rolling(window=period).std()
|
| 266 |
upper_band = middle_band + (std * std_dev)
|