-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
5ae3415
commit 419ad78
Showing
8 changed files
with
135 additions
and
12 deletions.
There are no files selected for viewing
Binary file not shown.
Binary file not shown.
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'), | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters