Spaces:
Running
Running
Oviya
commited on
Commit
路
adb0a5a
1
Parent(s):
0137587
update analysestock
Browse files- analysestock.py +39 -9
- predictedchart.py +4 -4
analysestock.py
CHANGED
|
@@ -11,7 +11,6 @@ from pathlib import Path
|
|
| 11 |
from datetime import timedelta
|
| 12 |
from collections import OrderedDict
|
| 13 |
|
| 14 |
-
|
| 15 |
from rsistrategies import get_rsi_trade_signal
|
| 16 |
from macdstrategies import get_macd_trade_signal
|
| 17 |
from emastrategies import get_ema_trade_signal
|
|
@@ -59,6 +58,8 @@ MODEL_BUNDLE_PATH = (
|
|
| 59 |
Path(MODEL_BUNDLE_PATH).parent.mkdir(parents=True, exist_ok=True) # ensure writable dir when training
|
| 60 |
# --- end snippet ---
|
| 61 |
|
|
|
|
|
|
|
| 62 |
from predictedchart import run_stock_prediction
|
| 63 |
|
| 64 |
# ===================== TA scoring =====================
|
|
@@ -77,8 +78,24 @@ def calculate_technical_analysis_score(indicator_scores):
|
|
| 77 |
weight_values = list(indicator_weights.values())
|
| 78 |
weighted_score = sum(score * weight for score, weight in zip(indicator_scores, weight_values))
|
| 79 |
total_weight = sum(weight_values)
|
| 80 |
-
technical_analysis_score = (weighted_score / (total_weight * 100)) * 85
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
# ================== Pivot levels & trade ==================
|
| 84 |
def calculate_pivot_points(ticker, score, live_price, atr_period=14):
|
|
@@ -163,16 +180,22 @@ def calculate_pivot_points(ticker, score, live_price, atr_period=14):
|
|
| 163 |
|
| 164 |
# =================== Main: short-term swing ===================
|
| 165 |
def analysestock(ticker):
|
| 166 |
-
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
stock_data.columns = [col.lower() if isinstance(col, str) else col[0].lower() for col in stock_data.columns]
|
|
|
|
| 169 |
stockdetail = yf.Ticker(ticker)
|
| 170 |
company_name = stockdetail.info.get("longName", "Company name not found")
|
| 171 |
live_price = stockdetail.info["regularMarketPrice"]
|
| 172 |
price_change = stockdetail.info['regularMarketChange']
|
| 173 |
percentage_change = stockdetail.info['regularMarketChangePercent']
|
| 174 |
|
| 175 |
-
recentdays = stock_data.tail(
|
| 176 |
ohlc_data = []
|
| 177 |
for index, row in recentdays.iterrows():
|
| 178 |
ohlc_data.append({
|
|
@@ -215,7 +238,7 @@ def analysestock(ticker):
|
|
| 215 |
sr_trade_signal['sr_score']
|
| 216 |
]
|
| 217 |
|
| 218 |
-
overall_ta_score = calculate_technical_analysis_score(indicator_score)
|
| 219 |
|
| 220 |
#FA signals
|
| 221 |
|
|
@@ -233,8 +256,10 @@ def analysestock(ticker):
|
|
| 233 |
|
| 234 |
#overallscore
|
| 235 |
|
| 236 |
-
overall_fa_score = fundamental_analysis["overall_fa_score"]
|
| 237 |
overall_news_score = news_payload['overall_news_score']
|
|
|
|
|
|
|
| 238 |
combined_overall_score = overall_ta_score + overall_fa_score + overall_news_score
|
| 239 |
combined_overall_signal = np.where(combined_overall_score > 65, 'Buy',
|
| 240 |
np.where(combined_overall_score > 50, 'Neutral', 'DBuy'))
|
|
@@ -284,6 +309,8 @@ def analysestock(ticker):
|
|
| 284 |
response = {
|
| 285 |
"ticker": ticker,
|
| 286 |
"company_name": company_name,
|
|
|
|
|
|
|
| 287 |
"live_price": round(live_price, 2),
|
| 288 |
"price_change": round(price_change, 2),
|
| 289 |
"percentage_change": round(percentage_change, 2),
|
|
@@ -298,9 +325,12 @@ def analysestock(ticker):
|
|
| 298 |
"BB": bb_trade_signal['bollinger_signals'],
|
| 299 |
"PA_MS": priceaction_trade_signal['priceaction_signals'],
|
| 300 |
"final_trade_signal": final_trade_signal,
|
| 301 |
-
"overall_ta_score": round(overall_ta_score, 2),
|
|
|
|
| 302 |
"fundamental_analysis": fundamental_analysis,
|
| 303 |
"overall_fa_score": overall_fa_score,
|
|
|
|
|
|
|
| 304 |
"news_overall_score": overall_news_score,
|
| 305 |
"news": news_payload["items"],
|
| 306 |
"combined_overall_score": round(combined_overall_score, 2),
|
|
|
|
| 11 |
from datetime import timedelta
|
| 12 |
from collections import OrderedDict
|
| 13 |
|
|
|
|
| 14 |
from rsistrategies import get_rsi_trade_signal
|
| 15 |
from macdstrategies import get_macd_trade_signal
|
| 16 |
from emastrategies import get_ema_trade_signal
|
|
|
|
| 58 |
Path(MODEL_BUNDLE_PATH).parent.mkdir(parents=True, exist_ok=True) # ensure writable dir when training
|
| 59 |
# --- end snippet ---
|
| 60 |
|
| 61 |
+
|
| 62 |
+
|
| 63 |
from predictedchart import run_stock_prediction
|
| 64 |
|
| 65 |
# ===================== TA scoring =====================
|
|
|
|
| 78 |
weight_values = list(indicator_weights.values())
|
| 79 |
weighted_score = sum(score * weight for score, weight in zip(indicator_scores, weight_values))
|
| 80 |
total_weight = sum(weight_values)
|
| 81 |
+
technical_analysis_score = (weighted_score / (total_weight * 100)) * 85
|
| 82 |
+
overall_ta_signal_100 = np.where(
|
| 83 |
+
technical_analysis_score > 65, 'Buy',
|
| 84 |
+
np.where(technical_analysis_score > 40, 'Neutral', 'DBuy')
|
| 85 |
+
)
|
| 86 |
+
return technical_analysis_score, overall_ta_signal_100
|
| 87 |
+
|
| 88 |
+
def signal_from_score(score, max_points, buy_frac=0.65, neutral_frac=0.40):
|
| 89 |
+
|
| 90 |
+
buy_cutoff = buy_frac * max_points
|
| 91 |
+
neutral_cutoff = neutral_frac * max_points
|
| 92 |
+
|
| 93 |
+
if score > buy_cutoff:
|
| 94 |
+
return "Buy"
|
| 95 |
+
elif score > neutral_cutoff:
|
| 96 |
+
return "Neutral"
|
| 97 |
+
else:
|
| 98 |
+
return "DBuy"
|
| 99 |
|
| 100 |
# ================== Pivot levels & trade ==================
|
| 101 |
def calculate_pivot_points(ticker, score, live_price, atr_period=14):
|
|
|
|
| 180 |
|
| 181 |
# =================== Main: short-term swing ===================
|
| 182 |
def analysestock(ticker):
|
| 183 |
+
now = datetime.datetime.now()
|
| 184 |
+
formatted_datetime = now.strftime('%Y-%m-%d %H:%M:%S.%f')
|
| 185 |
+
|
| 186 |
+
threshold_time = now.replace(hour=17, minute=0, second=0, microsecond=0)
|
| 187 |
+
end_date = (now + datetime.timedelta(days=1)).strftime('%Y-%m-%d') if now >= threshold_time else now.strftime('%Y-%m-%d')
|
| 188 |
+
|
| 189 |
+
stock_data = yf.download(ticker, start="2023-01-01", end=end_date, interval="1d")
|
| 190 |
stock_data.columns = [col.lower() if isinstance(col, str) else col[0].lower() for col in stock_data.columns]
|
| 191 |
+
lasttradingdate = stock_data.index[-1].strftime('%d-%m-%Y')
|
| 192 |
stockdetail = yf.Ticker(ticker)
|
| 193 |
company_name = stockdetail.info.get("longName", "Company name not found")
|
| 194 |
live_price = stockdetail.info["regularMarketPrice"]
|
| 195 |
price_change = stockdetail.info['regularMarketChange']
|
| 196 |
percentage_change = stockdetail.info['regularMarketChangePercent']
|
| 197 |
|
| 198 |
+
recentdays = stock_data.tail(30)
|
| 199 |
ohlc_data = []
|
| 200 |
for index, row in recentdays.iterrows():
|
| 201 |
ohlc_data.append({
|
|
|
|
| 238 |
sr_trade_signal['sr_score']
|
| 239 |
]
|
| 240 |
|
| 241 |
+
overall_ta_score,overall_ta_signal = calculate_technical_analysis_score(indicator_score)
|
| 242 |
|
| 243 |
#FA signals
|
| 244 |
|
|
|
|
| 256 |
|
| 257 |
#overallscore
|
| 258 |
|
| 259 |
+
overall_fa_score = fundamental_analysis["overall_fa_score"]
|
| 260 |
overall_news_score = news_payload['overall_news_score']
|
| 261 |
+
overall_fa_signal = signal_from_score(overall_fa_score,15)
|
| 262 |
+
overall_news_signal = signal_from_score(overall_news_score,5)
|
| 263 |
combined_overall_score = overall_ta_score + overall_fa_score + overall_news_score
|
| 264 |
combined_overall_signal = np.where(combined_overall_score > 65, 'Buy',
|
| 265 |
np.where(combined_overall_score > 50, 'Neutral', 'DBuy'))
|
|
|
|
| 309 |
response = {
|
| 310 |
"ticker": ticker,
|
| 311 |
"company_name": company_name,
|
| 312 |
+
"lasttradingdate": lasttradingdate,
|
| 313 |
+
"currentdatetime": formatted_datetime,
|
| 314 |
"live_price": round(live_price, 2),
|
| 315 |
"price_change": round(price_change, 2),
|
| 316 |
"percentage_change": round(percentage_change, 2),
|
|
|
|
| 325 |
"BB": bb_trade_signal['bollinger_signals'],
|
| 326 |
"PA_MS": priceaction_trade_signal['priceaction_signals'],
|
| 327 |
"final_trade_signal": final_trade_signal,
|
| 328 |
+
"overall_ta_score": round(overall_ta_score, 2),
|
| 329 |
+
"overall_ta_signal": str(overall_ta_signal),
|
| 330 |
"fundamental_analysis": fundamental_analysis,
|
| 331 |
"overall_fa_score": overall_fa_score,
|
| 332 |
+
"overall_fa_signal": str(overall_fa_signal),
|
| 333 |
+
"overall_news_signal": str(overall_news_signal),
|
| 334 |
"news_overall_score": overall_news_score,
|
| 335 |
"news": news_payload["items"],
|
| 336 |
"combined_overall_score": round(combined_overall_score, 2),
|
predictedchart.py
CHANGED
|
@@ -8,9 +8,9 @@ import torch.nn as nn
|
|
| 8 |
from torch.utils.data import Dataset, DataLoader
|
| 9 |
|
| 10 |
# Step 1: Download data with TA indicators
|
| 11 |
-
def fetch_stock_data_with_indicators(ticker, start="2020-01-01", end="2025-09-
|
| 12 |
df = yf.download(ticker, start=start, end=end)
|
| 13 |
-
actualdata = yf.download(ticker, start=start, end="2025-09-
|
| 14 |
df = df[["Open", "High", "Low", "Close", "Volume"]]
|
| 15 |
close_prices = df['Close'].to_numpy().flatten()
|
| 16 |
low_prices = df['Low'].to_numpy().flatten()
|
|
@@ -90,7 +90,7 @@ def run_stock_prediction(ticker):
|
|
| 90 |
predictions = []
|
| 91 |
input_seq = scaled_data[-window_size:].copy() # shape: [20, features]
|
| 92 |
|
| 93 |
-
for i in range(
|
| 94 |
seq_tensor = torch.tensor(input_seq, dtype=torch.float32).unsqueeze(1) # [seq_len, 1, features]
|
| 95 |
|
| 96 |
with torch.no_grad():
|
|
@@ -110,7 +110,7 @@ def run_stock_prediction(ticker):
|
|
| 110 |
|
| 111 |
# Get the last date from the dataset
|
| 112 |
last_date = df.index[-1]
|
| 113 |
-
predicted_dates = pd.date_range(start=last_date + pd.Timedelta(days=1), periods=
|
| 114 |
|
| 115 |
|
| 116 |
prediction_results = pd.DataFrame({
|
|
|
|
| 8 |
from torch.utils.data import Dataset, DataLoader
|
| 9 |
|
| 10 |
# Step 1: Download data with TA indicators
|
| 11 |
+
def fetch_stock_data_with_indicators(ticker, start="2020-01-01", end="2025-09-10"):
|
| 12 |
df = yf.download(ticker, start=start, end=end)
|
| 13 |
+
actualdata = yf.download(ticker, start=start, end="2025-09-11")
|
| 14 |
df = df[["Open", "High", "Low", "Close", "Volume"]]
|
| 15 |
close_prices = df['Close'].to_numpy().flatten()
|
| 16 |
low_prices = df['Low'].to_numpy().flatten()
|
|
|
|
| 90 |
predictions = []
|
| 91 |
input_seq = scaled_data[-window_size:].copy() # shape: [20, features]
|
| 92 |
|
| 93 |
+
for i in range(30):
|
| 94 |
seq_tensor = torch.tensor(input_seq, dtype=torch.float32).unsqueeze(1) # [seq_len, 1, features]
|
| 95 |
|
| 96 |
with torch.no_grad():
|
|
|
|
| 110 |
|
| 111 |
# Get the last date from the dataset
|
| 112 |
last_date = df.index[-1]
|
| 113 |
+
predicted_dates = pd.date_range(start=last_date + pd.Timedelta(days=1), periods=30, freq='B') # Business days
|
| 114 |
|
| 115 |
|
| 116 |
prediction_results = pd.DataFrame({
|