Skip to content

Commit

Permalink
added daily graphing on click
Browse files Browse the repository at this point in the history
  • Loading branch information
eethansmith committed Dec 12, 2023
1 parent 5ae3415 commit 419ad78
Show file tree
Hide file tree
Showing 8 changed files with 135 additions and 12 deletions.
Binary file not shown.
Binary file not shown.
Binary file modified backend/myapp/__pycache__/urls.cpython-38.pyc
Binary file not shown.
70 changes: 70 additions & 0 deletions backend/myapp/current_stock_holdings_day.py
Original file line number Diff line number Diff line change
@@ -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)
35 changes: 35 additions & 0 deletions backend/myapp/graph_stock_holdings_day.py
Original file line number Diff line number Diff line change
@@ -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)
2 changes: 1 addition & 1 deletion backend/myapp/tester.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import yfinance as yf

ticker = yf.Ticker("VUAG.L")
ticker = yf.Ticker("AAPL")
print(ticker.info)
4 changes: 4 additions & 0 deletions backend/myapp/urls.py
Original file line number Diff line number Diff line change
@@ -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/<str:ticker>/', get_stock_history, name='graph_stock'),
path('graph_stock_day/<str:ticker>/', get_stock_history, name='graph_stock_day'),
path('historic_holdings/', get_historic_stock_holdings, name='all_holdings'),
path('graph_portfolio/<int:days>/', get_portfolio_value, name='graph_portfolio'),
]
36 changes: 25 additions & 11 deletions frontend/src/StockHoldings.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
};

Expand All @@ -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) => {
Expand Down Expand Up @@ -70,7 +84,7 @@ function StockHoldings({ onStockSelect, timeFrame }) {
fetchStockHoldings();
const interval = setInterval(fetchStockHoldings, 2000);
return () => clearInterval(interval);
}, []);
}, [timeFrame]);

return (
<div className="stock-holdings">
Expand Down

0 comments on commit 419ad78

Please sign in to comment.