forked from williamliu91/rss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnomalies.py
226 lines (187 loc) · 7.62 KB
/
Anomalies.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import streamlit as st
import pandas as pd
import yfinance as yf
import numpy as np
import plotly.graph_objects as go
from datetime import datetime, timedelta
import feedparser
# Function to fetch data based on the selected period and stock symbol
def fetch_data(period, stock_symbol):
end_date = datetime.now()
if period == "1 Year":
start_date = end_date - timedelta(days=365)
elif period == "6 Months":
start_date = end_date - timedelta(days=183)
elif period == "3 Months":
start_date = end_date - timedelta(days=91)
else:
st.error("Invalid period selected.")
return pd.DataFrame() # Return empty DataFrame
try:
data = yf.download(stock_symbol, start=start_date, end=end_date)
if data.empty:
st.error(f"No data returned for ticker {stock_symbol}. Please check the ticker symbol.")
return data
except Exception as e:
st.error(f"Error fetching data from Yahoo Finance: {e}")
return pd.DataFrame() # Return empty DataFrame
# Function to calculate support and resistance levels
def calculate_support_resistance(data, window=20):
if 'Low' not in data.columns or 'High' not in data.columns:
st.error("Data does not contain required columns for support and resistance calculation.")
return None, None
if len(data) < window:
st.error("Not enough data to calculate support and resistance.")
return None, None
try:
data['Support'] = data['Low'].rolling(window=window).min()
data['Resistance'] = data['High'].rolling(window=window).max()
latest_support = data['Support'].dropna().iloc[-1] if not data['Support'].dropna().empty else None
latest_resistance = data['Resistance'].dropna().iloc[-1] if not data['Resistance'].dropna().empty else None
if latest_support is None or latest_resistance is None:
st.error("Failed to retrieve latest support or resistance values.")
return latest_support, latest_resistance
except Exception as e:
st.error(f"Error calculating support and resistance: {e}")
return None, None
# Function to fetch stock news using RSS feed
def fetch_stock_news(stock_symbol):
url = "https://finance.yahoo.com/rss/headline?s=" + stock_symbol
try:
feed = feedparser.parse(url)
articles = []
for entry in feed.entries:
articles.append({
'title': entry.title,
'publishedAt': entry.published,
'url': entry.link
})
return articles
except Exception as e:
st.error(f"Error fetching news from RSS feed: {e}")
return []
# Streamlit app
def main():
st.title("Stock Analysis with News")
# Sidebar for user input
st.sidebar.header("Settings")
stock_symbols = [
"AAPL", # Apple
"GOOGL", # Alphabet (Google)
"MSFT", # Microsoft
"AMZN", # Amazon
"TSLA", # Tesla
"META", # Meta Platforms (Facebook)
"NFLX", # Netflix
"NVDA", # NVIDIA
"INTC", # Intel
"AMD" # AMD
]
stock_symbol = st.sidebar.selectbox("Select Stock Symbol", stock_symbols)
period = st.sidebar.selectbox("Select Time Period", ["1 Year", "6 Months", "3 Months"])
# Fetch data based on selected period and stock symbol
data = fetch_data(period, stock_symbol)
if data.empty:
st.error("Failed to retrieve data. Please try again.")
return
# Calculate daily returns
close_data = data['Close']
data_returns = close_data.pct_change().dropna()
# Define Lorentzian distance function
def lorentzian_distance(x, y):
return np.log(1 + (x - y)**2)
# Compute Lorentzian distances between consecutive returns
if len(data_returns) < 2:
st.warning("Not enough data to compute Lorentzian distances.")
lorentzian_distances = np.array([])
else:
lorentzian_distances = [lorentzian_distance(data_returns[i], data_returns[i + 1]) for i in range(len(data_returns) - 1)]
lorentzian_distances = np.array(lorentzian_distances)
# Define a threshold to identify anomalies
if len(lorentzian_distances) > 0:
threshold = lorentzian_distances.mean() + 2 * lorentzian_distances.std()
anomalies = lorentzian_distances > threshold
anomaly_indices = np.where(anomalies)[0]
anomaly_dates = data_returns.index[anomaly_indices]
else:
threshold = None
anomaly_dates = []
# Prepare the data for candlestick chart
data['Anomalies'] = np.where(data.index.isin(anomaly_dates), data['Close'], np.nan)
# Calculate support and resistance levels
latest_support, latest_resistance = calculate_support_resistance(data)
if latest_support is None or latest_resistance is None:
st.error("Failed to calculate support and resistance levels.")
return
# Create candlestick chart
fig = go.Figure()
# Add candlestick trace
fig.add_trace(go.Candlestick(
x=data.index,
open=data['Open'],
high=data['High'],
low=data['Low'],
close=data['Close'],
name='Candlestick'
))
# Add support and resistance lines
fig.add_trace(go.Scatter(
x=data.index,
y=[latest_support] * len(data),
mode='lines',
name='Support',
line=dict(color='green', width=2, dash='dash')
))
fig.add_trace(go.Scatter(
x=data.index,
y=[latest_resistance] * len(data),
mode='lines',
name='Resistance',
line=dict(color='blue', width=2, dash='dash')
))
# Add anomalies as scatter points
fig.add_trace(go.Scatter(
x=data.index,
y=data['Anomalies'],
mode='markers',
name='Anomalies',
marker=dict(color='yellow', size=10, symbol='x')
))
# Update layout
fig.update_layout(
title=f'{stock_symbol} Stock Price with Anomalies, Support, and Resistance ({period})',
xaxis_title='Date',
yaxis_title='Stock Price',
xaxis_rangeslider_visible=False, # Hide range slider
xaxis_tickformat='%b %Y', # Format x-axis to show month and year
)
# Display the chart
st.plotly_chart(fig)
# News section
st.header(f"Recent {stock_symbol} News")
# Fetch and display news
news_items = fetch_stock_news(stock_symbol)
if not news_items:
st.write("No news found.")
return
for item in news_items:
st.subheader(item['title'])
st.write(f"Published: {item['publishedAt']}")
st.write(f"[Read more]({item['url']})")
st.write("---")
# Predict the next day's return
st.header("Prediction")
def predict_next_return(data_returns, lorentzian_distances):
if len(data_returns) < 2:
st.warning("Not enough data to predict next day's return.")
return 0
recent_distance = lorentzian_distance(data_returns[-2], data_returns[-1])
if threshold and recent_distance > threshold:
st.warning("Anomaly detected. Predicted return may be highly volatile.")
else:
st.info("No anomaly detected. Predicted return is based on historical average.")
return data_returns.mean()
predicted_return = predict_next_return(data_returns, lorentzian_distances)
st.write(f"Predicted return for the next day: {predicted_return:.2f}%")
if __name__ == "__main__":
main()