Skip to content

Commit

Permalink
full functioning daily view
Browse files Browse the repository at this point in the history
  • Loading branch information
eethansmith committed Dec 12, 2023
1 parent 419ad78 commit a9e2a33
Show file tree
Hide file tree
Showing 7 changed files with 64 additions and 19 deletions.
Binary file modified backend/myapp/__pycache__/graph_stock_holdings.cpython-38.pyc
Binary file not shown.
Binary file modified backend/myapp/__pycache__/graph_stock_holdings_day.cpython-38.pyc
Binary file not shown.
Binary file modified backend/myapp/__pycache__/urls.cpython-38.pyc
Binary file not shown.
2 changes: 1 addition & 1 deletion backend/myapp/graph_stock_holdings.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def get_stock_history(request, ticker):
historical_prices = stock.history(start=start_date.strftime('%Y-%m-%d'), end=end_date.strftime('%Y-%m-%d'))

# Check if data is sparse and fetch hourly data if necessary
if len(historical_prices) < 10:
if len(historical_prices) < 80:
historical_prices = stock.history(period="1mo", interval="1h")

historical_values = []
Expand Down
58 changes: 48 additions & 10 deletions backend/myapp/graph_stock_holdings_day.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,65 @@
# Your timezone, for example, 'UTC'
timezone = pytz.timezone('EST')

def get_stock_history(request, ticker):
def get_current_shares_held(ticker):
if not ticker:
return JsonResponse({"error": "Ticker symbol is required."}, status=400)

# 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)

transactions = [t for t in transactions_data if t['Ticker Symbol'] == ticker]

if not transactions:
return JsonResponse({"error": "No transactions found for given ticker."}, status=404)

current_shares = 0.0

# Calculate the current number of shares held
for transaction in transactions:
shares = float(transaction["No. of Shares"])
if transaction["Transaction Type"] == "BUY":
current_shares += shares
elif transaction["Transaction Type"] == "SELL":
current_shares -= shares

return current_shares

def get_stock_history_day(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")
# Get today's date and yesterday's date in the specified timezone
today = datetime.now(tz=timezone).date()
yesterday = today - timedelta(days=1)

# Fetch today's data
today_data = stock.history(period='1d', interval='1m', start=today, end=today + timedelta(days=1))

if today_data.empty: # If today's data is empty, assume the market is closed
# Fetch previous day's data
historical_prices = stock.history(period='1d', interval='1m', start=yesterday, end=today)
else:
historical_prices = today_data

shares_held = get_current_shares_held(ticker)

# 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]
previous_close_paid = shares_held * previous_close

# 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
"date": date.tz_convert(timezone).strftime('%Y-%m-%d %H:%M:%S'),
"value": row['Close'] * shares_held, # Current value of shares held
"value_paid": previous_close_paid # Value based on previous day's close
} for date, row in historical_prices.iterrows()]

return JsonResponse(historical_values, safe=False)
return JsonResponse(historical_values, safe=False)
4 changes: 2 additions & 2 deletions backend/myapp/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@
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 .graph_stock_holdings_day import get_stock_history_day
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('graph_stock_day/<str:ticker>/', get_stock_history_day, 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'),
]
19 changes: 13 additions & 6 deletions frontend/src/StockGraphing.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,23 @@ import React, { useState, useEffect } from 'react';
import { Line } from 'react-chartjs-2';
import 'chart.js/auto';

function StockGraph({ ticker }) { // Use destructuring to get the ticker prop
function StockGraph({ ticker, timeFrame }) { // Use destructuring to get the ticker prop
const [stockData, setStockData] = useState([]);

useEffect(() => {
// Ensure the ticker value is included in the fetch URL
fetch(`http://localhost:8000/api/graph_stock/${ticker}/`)
.then(response => response.json())
.then(data => setStockData(data))
.catch(error => console.error('Error fetching data:', error));
}, [ticker]); // Include ticker in the dependency array
if (timeFrame == 'All') {
fetch(`http://localhost:8000/api/graph_stock/${ticker}/`)
.then(response => response.json())
.then(data => setStockData(data))
.catch(error => console.error('Error fetching data:', error));
} else {
fetch(`http://localhost:8000/api/graph_stock_day/${ticker}/`)
.then(response => response.json())
.then(data => setStockData(data))
.catch(error => console.error('Error fetching data:', error));
}
}, [ticker]);

const chartData = {
labels: stockData.map(data => data.date),
Expand Down

0 comments on commit a9e2a33

Please sign in to comment.