-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfinancial_data.py
50 lines (38 loc) · 1.47 KB
/
financial_data.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
import yfinance as yf
import requests
import os
from dotenv import load_dotenv
import pandas as pd
import streamlit as st
load_dotenv()
ALPHA_VANTAGE_API_KEY = os.getenv("ALPHA_VANTAGE_API_KEY")
def get_financial_news():
try:
url = f'https://www.alphavantage.co/query?function=NEWS_SENTIMENT&apikey={ALPHA_VANTAGE_API_KEY}'
response = requests.get(url)
response.raise_for_status()
data = response.json()
return data.get('feed', [])[:5]
except requests.RequestException as e:
st.error(f"Error fetching financial news: {e}")
return []
def get_stock_data(ticker, period="1y"):
try:
stock = yf.Ticker(ticker)
data = stock.history(period=period)
print(f"yfinance: Data for {ticker}: {data.head()}")
return data, stock.info
except Exception as e:
st.error(f"Error fetching stock data using yfinance: {e}")
return pd.DataFrame(), {}
def get_stock_value(ticker, quantity):
try:
stock = yf.Ticker(ticker)
current_price = stock.info.get('regularMarketPrice')
print(f"yfinance: Current price for {ticker} is {current_price}")
if current_price is None:
raise ValueError("yfinance failed to fetch price.")
return current_price * quantity
except Exception as e:
st.error(f"Error fetching stock value for {ticker} using yfinance: {e}")
return 0