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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
import yfinance as yf
|
| 4 |
+
import os
|
| 5 |
+
import finnhub
|
| 6 |
+
from twelvedata import TDClient
|
| 7 |
+
try:
|
| 8 |
+
import talib as ta
|
| 9 |
+
except ImportError:
|
| 10 |
+
ta = None
|
| 11 |
+
from datetime import datetime, timedelta
|
| 12 |
+
from newsapi import NewsApiClient
|
| 13 |
+
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
| 14 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 15 |
+
from alpha_vantage.timeseries import TimeSeries
|
| 16 |
+
import time
|
| 17 |
+
import logging
|
| 18 |
+
import requests
|
| 19 |
+
|
| 20 |
+
# Configure logging
|
| 21 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 22 |
+
|
| 23 |
+
def print_log(message, level='INFO'):
|
| 24 |
+
if level == 'INFO':
|
| 25 |
+
logging.info(message)
|
| 26 |
+
elif level == 'WARNING':
|
| 27 |
+
logging.warning(message)
|
| 28 |
+
elif level == 'ERROR':
|
| 29 |
+
logging.error(message)
|
| 30 |
+
else:
|
| 31 |
+
logging.debug(message)
|
| 32 |
+
|
| 33 |
+
analyzer = SentimentIntensityAnalyzer()
|
| 34 |
+
|
| 35 |
+
def load_data_finnhub(ticker, start, end, interval, api_key):
|
| 36 |
+
print_log(f"Fetching data for {ticker} from Finnhub")
|
| 37 |
+
try:
|
| 38 |
+
if not api_key:
|
| 39 |
+
raise ValueError("Finnhub API key is required.")
|
| 40 |
+
finnhub_client = finnhub.Client(api_key=api_key)
|
| 41 |
+
start_ts = int(time.mktime(pd.to_datetime(start).timetuple()))
|
| 42 |
+
end_ts = int(time.mktime(pd.to_datetime(end).timetuple()))
|
| 43 |
+
|
| 44 |
+
# Finnhub interval mapping
|
| 45 |
+
finnhub_interval_map = {
|
| 46 |
+
"1m": "1", "5m": "5", "15m": "15", "30m": "30", "60m": "60",
|
| 47 |
+
"1h": "60", "1d": "D", "1wk": "W", "1mo": "M"
|
| 48 |
+
}
|
| 49 |
+
fh_interval = finnhub_interval_map.get(interval, "D")
|
| 50 |
+
|
| 51 |
+
res = finnhub_client.stock_candles(ticker, fh_interval, start_ts, end_ts)
|
| 52 |
+
if res['s'] == 'no_data':
|
| 53 |
+
raise ValueError(f"No data for {ticker} from Finnhub")
|
| 54 |
+
df = pd.DataFrame(res)
|
| 55 |
+
df['Date'] = pd.to_datetime(df['t'], unit='s')
|
| 56 |
+
df = df.rename(columns={'o': 'Open', 'h': 'High', 'l': 'Low', 'c': 'value', 'v': 'Volume'})
|
| 57 |
+
df = df.set_index('Date')
|
| 58 |
+
df = df[['Open', 'High', 'Low', 'value', 'Volume']]
|
| 59 |
+
return df
|
| 60 |
+
except Exception as e:
|
| 61 |
+
print_log(f"Error in load_data_finnhub for {ticker}: {str(e)}", 'ERROR')
|
| 62 |
+
raise ValueError(f"Failed to load data for {ticker} from Finnhub: {str(e)}")
|
| 63 |
+
|
| 64 |
+
def load_data_twelvedata(ticker, start, end, interval, api_key):
|
| 65 |
+
print_log(f"Fetching data for {ticker} from Twelve Data")
|
| 66 |
+
try:
|
| 67 |
+
if not api_key:
|
| 68 |
+
raise ValueError("Twelve Data API key is required.")
|
| 69 |
+
td = TDClient(apikey=api_key)
|
| 70 |
+
|
| 71 |
+
# Twelve Data interval mapping
|
| 72 |
+
twelvedata_interval_map = {
|
| 73 |
+
"1m": "1min", "5m": "5min", "15m": "15min", "30m": "30min", "60m": "1h",
|
| 74 |
+
"1h": "1h", "1d": "1day", "1wk": "1week", "1mo": "1month"
|
| 75 |
+
}
|
| 76 |
+
td_interval = twelvedata_interval_map.get(interval, "1day")
|
| 77 |
+
|
| 78 |
+
ts = td.time_series(symbol=ticker, interval=td_interval, start_date=start, end_date=end, outputsize=5000)
|
| 79 |
+
df = ts.as_pandas()
|
| 80 |
+
if df is None or df.empty:
|
| 81 |
+
raise ValueError(f"No data for {ticker} from Twelve Data")
|
| 82 |
+
df = df.rename(columns={'close': 'value', 'open': 'Open', 'high': 'High', 'low': 'Low', 'volume': 'Volume'})
|
| 83 |
+
df.index.name = 'Date'
|
| 84 |
+
return df
|
| 85 |
+
except Exception as e:
|
| 86 |
+
print_log(f"Error in load_data_twelvedata for {ticker}: {str(e)}", 'ERROR')
|
| 87 |
+
raise ValueError(f"Failed to load data for {ticker} from Twelve Data: {str(e)}")
|
| 88 |
+
|
| 89 |
+
def load_data(data_src='yahoo', ticker='AAPL', start='2020-01-01', end='2023-01-01', interval='1d', file_upload=None, alpha_api_key=None, finnhub_api_key=None, twelvedata_api_key=None):
|
| 90 |
+
print_log(f"Loading data: source={data_src}, ticker={ticker}, start={start}, end={end}, interval={interval}, file_upload={'set' if file_upload else 'unset'}, alpha_api_key={'set' if alpha_api_key else 'unset'}, finnhub_api_key={'set' if finnhub_api_key else 'unset'}, twelvedata_api_key={'set' if twelvedata_api_key else 'unset'}")
|
| 91 |
+
|
| 92 |
+
start_date = pd.to_datetime(start)
|
| 93 |
+
end_date = pd.to_datetime(end)
|
| 94 |
+
if start_date >= end_date:
|
| 95 |
+
raise ValueError(f"Start date {start} must be before end date {end}")
|
| 96 |
+
if end_date > datetime.now():
|
| 97 |
+
print_log(f"End date {end} is in the future. Using current date as end date.", 'WARNING')
|
| 98 |
+
end_date = datetime.now()
|
| 99 |
+
|
| 100 |
+
df = pd.DataFrame()
|
| 101 |
+
|
| 102 |
+
if data_src == 'csv' and file_upload:
|
| 103 |
+
try:
|
| 104 |
+
file_path = getattr(file_upload, 'name', file_upload)
|
| 105 |
+
print_log(f"Loading CSV from {file_path}")
|
| 106 |
+
df = pd.read_csv(file_path)
|
| 107 |
+
if 'Date' not in df.columns:
|
| 108 |
+
raise ValueError("CSV must contain a 'Date' column")
|
| 109 |
+
df['Date'] = pd.to_datetime(df['Date']).dt.tz_localize(None)
|
| 110 |
+
df = df.set_index('Date')
|
| 111 |
+
if 'Close' not in df.columns and 'value' not in df.columns:
|
| 112 |
+
raise ValueError("CSV must contain 'Close' or 'value' column")
|
| 113 |
+
if 'Close' in df.columns:
|
| 114 |
+
df = df.rename(columns={'Close': 'value'})
|
| 115 |
+
if df.empty:
|
| 116 |
+
raise ValueError(f"CSV data is empty for {ticker}")
|
| 117 |
+
if df['value'].isna().all():
|
| 118 |
+
raise ValueError(f"CSV 'value' column contains only NaNs for {ticker}")
|
| 119 |
+
except Exception as e:
|
| 120 |
+
print_log(f"Failed to load CSV {file_path}: {str(e)}", 'ERROR')
|
| 121 |
+
raise ValueError(f"Failed to load CSV: {str(e)}")
|
| 122 |
+
elif data_src == 'yahoo':
|
| 123 |
+
print_log(f"Fetching data for {ticker} from Yahoo Finance")
|
| 124 |
+
try:
|
| 125 |
+
# Adjust start_date for yfinance intraday limitations
|
| 126 |
+
if interval in ["1m"]:
|
| 127 |
+
max_days = 7
|
| 128 |
+
elif interval in ["2m", "5m", "15m", "30m", "60m", "90m", "1h"]:
|
| 129 |
+
max_days = 60
|
| 130 |
+
else:
|
| 131 |
+
max_days = None
|
| 132 |
+
|
| 133 |
+
if max_days:
|
| 134 |
+
adjusted_end_date = end_date + timedelta(days=1) # yfinance end date is exclusive
|
| 135 |
+
adjusted_start_date = adjusted_end_date - timedelta(days=max_days)
|
| 136 |
+
if start_date < adjusted_start_date:
|
| 137 |
+
print_log(f"Adjusting start date for {interval} interval from {start_date.strftime('%Y-%m-%d')} to {adjusted_start_date.strftime('%Y-%m-%d')} due to yfinance limitations.", 'WARNING')
|
| 138 |
+
start_date = adjusted_start_date
|
| 139 |
+
|
| 140 |
+
df = yf.download(ticker, start=start_date, end=end_date, interval=interval, progress=False, auto_adjust=False)
|
| 141 |
+
|
| 142 |
+
if isinstance(df.columns, pd.MultiIndex):
|
| 143 |
+
df.columns = df.columns.droplevel(1)
|
| 144 |
+
if df.empty:
|
| 145 |
+
raise ValueError(f"No data returned from Yahoo Finance for {ticker}")
|
| 146 |
+
if 'Close' not in df.columns:
|
| 147 |
+
raise ValueError(f"Yahoo Finance data missing 'Close' column for {ticker}")
|
| 148 |
+
df = df.rename(columns={'Close': 'value'})
|
| 149 |
+
# The index is already datetime, no need to create a 'Date' column and then reset
|
| 150 |
+
if df['value'].isna().all():
|
| 151 |
+
raise ValueError(f"Yahoo Finance 'value' column contains only NaNs for {ticker}")
|
| 152 |
+
if df['value'].empty:
|
| 153 |
+
raise ValueError(f"Yahoo Finance 'value' column is empty for {ticker}")
|
| 154 |
+
except Exception as e:
|
| 155 |
+
print_log(f"Yahoo Finance failed for {ticker}: {str(e)}", 'ERROR')
|
| 156 |
+
raise ValueError(f"Yahoo Finance failed for {ticker}: {str(e)}")
|
| 157 |
+
elif data_src == 'alpha_vantage' and alpha_api_key:
|
| 158 |
+
print_log(f"Attempting Alpha Vantage for {ticker}, interval {interval}")
|
| 159 |
+
try:
|
| 160 |
+
ts = TimeSeries(key=alpha_api_key, output_format='pandas')
|
| 161 |
+
# Alpha Vantage interval mapping
|
| 162 |
+
av_interval_map = {
|
| 163 |
+
"1m": "1min", "5m": "5min", "15m": "15min", "30m": "30min", "60m": "60min",
|
| 164 |
+
"1h": "60min"
|
| 165 |
+
}
|
| 166 |
+
av_interval = av_interval_map.get(interval)
|
| 167 |
+
|
| 168 |
+
if av_interval:
|
| 169 |
+
df_av, _ = ts.get_intraday(symbol=ticker, interval=av_interval, outputsize='full')
|
| 170 |
+
elif interval == "1d":
|
| 171 |
+
df_av, _ = ts.get_daily(symbol=ticker, outputsize='full')
|
| 172 |
+
elif interval == "1wk":
|
| 173 |
+
df_av, _ = ts.get_weekly(symbol=ticker)
|
| 174 |
+
elif interval == "1mo":
|
| 175 |
+
df_av, _ = ts.get_monthly(symbol=ticker)
|
| 176 |
+
else:
|
| 177 |
+
raise ValueError(f"Unsupported interval for Alpha Vantage: {interval}")
|
| 178 |
+
|
| 179 |
+
if df_av.empty:
|
| 180 |
+
raise ValueError(f"No data returned from Alpha Vantage for {ticker}")
|
| 181 |
+
|
| 182 |
+
# Standardize column names
|
| 183 |
+
df_av = df_av.rename(columns={
|
| 184 |
+
'4. close': 'value', '1. open': 'Open', '2. high': 'High',
|
| 185 |
+
'3. low': 'Low', '5. volume': 'Volume'
|
| 186 |
+
})
|
| 187 |
+
# For daily/weekly/monthly, index is already datetime. For intraday, it's also datetime.
|
| 188 |
+
# Ensure consistent column order and index type
|
| 189 |
+
df = df_av[['Open', 'High', 'Low', 'value', 'Volume']]
|
| 190 |
+
df.index = pd.to_datetime(df.index)
|
| 191 |
+
df = df.sort_index()
|
| 192 |
+
|
| 193 |
+
if df['value'].isna().all():
|
| 194 |
+
raise ValueError(f"Alpha Vantage 'value' column contains only NaNs for {ticker}")
|
| 195 |
+
if df['value'].empty:
|
| 196 |
+
raise ValueError(f"Alpha Vantage 'value' column is empty for {ticker}")
|
| 197 |
+
print_log(f"Data loaded for {ticker} from Alpha Vantage with date range: {df.index.min()} to {df.index.max()}, shape: {df.shape}")
|
| 198 |
+
|
| 199 |
+
except Exception as e:
|
| 200 |
+
print_log(f"Alpha Vantage failed for {ticker}: {str(e)}", 'ERROR')
|
| 201 |
+
raise ValueError(f"Alpha Vantage failed for {ticker}: {str(e)}")
|
| 202 |
+
elif data_src == 'finnhub' and finnhub_api_key:
|
| 203 |
+
df = load_data_finnhub(ticker, start, end, interval, finnhub_api_key)
|
| 204 |
+
elif data_src == 'twelvedata' and twelvedata_api_key:
|
| 205 |
+
df = load_data_twelvedata(ticker, start, end, interval, twelvedata_api_key)
|
| 206 |
+
|
| 207 |
+
if df.empty:
|
| 208 |
+
raise ValueError(f"No data loaded for {ticker} from {data_src}")
|
| 209 |
+
|
| 210 |
+
# Ensure index is DatetimeIndex and sorted
|
| 211 |
+
if not isinstance(df.index, pd.DatetimeIndex):
|
| 212 |
+
df.index = pd.to_datetime(df.index)
|
| 213 |
+
df = df.sort_index()
|
| 214 |
+
|
| 215 |
+
required_cols = ['Open', 'High', 'Low', 'value', 'Volume']
|
| 216 |
+
for col in required_cols:
|
| 217 |
+
if col not in df.columns:
|
| 218 |
+
df[col] = np.nan
|
| 219 |
+
|
| 220 |
+
if 'value' not in df.columns:
|
| 221 |
+
raise ValueError(f"Target column 'value' is missing for {ticker}")
|
| 222 |
+
if df['value'].isna().all():
|
| 223 |
+
raise ValueError(f"Target column 'value' contains only NaNs for {ticker}")
|
| 224 |
+
if df['value'].empty:
|
| 225 |
+
raise ValueError(f"Target column 'value' is empty for {ticker}")
|
| 226 |
+
|
| 227 |
+
print_log(f"Data loaded for {ticker} with date range: {df.index.min()} to {df.index.max()}, shape: {df.shape}")
|
| 228 |
+
return df
|
| 229 |
+
|
| 230 |
+
def add_technical_indicators(df, selected_indicators):
|
| 231 |
+
try:
|
| 232 |
+
print_log(f"Starting add_technical_indicators with indicators: {selected_indicators}")
|
| 233 |
+
if df.empty:
|
| 234 |
+
print_log("DataFrame is empty, skipping technical indicator calculation.", "WARNING")
|
| 235 |
+
return df, []
|
| 236 |
+
|
| 237 |
+
for col in ['Open', 'High', 'Low', 'value', 'Volume']:
|
| 238 |
+
if col not in df.columns:
|
| 239 |
+
df[col] = np.nan
|
| 240 |
+
df[col] = pd.to_numeric(df[col], errors='coerce')
|
| 241 |
+
|
| 242 |
+
df.dropna(subset=['Open', 'High', 'Low', 'value', 'Volume'], inplace=True)
|
| 243 |
+
if df.empty:
|
| 244 |
+
print_log("DataFrame is empty after dropping NaNs for technical indicators.", "WARNING")
|
| 245 |
+
return df, []
|
| 246 |
+
|
| 247 |
+
if ta is None:
|
| 248 |
+
print_log("TA-Lib not available. Cannot compute indicators. Falling back to 'value'.", 'ERROR')
|
| 249 |
+
return df, []
|
| 250 |
+
|
| 251 |
+
close = df['value'].values
|
| 252 |
+
high = df['High'].values
|
| 253 |
+
low = df['Low'].values
|
| 254 |
+
volume = df['Volume'].values
|
| 255 |
+
open_ = df['Open'].values
|
| 256 |
+
|
| 257 |
+
indicator_map = {
|
| 258 |
+
'rsi': {'func': ta.RSI, 'inputs': ['close'], 'params': {'timeperiod': 14}, 'output': ['rsi_14']},
|
| 259 |
+
'macd': {'func': ta.MACD, 'inputs': ['close'], 'params': {'fastperiod': 12, 'slowperiod': 26, 'signalperiod': 9}, 'output': ['macd_12_26_9', 'macds_12_26_9', 'macdhist_12_26_9']},
|
| 260 |
+
'bbands': {'func': ta.BBANDS, 'inputs': ['close'], 'params': {'timeperiod': 20}, 'output': ['upperband_20', 'middleband_20', 'lowerband_20']},
|
| 261 |
+
'stoch': {'func': ta.STOCH, 'inputs': ['high', 'low', 'close'], 'params': {'fastk_period': 14, 'slowk_period': 3, 'slowd_period': 3}, 'output': ['slowk_14_3_3', 'slowd_14_3_3']},
|
| 262 |
+
'adx': {'func': ta.ADX, 'inputs': ['high', 'low', 'close'], 'params': {'timeperiod': 14}, 'output': ['adx_14']},
|
| 263 |
+
'atr': {'func': ta.ATR, 'inputs': ['high', 'low', 'close'], 'params': {'timeperiod': 14}, 'output': ['atr_14']},
|
| 264 |
+
'cci': {'func': ta.CCI, 'inputs': ['high', 'low', 'close'], 'params': {'timeperiod': 14}, 'output': ['cci_14']},
|
| 265 |
+
'ema': {'func': ta.EMA, 'inputs': ['close'], 'params': {'timeperiod': 14}, 'output': ['ema_14']},
|
| 266 |
+
'sma': {'func': ta.SMA, 'inputs': ['close'], 'params': {'timeperiod': 14}, 'output': ['sma_14']},
|
| 267 |
+
'mom': {'func': ta.MOM, 'inputs': ['close'], 'params': {'timeperiod': 10}, 'output': ['mom_10']},
|
| 268 |
+
'roc': {'func': ta.ROC, 'inputs': ['close'], 'params': {'timeperiod': 10}, 'output': ['roc_10']},
|
| 269 |
+
'willr': {'func': ta.WILLR, 'inputs': ['high', 'low', 'close'], 'params': {'timeperiod': 14}, 'output': ['willr_14']},
|
| 270 |
+
'ultosc': {'func': ta.ULTOSC, 'inputs': ['high', 'low', 'close'], 'params': {'timeperiod1': 7, 'timeperiod2': 14, 'timeperiod3': 28}, 'output': ['ultosc_7_14_28']},
|
| 271 |
+
'dx': {'func': ta.DX, 'inputs': ['high', 'low', 'close'], 'params': {'timeperiod': 14}, 'output': ['dx_14']},
|
| 272 |
+
'minus_di': {'func': ta.MINUS_DI, 'inputs': ['high', 'low', 'close'], 'params': {'timeperiod': 14}, 'output': ['minus_di_14']},
|
| 273 |
+
'plus_di': {'func': ta.PLUS_DI, 'inputs': ['high', 'low', 'close'], 'params': {'timeperiod': 14}, 'output': ['plus_di_14']},
|
| 274 |
+
'mfi': {'func': ta.MFI, 'inputs': ['high', 'low', 'close', 'volume'], 'params': {'timeperiod': 14}, 'output': ['mfi_14']},
|
| 275 |
+
'obv': {'func': ta.OBV, 'inputs': ['close', 'volume'], 'params': {}, 'output': ['obv']},
|
| 276 |
+
'ad': {'func': ta.AD, 'inputs': ['high', 'low', 'close', 'volume'], 'params': {}, 'output': ['ad']},
|
| 277 |
+
'adosc': {'func': ta.ADOSC, 'inputs': ['high', 'low', 'close', 'volume'], 'params': {'fastperiod': 3, 'slowperiod': 10}, 'output': ['adosc_3_10']},
|
| 278 |
+
'aroon': {'func': ta.AROON, 'inputs': ['high', 'low'], 'params': {'timeperiod': 14}, 'output': ['aroon_down_14', 'aroon_up_14']},
|
| 279 |
+
'aroonosc': {'func': ta.AROONOSC, 'inputs': ['high', 'low'], 'params': {'timeperiod': 14}, 'output': ['aroonosc_14']},
|
| 280 |
+
'bop': {'func': ta.BOP, 'inputs': ['open_', 'high', 'low', 'close'], 'params': {}, 'output': ['bop']},
|
| 281 |
+
'cmo': {'func': ta.CMO, 'inputs': ['close'], 'params': {'timeperiod': 14}, 'output': ['cmo_14']},
|
| 282 |
+
'dema': {'func': ta.DEMA, 'inputs': ['close'], 'params': {'timeperiod': 30}, 'output': ['dema_30']},
|
| 283 |
+
'kama': {'func': ta.KAMA, 'inputs': ['close'], 'params': {'timeperiod': 30}, 'output': ['kama_30']},
|
| 284 |
+
'ppo': {'func': ta.PPO, 'inputs': ['close'], 'params': {'fastperiod': 12, 'slowperiod': 26, 'matype': 0}, 'output': ['ppo_12_26_0']},
|
| 285 |
+
'rocp': {'func': ta.ROCP, 'inputs': ['close'], 'params': {'timeperiod': 10}, 'output': ['rocp_10']},
|
| 286 |
+
'rocr': {'func': ta.ROCR, 'inputs': ['close'], 'params': {'timeperiod': 10}, 'output': ['rocr_10']},
|
| 287 |
+
'rocr100': {'func': ta.ROCR100, 'inputs': ['close'], 'params': {'timeperiod': 10}, 'output': ['rocr100_10']},
|
| 288 |
+
'trix': {'func': ta.TRIX, 'inputs': ['close'], 'params': {'timeperiod': 14}, 'output': ['trix_14']},
|
| 289 |
+
'tsi': {'func': ta.TSI, 'inputs': ['close'], 'params': {'fastperiod': 13, 'slowperiod': 25}, 'output': ['tsi_13_25']},
|
| 290 |
+
'uo': {'func': ta.ULTOSC, 'inputs': ['high', 'low', 'close'], 'params': {'timeperiod1': 7, 'timeperiod2': 14, 'timeperiod3': 28}, 'output': ['ultosc_7_14_28']},
|
| 291 |
+
'willr': {'func': ta.WILLR, 'inputs': ['high', 'low', 'close'], 'params': {'timeperiod': 14}, 'output': ['willr_14']},
|
| 292 |
+
'wma': {'func': ta.WMA, 'inputs': ['close'], 'params': {'timeperiod': 30}, 'output': ['wma_30']},
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
added_features = []
|
| 296 |
+
for indicator_name in selected_indicators:
|
| 297 |
+
if indicator_name in indicator_map:
|
| 298 |
+
indicator_info = indicator_map[indicator_name]
|
| 299 |
+
func = indicator_info['func']
|
| 300 |
+
inputs = []
|
| 301 |
+
for input_name in indicator_info['inputs']:
|
| 302 |
+
if input_name == 'close':
|
| 303 |
+
inputs.append(close)
|
| 304 |
+
elif input_name == 'high':
|
| 305 |
+
inputs.append(high)
|
| 306 |
+
elif input_name == 'low':
|
| 307 |
+
inputs.append(low)
|
| 308 |
+
elif input_name == 'volume':
|
| 309 |
+
inputs.append(volume)
|
| 310 |
+
elif input_name == 'open_':
|
| 311 |
+
inputs.append(open_)
|
| 312 |
+
|
| 313 |
+
# Ensure inputs are numpy arrays and not empty
|
| 314 |
+
if not all(len(arr) > 0 for arr in inputs):
|
| 315 |
+
print_log(f"Skipping {indicator_name}: insufficient data for inputs.", "WARNING")
|
| 316 |
+
continue
|
| 317 |
+
|
| 318 |
+
try:
|
| 319 |
+
output_values = func(*inputs, **indicator_info['params'])
|
| 320 |
+
if not isinstance(output_values, tuple):
|
| 321 |
+
output_values = (output_values,)
|
| 322 |
+
|
| 323 |
+
for i, col_name in enumerate(indicator_info['output']):
|
| 324 |
+
df[col_name] = np.nan
|
| 325 |
+
# Ensure the output array matches the DataFrame length
|
| 326 |
+
if len(output_values[i]) == len(df):
|
| 327 |
+
df[col_name] = output_values[i]
|
| 328 |
+
else:
|
| 329 |
+
# Align output to DataFrame by padding with NaNs at the beginning
|
| 330 |
+
nan_padding = np.full(len(df) - len(output_values[i]), np.nan)
|
| 331 |
+
df[col_name] = np.concatenate((nan_padding, output_values[i]))
|
| 332 |
+
added_features.append(col_name)
|
| 333 |
+
except Exception as e:
|
| 334 |
+
print_log(f"Error calculating indicator {indicator_name}: {str(e)}", "ERROR")
|
| 335 |
+
else:
|
| 336 |
+
print_log(f"Unknown indicator: {indicator_name}", "WARNING")
|
| 337 |
+
|
| 338 |
+
df.dropna(inplace=True)
|
| 339 |
+
print_log(f"Finished add_technical_indicators. New features added: {added_features}")
|
| 340 |
+
return df, added_features
|
| 341 |
+
except Exception as e:
|
| 342 |
+
print_log(f"Error in add_technical_indicators: {str(e)}", 'ERROR')
|
| 343 |
+
return df, []
|
| 344 |
+
|
| 345 |
+
def add_sentiment(df, ticker, news_api_key, start_date, end_date):
|
| 346 |
+
try:
|
| 347 |
+
sentiment_text, sentiment_score = sentiment_analysis(ticker, start_date, end_date, news_api_key)
|
| 348 |
+
df['sentiment'] = sentiment_score if sentiment_score is not None else 0.0
|
| 349 |
+
return df, sentiment_text
|
| 350 |
+
except Exception as e:
|
| 351 |
+
print_log(f"Error adding sentiment: {str(e)}", 'ERROR')
|
| 352 |
+
df['sentiment'] = 0.0 # Default to neutral sentiment on error
|
| 353 |
+
return df, f"Error adding sentiment: {str(e)}"
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def sentiment_analysis(ticker, start_date, end_date, api_key):
|
| 357 |
+
try:
|
| 358 |
+
if not api_key:
|
| 359 |
+
print_log("News API key not provided for sentiment analysis.", 'WARNING')
|
| 360 |
+
return "No API key provided", None
|
| 361 |
+
newsapi = NewsApiClient(api_key=api_key)
|
| 362 |
+
start = pd.to_datetime(start_date)
|
| 363 |
+
end = pd.to_datetime(end_date)
|
| 364 |
+
articles = newsapi.get_everything(
|
| 365 |
+
q=ticker, from_param=start.strftime("%Y-%m-%d"), to=end.strftime("%Y-%m-%d"),
|
| 366 |
+
language='en', sort_by='relevancy'
|
| 367 |
+
)
|
| 368 |
+
sentiments = [analyzer.polarity_scores(article["title"])['compound'] for article in articles["articles"] if "title" in article and article["title"] is not None]
|
| 369 |
+
avg_sentiment = np.mean(sentiments) if sentiments else 0.0
|
| 370 |
+
sentiment_text = f"Average sentiment for {ticker}: {avg_sentiment:.2f}"
|
| 371 |
+
return sentiment_text, avg_sentiment
|
| 372 |
+
except Exception as e:
|
| 373 |
+
print_log(f"Sentiment analysis failed: {str(e)}", 'ERROR')
|
| 374 |
+
return f"Sentiment analysis failed: {str(e)}", None
|