diff --git a/backend/myapp/__pycache__/current_stock_holdings_day.cpython-38.pyc b/backend/myapp/__pycache__/current_stock_holdings_day.cpython-38.pyc new file mode 100644 index 0000000..d2a32ca Binary files /dev/null and b/backend/myapp/__pycache__/current_stock_holdings_day.cpython-38.pyc differ diff --git a/backend/myapp/__pycache__/graph_stock_holdings_day.cpython-38.pyc b/backend/myapp/__pycache__/graph_stock_holdings_day.cpython-38.pyc new file mode 100644 index 0000000..c88f964 Binary files /dev/null and b/backend/myapp/__pycache__/graph_stock_holdings_day.cpython-38.pyc differ diff --git a/backend/myapp/__pycache__/urls.cpython-38.pyc b/backend/myapp/__pycache__/urls.cpython-38.pyc index f144b3c..a3dc8d1 100644 Binary files a/backend/myapp/__pycache__/urls.cpython-38.pyc and b/backend/myapp/__pycache__/urls.cpython-38.pyc differ diff --git a/backend/myapp/current_stock_holdings_day.py b/backend/myapp/current_stock_holdings_day.py new file mode 100644 index 0000000..9311c9a --- /dev/null +++ b/backend/myapp/current_stock_holdings_day.py @@ -0,0 +1,70 @@ +import json +from django.http import JsonResponse +from django.conf import settings +from pathlib import Path +import yfinance as yf + +def get_stock_holdings_day(request): + # Define the path to the JSON file + json_file_path = Path(settings.BASE_DIR) / 'data' / 'investments_data.json' + + # Open the JSON file and load its content + with open(json_file_path, 'r') as file: + transactions_data = json.load(file) + + # Process transactions to determine current holdings + holdings = {} + for transaction in transactions_data: + ticker = transaction["Ticker Symbol"] + shares = float(transaction["No. of Shares"]) + transaction_type = transaction["Transaction Type"] + + if ticker not in holdings: + holdings[ticker] = 0.0 + + holdings[ticker] += shares if transaction_type == "BUY" else -shares + + # Filter out stocks where holdings are zero or negative + holdings = {k: v for k, v in holdings.items() if v > 0} + + # Fetch live data for remaining stocks + live_data = {} + for ticker, shares in holdings.items(): + try: + stock = yf.Ticker(ticker) + stock_info = stock.info + + # Determine the correct fields based on the ticker + name_field = "longName" if ticker == "VUAG.L" else "shortName" + price_field = "previousClose" if ticker == "VUAG.L" else "currentPrice" + + # Fetch the relevant data + name = stock_info.get(name_field) + current_price = stock_info.get(price_field) or stock_info.get("previousClose") + average_cost = stock_info.get("previousClose") + total_investment = average_cost * shares + current_value = shares * current_price if current_price is not None else None + value_held = round((shares * current_price if current_price is not None else None),2) + + profit_loss_percentage = round((((current_value - total_investment) / total_investment * 100) if current_value is not None else None),2) + + + live_data[ticker] = { + "ticker": ticker, + "name": name, + "shares_held": round(shares,4), + "current_price": current_price, + "value_held": value_held, + "profit_loss_percentage": profit_loss_percentage + } + except Exception as e: + print(f"Error fetching data for {ticker}: {e}") + live_data[ticker] = { + "ticker": ticker, + "error": str(e) + } + + sorting_data = sorted(live_data.items(), key=lambda x: x[1].get('value_held', 0), reverse=True) + live_data = {k: v for k, v in sorting_data} + + return JsonResponse(live_data) \ No newline at end of file diff --git a/backend/myapp/graph_stock_holdings_day.py b/backend/myapp/graph_stock_holdings_day.py new file mode 100644 index 0000000..61b2a6a --- /dev/null +++ b/backend/myapp/graph_stock_holdings_day.py @@ -0,0 +1,35 @@ +import json +from django.http import JsonResponse +from django.conf import settings +from pathlib import Path +import yfinance as yf +import pytz +from datetime import datetime, timedelta + +# Your timezone, for example, 'UTC' +timezone = pytz.timezone('EST') + +def get_stock_history(request, ticker): + if not ticker: + return JsonResponse({"error": "Ticker symbol is required."}, status=400) + + stock = yf.Ticker(ticker) + # Fetch data for the last 24 hours with granular intervals (e.g., 5 minutes) + end_date = datetime.now(tz=timezone) + start_date = end_date - timedelta(days=1) + historical_prices = stock.history(start=start_date.strftime('%Y-%m-%d'), end=end_date.strftime('%Y-%m-%d'), interval="5m") + + # Fetch the previous day's closing price + previous_day_data = stock.history(period="2d", interval="1d") + if len(previous_day_data) < 2: + return JsonResponse({"error": "Previous day's data not available"}, status=404) + previous_close = previous_day_data['Close'].iloc[-2] + + # Convert data to the desired timezone and format for response + historical_values = [{ + "datetime": date.tz_convert(timezone).strftime('%Y-%m-%d %H:%M:%S'), + "value": row['Close'], + "value_paid": previous_close + } for date, row in historical_prices.iterrows()] + + return JsonResponse(historical_values, safe=False) diff --git a/backend/myapp/tester.py b/backend/myapp/tester.py index 066664f..4b778a1 100644 --- a/backend/myapp/tester.py +++ b/backend/myapp/tester.py @@ -1,4 +1,4 @@ import yfinance as yf -ticker = yf.Ticker("VUAG.L") +ticker = yf.Ticker("AAPL") print(ticker.info) \ No newline at end of file diff --git a/backend/myapp/urls.py b/backend/myapp/urls.py index 9a13706..165e33c 100644 --- a/backend/myapp/urls.py +++ b/backend/myapp/urls.py @@ -1,12 +1,16 @@ from django.urls import path from .current_stock_holdings import get_stock_holdings +from .current_stock_holdings_day import get_stock_holdings_day from .graph_stock_holdings import get_stock_history +from .graph_stock_holdings_day import get_stock_history from .historic_stock_holdings import get_historic_stock_holdings from .graph_all_holdings import get_portfolio_value urlpatterns = [ path('stock_holdings/', get_stock_holdings, name='stock_holdings'), + path('stock_holdings_day/', get_stock_holdings_day, name='stock_holdings_day'), path('graph_stock//', get_stock_history, name='graph_stock'), + path('graph_stock_day//', get_stock_history, name='graph_stock_day'), path('historic_holdings/', get_historic_stock_holdings, name='all_holdings'), path('graph_portfolio//', get_portfolio_value, name='graph_portfolio'), ] \ No newline at end of file diff --git a/frontend/src/StockHoldings.js b/frontend/src/StockHoldings.js index df8b092..2d3b149 100644 --- a/frontend/src/StockHoldings.js +++ b/frontend/src/StockHoldings.js @@ -6,16 +6,30 @@ function StockHoldings({ onStockSelect, timeFrame }) { // Function to fetch data from your API const fetchStockHoldings = async () => { - try { - const response = await fetch('http://localhost:8000/api/stock_holdings/'); - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); + if (timeFrame === 'All') { + try { + const response = await fetch(`http://localhost:8000/api/stock_holdings/`); + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + const data = await response.json(); + console.log(data); + setHoldings(Object.values(data)); + } catch (error) { + console.error('Fetching data failed:', error); + } + } else { + try { + const response = await fetch('http://localhost:8000/api/stock_holdings_day/'); + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + const data = await response.json(); + console.log(data); + setHoldings(Object.values(data)); + } catch (error) { + console.error('Fetching data failed:', error); } - const data = await response.json(); - console.log(data); // Check the structure of the fetched data - setHoldings(Object.values(data)); // Convert the object to an array and update state - } catch (error) { - console.error('Fetching data failed:', error); } }; @@ -30,7 +44,7 @@ function StockHoldings({ onStockSelect, timeFrame }) { fetchStockHoldings(); const interval = setInterval(fetchStockHoldings, 2000); return () => clearInterval(interval); - }, []); + }, [timeFrame]); // Function to load images const loadImage = async (ticker) => { @@ -70,7 +84,7 @@ function StockHoldings({ onStockSelect, timeFrame }) { fetchStockHoldings(); const interval = setInterval(fetchStockHoldings, 2000); return () => clearInterval(interval); - }, []); + }, [timeFrame]); return (