Skip to content

Commit

Permalink
graphing formating
Browse files Browse the repository at this point in the history
  • Loading branch information
eethansmith committed Dec 13, 2023
1 parent d046de3 commit ee231f6
Show file tree
Hide file tree
Showing 6 changed files with 195 additions and 40 deletions.
41 changes: 41 additions & 0 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"@testing-library/user-event": "^13.5.0",
"axios": "^1.6.2",
"chart.js": "^4.4.0",
"chartjs-adapter-date-fns": "^3.0.0",
"react": "^18.2.0",
"react-chartjs-2": "^5.2.0",
"react-dom": "^18.2.0",
Expand Down
24 changes: 24 additions & 0 deletions frontend/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,29 @@ function App() {
}
};

const fetchSelectedStockData = async () => {
if (selectedStock) {
try {
const response = await fetch(`[Your API Endpoint]/${selectedStock.ticker}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
// Update your selectedStock state with the new data
setSelectedStock(data);
} catch (error) {
console.error('Fetching stock data failed:', error);
}
}
};

useEffect(() => {
const interval = setInterval(() => {
fetchSelectedStockData();
}, 5000);
return () => clearInterval(interval);
}, [selectedStock]);

return (
<div className="App">
<nav className="App-nav">
Expand Down Expand Up @@ -57,6 +80,7 @@ function App() {
<div className="stock-info">
<p>
Current Value: ${selectedStock.value_held.toFixed(2)}

<span style={{ color: selectedStock.profit_loss_percentage >= 0 ? 'green' : 'red' }}>
{` (${formatPercentage(selectedStock.profit_loss_percentage)})`}
</span>
Expand Down
34 changes: 17 additions & 17 deletions frontend/src/StockGraphingAll.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useState, useEffect } from 'react';
import { Line } from 'react-chartjs-2';
import 'chart.js/auto';
import 'chartjs-adapter-date-fns';

function StockGraphAll({ ticker, timeFrame }) { // Use destructuring to get the ticker prop
const [stockData, setStockData] = useState([]);
Expand Down Expand Up @@ -45,43 +46,42 @@ function StockGraphAll({ ticker, timeFrame }) { // Use destructuring to get the

const chartOptions = {
responsive: true,
plugins: {
legend: {
display: false
},
tooltip: {
mode: 'index',
intersect: false
},
},
scales: {
y: {
beginAtZero: true // Start Y-axis at 0
beginAtZero: false
},
x: {
type: 'time',
time: {
unit: 'month',
unit: 'day',
displayFormats: {
month: 'DD-MM-YY'
month: 'dd-MM-yy'
}
},
ticks: {
display: false // Hide the X-axis labels
display: false
}
}
},
legend: {
display: false // Hide the legend
},
tooltips: {
mode: 'index',
intersect: false
},
hover: {
mode: 'nearest',
intersect: true
},
animation: {
duration: 200 // Animation duration in milliseconds
duration: 1000 // Animation duration in milliseconds
}
};



return (
<div className="stock-graph-container">
<Line data={chartData} />
<Line data={chartData} options={chartOptions} />
</div>
);
}
Expand Down
38 changes: 15 additions & 23 deletions frontend/src/StockGraphingDay.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useState, useEffect } from 'react';
import { Line } from 'react-chartjs-2';
import 'chart.js/auto';
import 'chartjs-adapter-date-fns';

function StockGraphDay({ ticker, timeFrame }) {
const [stockData, setStockData] = useState([]);
Expand Down Expand Up @@ -45,50 +46,41 @@ function StockGraphDay({ ticker, timeFrame }) {

const chartOptions = {
responsive: true,
plugins: {
legend: {
display: false
},
tooltip: {
mode: 'index',
intersect: false
},
},
scales: {
y: {
beginAtZero: true // Start Y-axis at 0
beginAtZero: false
},
x: {
type: 'time',
time: {
unit: 'day',
unit: 'month',
displayFormats: {
month: 'DD/MM/YY'
month: 'dd-MM-yy-HH:mm'
}
},
ticks: {
display: false
}
}
},
plugins: {
tooltips: {
mode: 'index',
intersect: false,
callbacks: {
title: function(tooltipItem, data) {
return '${data.datasets[tooltipItem.datasetIndex].label}: ${tooltipItem.formattedValue}';
}
}
},
legend: {
display: false // Hide the legend
}
},
hover: {
mode: 'nearest',
intersect: true
},
animation: {
duration: 200 // Animation duration in milliseconds
duration: 1000 // Animation duration in milliseconds
}
};


return (
<div className="stock-graph-container">
<Line data={chartData} />
<Line data={chartData} options={chartOptions} />
</div>
);
}
Expand Down
97 changes: 97 additions & 0 deletions frontend/src/StockHoldingsDay.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import React, { useState, useEffect } from 'react';

function StockHoldingsDay({ onStockSelect, timeFrame }) {
const [holdings, setHoldings] = useState([]);
const [images, setImages] = useState({});

// Function to fetch data from your API
const fetchStockHoldings = async () => {
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);
}
};

// Updated handleStockClick to pass the entire stock object
const handleStockClick = (stock) => {
if (onStockSelect) {
onStockSelect(stock); // Pass the entire stock object
}
};

useEffect(() => {
fetchStockHoldings();
const interval = setInterval(fetchStockHoldings, 2000);
return () => clearInterval(interval);
}, [timeFrame]);

// Function to load images
const loadImage = async (ticker) => {
try {
const image = await import(`./resources/${ticker}.png`);
return image.default;
} catch (error) {
// Attempt to load without '.L' if it fails
if (ticker.endsWith('.L')) {
try {
const modifiedTicker = ticker.replace('.L', '');
const image = await import(`./resources/${modifiedTicker}.png`);
return image.default;
} catch (innerError) {
console.error('Error loading image:', innerError);
return '';
}
}
}
};

useEffect(() => {
const loadImages = async () => {
const loadedImages = {};
for (const stock of holdings) {
loadedImages[stock.ticker] = await loadImage(stock.ticker);
}
setImages(loadedImages);
};

if (holdings.length > 0) {
loadImages();
}
}, [holdings]);

useEffect(() => {
fetchStockHoldings();
const interval = setInterval(fetchStockHoldings, 2000);
return () => clearInterval(interval);
}, [timeFrame]);

return (
<div className="stock-holdings">
<h2>Current Stock Holdings</h2>
{holdings.map((stock, index) => (
<button key={index} className="stock-button" onClick={() => handleStockClick(stock)}>
<img src={images[stock.ticker]} alt={stock.name} className="stock-image" />
<div className="stock-details">
<div className="stock-name">{stock.name}</div>
<div>{`${stock.shares_held} shares`}</div>
</div>
<div className="stock-value-gain">
<div>{`$${stock.value_held.toFixed(2)}`}</div>
<div className="gain-loss" style={{ color: stock.profit_loss_percentage < 0 ? 'red' : 'green' }}>
{`${stock.profit_loss_percentage.toFixed(2)}%`}
</div>
</div>
</button>
))}
</div>
);
}

export default StockHoldingsDay;

0 comments on commit ee231f6

Please sign in to comment.