Question

CSC151 Stock Portfolio GUI Project

Goal

You are to write a GUI program that will allow a user to buy, sell and view stocks in a stock portfolio. This document will describe the minimum expected functions for a grade of 90. Your mission is to “go and do better.” You’ll find a list of enhancement options at the end of this document.

Objectives

By the end of this project, the student will be able to

• write a GUI program that maintains a cash balance, list of stock holdings, supports buying and selling of stocks and displays the current portfolio inventory

• demonstrate the ability to assemble already-written classes into a larger, more complicated program

• demonstrate the ability to segregate business logic from user interface code.

Capabilities

At a minimum, the program should

• allow a user to buy a stock with a given number of shares and price per share.

• display the current portfolio (stock ticker, number of shares, initial price).

• update the portfolio display for purchases and sales.

• allow the user to sell all the shares of a given stock.

• give the user an initial cash balance, and update and display the balance according to the user's purchases and sales.

• ignore any transaction that causes the cash position to go below $0.

Sample Execution price per share It also has buy Note, the focus of this project is furetionality provide sasted ability to pretty up the snterface, se just live with Lets buy Appl titker AAPL) shares First, we enter the ticker, number of Figure 3 Click Buy to Purchase AApie cordingly- portfolio

media%2Fbf8%2Fbf808735-ea97-44ce-8575-dc

Hints

The StockHolding and PortfolioList classes from earlier Lessons should be directly usable in this project. The sample screens above were generated with a version of that code that had slightly different toString() methods, but that's not significant to the function of the program.

The following is a list of possible enhancements, along with their point value, from which you can choose.

1. track the profit or loss on the trades – 4 points

2. allow for sale of partial holding – 4 points

3. subsequent purchases to be added to an existing holding – 4 points

4. formatting of dollar values – 1 point

5. user entered numeric data error checking/reporting – 2 points

6. checking/reporting of data entry errors (e.g., can’t spend more than your balance on hand, can’t sell a stock you don’t own, can’t sell more shares than you own) – 3 points

As you can see, it is possible to earn more than 100 points on this assignment.

Below is the code that I want you to use for writing out the program.

media%2F752%2F75290fc3-88e6-4931-8495-af

media%2Fccc%2Fccc4a1a1-00d7-4fc7-82f2-1e

STOCK PORTFOLIO:

public class PortFolio1{

  

private ArrayList<StockHolding> stocklist;

  

public PortFolio1(){

stockList = new ArrayList<>();

}

  

void add(StockHolding stock){ // adds the given StockHolding to the portfolio

stockList.add(stock);

}

void remove(String ticker){ // removes the StockHolding with the given ticker from the portfolio

  

int index = -1;

  

for(int i=0; i<stockList.size(); i++)

if(ticker.equalsIgnoreCase(stockList.get(i).getTicker())){

index = i;

break;

}

if(index != -1)

stockList.remove(index);

}

  

StockHolding find(String ticker){ // returns a reference to the portfolio element having the given ticker.

int index = -1;

  

for(int i=0; i<stockList.size(); i++)

if(ticker.equalsIgnoreCase(stockList.get(i).getTicker())){

return stockList.get(i);

}

return null;

  

}

String toString(){ // returns a string containing the toString values of each element

//separated by newline characters (\n)

String result = "";

for(StockHolding stock : stockList)

result = result + stock.toString()+"\n";

  

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

SOURCE CODE:


package stock;

public class StockHolding {

private String ticker;
private int numShares;
private double initialSharePrice;
private double currentSharePrice;

public StockHolding(String ticker, int numberShares, double initialPrice) {
this.ticker = ticker;
numShares = numberShares;
initialSharePrice = initialPrice;
currentSharePrice = initialPrice;
}

public double getCurrentValue() {
return numShares * getCurrentSharePrice();
}

public double getInitialCost() {
return numShares * getInitialSharePrice();
}

public double getCurrentProfit() {
return getCurrentValue() - getInitialCost();
}
public double getCurrentSharePrice() {
return currentSharePrice;
}
public void setCurrentSharePrice(double currentSharePrice) {
this.currentSharePrice = currentSharePrice;
}
public String getTicker() {
return ticker;
}
public int getShares() {
return numShares;
}
public double getInitialSharePrice() {
return initialSharePrice;
}

public void setNumShares(int numShares) {
this.numShares = numShares;
}

@Override
public String toString() {
return "Stock " + ticker + ", " + numShares + ", shares bought at "
+ initialSharePrice + ", current price "
+ currentSharePrice;
}
}

-----------------------------------------------------------------------------------------------------------------------

package stock;

import java.util.ArrayList;

/**
*
* @author Gojkid
*/
public class PortfolioList {

private ArrayList<StockHolding> portfolio;

public PortfolioList() {
portfolio = new ArrayList<StockHolding>();
}

public void add(StockHolding stock) {
portfolio.add(stock);
}

public StockHolding find(String ticker) {
for (int i = 0; i < portfolio.size(); i++) {
StockHolding sh = portfolio.get(i);
if (sh.getTicker().equals(ticker)) {
return sh;
}
}
return null;
}
public int getPos(StockHolding sh)
{
return portfolio.indexOf(sh);
}
public int getSize()
{
return portfolio.size();
}
public StockHolding getElement(int i) {
return portfolio.get(i);
}
public void remove(String ticker) {
int pos = -1;
for (int i = 0; i < portfolio.size(); i++) {
StockHolding sh = portfolio.get(i);
if (sh.getTicker().equals(ticker)) {
pos = i;
}
}
if (pos != -1) {
portfolio.remove(pos);
}
}
}

-----------------------------------------------------------------------------------------------------------------------

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/*
* StockTrading.java
*
* Created on Nov 29, 2016, 12:43:57 AM
*/
package stock;

import javax.swing.table.DefaultTableModel;

public class StockTrading extends javax.swing.JFrame {

/** Creates new form StockTrading */
public StockTrading() {
initComponents();
}

@SuppressWarnings("unchecked")
private void initComponents() {

ticker = new javax.swing.JComboBox();
jScrollPane1 = new javax.swing.JScrollPane();
portfolio = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
price = new javax.swing.JTextField();
number = new javax.swing.JSpinner();
buy = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
balance = new javax.swing.JTextField();
sell = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
message = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Stock Trading Program");

ticker.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "A – Agilent Technologies", "AAPL – Apple Inc.", "BRK.A – Berkshire Hathaway", "C – Citigroup", "GOOG – Alphabet Inc.", "HOG – Harley-Davidson Inc.", "HPQ – Hewlett-Packard", "INTC – Intel", "KO – The Coca-Cola Company", "LUV - Southwest Airlines", "MMM – Minnesota Mining and Manufacturing", "MSFT – Microsoft", "T - AT&T", "TGT – Target Corporation", "TXN – Texas Instruments", "WMT – Walmart" }));

portfolio.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Ticker", "Number", "Current Price", "Intial Price"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false
};

public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}

public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(portfolio);

jLabel1.setText("Ticker :");

jLabel2.setText("Price:");

number.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));

buy.setText("Buy");
buy.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buyActionPerformed(evt);
}
});

jLabel3.setText("Remaining Balance:");

balance.setText("$10000");

sell.setText("Sell");
sell.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sellActionPerformed(evt);
}
});

jLabel4.setText("User's Portfolio");

message.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
message.setText(" ");

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 723, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(103, 103, 103)
.addComponent(jLabel3)
.addGap(29, 29, 29)
.addComponent(balance, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 291, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buy)
.addGap(31, 31, 31)
.addComponent(sell))
.addGroup(layout.createSequentialGroup()
.addComponent(ticker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(number, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(message, javax.swing.GroupLayout.PREFERRED_SIZE, 489, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(39, 39, 39))
.addGroup(layout.createSequentialGroup()
.addGap(365, 365, 365)
.addComponent(jLabel4)
.addContainerGap(878, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(33, 33, 33)
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(67, 67, 67)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(balance, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(102, 102, 102)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ticker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(number, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(38, 38, 38)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buy)
.addComponent(sell))
.addGap(64, 64, 64)
.addComponent(message)))
.addContainerGap(69, Short.MAX_VALUE))
);

pack();
}

private void buyActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
message.setText("");
price.setText(""+(int)(Math.random()*1000+Math.random()*100+Math.random()*10));
double p = Double.parseDouble(price.getText());
int n = ((Integer)number.getValue()).intValue();
StockHolding sh=new StockHolding((String)ticker.getSelectedItem(),n,p);
if(Double.parseDouble(balance.getText().substring(1))>=(p*n))
{
userPortfolio.add(sh);
bal=Double.parseDouble(balance.getText().substring(1))-(n*p);
balance.setText("$"+(int)bal);
}

else
message.setText("You don't have enough money to buy these shares");
updateTable();
  
}

private void sellActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
message.setText("");
if(userPortfolio.find((String)ticker.getSelectedItem())!=null)
{
if(userPortfolio.find((String)ticker.getSelectedItem()).getShares()>=((Integer)number.getValue()).intValue())
{
bal = Double.parseDouble(balance.getText().substring(1))+userPortfolio.find((String)ticker.getSelectedItem()).getCurrentSharePrice()*((Integer)number.getValue()).intValue();
userPortfolio.find((String)ticker.getSelectedItem()).setNumShares(userPortfolio.find((String)ticker.getSelectedItem()).getShares()-((Integer)number.getValue()).intValue());
balance.setText("$"+(int)bal);
}
else if(Double.parseDouble(balance.getText().substring(1))==(userPortfolio.find((String)ticker.getSelectedItem()).getCurrentSharePrice()*((Integer)number.getValue()).intValue()))
{
bal=Double.parseDouble(balance.getText().substring(1))-(((Integer)number.getValue()).intValue()*userPortfolio.find((String)ticker.getSelectedItem()).getCurrentSharePrice());
DefaultTableModel dtm = (DefaultTableModel) portfolio.getModel();
dtm.removeRow(userPortfolio.getPos(userPortfolio.find((String)ticker.getSelectedItem())));
userPortfolio.remove((String)ticker.getSelectedItem());
balance.setText("$"+(int)bal);
}
else
message.setText("You only have "+userPortfolio.find((String)ticker.getSelectedItem()).getShares()+" shares of"+ticker.getSelectedItem());
}
else
message.setText("You don't have any "+ticker.getSelectedItem()+" shares");
updateTable();
}

public void updateTable()
{
  
for (int i = 0; i < userPortfolio.getSize(); i++) {
StockHolding sh = userPortfolio.getElement(i);
if(i <= userPortfolio.getSize())
{
DefaultTableModel dtm = (DefaultTableModel) portfolio.getModel();
dtm.addRow(new Object[]{"", "", "",""});
  
}
sh.setCurrentSharePrice(sh.getInitialSharePrice()+Math.random()*10);
portfolio.setValueAt(sh.getTicker(), i, 0 );
portfolio.setValueAt(sh.getShares()+"", i, 1 );
portfolio.setValueAt("$"+(int)sh.getCurrentSharePrice(), i, 2 );
portfolio.setValueAt("$"+(int)sh.getInitialSharePrice(), i, 3 );
}
}
  
public static void main(String args[]) {

try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(StockTrading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StockTrading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StockTrading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StockTrading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {
new StockTrading().setVisible(true);
}
});
}
private javax.swing.JTextField balance;
private javax.swing.JButton buy;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel message;
private javax.swing.JSpinner number;
private javax.swing.JTable portfolio;
private javax.swing.JTextField price;
private javax.swing.JButton sell;
private javax.swing.JComboBox ticker;

private PortfolioList userPortfolio = new PortfolioList();
private double bal;
}

Add a comment
Know the answer?
Add Answer to:
CSC151 Stock Portfolio GUI Project Goal You are to write a GUI program that will allow...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In Java. Write a GUI contact list application. The program should allow you to input names...

    In Java. Write a GUI contact list application. The program should allow you to input names and phone numbers. You should also be able to input a name and have it display the previously entered phone number. The GUI should look something like the following, although you are welcome to format it in any way that works. This should be a GUI application with a JFrame. The program should contain two arrays of Strings. One array will contain a list...

  • Write a javafx GUI program that uses a TextField to allow the user to enter a...

    Write a javafx GUI program that uses a TextField to allow the user to enter a string. When the user presses return, have the action handler for the TextField count the number of vowels (a, e, i, o, u, y) in the string. Use a switch statement for this rather that if statements. Write out the number of vowels in a Label. Case does not matter for the vowels.

  • This project will create a GUI to access data held in a MySQL database. You will design a GUI usi...

    This project will create a GUI to access data held in a MySQL database. You will design a GUI using Swing components that will allow you to add a record, delete a record, update a record and display all current records int he database. The design is your choice. Extra credit will be given for the ability to search for a specific record by a key value. You will need to provide details of the database domain, table and record...

  • REQUIREMENTS: Write a Graphical User Interface (GUI) program using JavaFX that prompts the user to enter...

    REQUIREMENTS: Write a Graphical User Interface (GUI) program using JavaFX that prompts the user to enter a credit card number. Display whether the number is valid and the type of credit cards (i.e., Visa, MasterCard, American Express, Discover, and etc). The requirements for this assignment are listed below: • Create a class (CreditNumberValidator) that contains these methods: // Return true if the card number is valid. Boolean isValid(String cardNumber); // Get result from Step 2. int sumOfDoubleEvenPlace(String cardNumber); // Return...

  • I am creating a program that will allow users to sign in with a username and...

    I am creating a program that will allow users to sign in with a username and password. Their information is saved in a text file. The information in the text file is saved as such: Username Password I have created a method that will take the text file and convert into an array list. Once the username and password is found, it will be removed from the arraylist and will give the user an opportunity to sign in with a...

  • This is an additional assignment from the chapter on the Java Collections Framework. Suppose you buy...

    This is an additional assignment from the chapter on the Java Collections Framework. Suppose you buy 100 shares of a stock at $12 per share, then another 100 at $10 per share, then you sell 150 shares at $15. You have to pay taxes on the gain, but exactly what is the gain? In the United States, the FIFO rule holds: You first sell all shares of the first batch for a profit of $300, then 50 of the shares...

  • Java: student directory GUI You need to implement three classes: Person Student StudentDirectory StudentMain Start by...

    Java: student directory GUI You need to implement three classes: Person Student StudentDirectory StudentMain Start by implementing Person and Student classes. Once you are sure you can serialize and deserialize and ArrayList of Students to and from a file, move on to building the GUI application. Person: The Person class should implement serializable interface. It contains the following: Person's first name (String) Person's last name (String) Person's id number Person's date of birth (Date) public String toString(): This method method...

  • PROGRAMING IN C. PLEASE HELP FIX MY CODE TO FIT THE FOLLOWING CRITERIA: 1.)Read your stocks...

    PROGRAMING IN C. PLEASE HELP FIX MY CODE TO FIT THE FOLLOWING CRITERIA: 1.)Read your stocks from your mystocks.txt file. You can use this information for the simulator. 2.)The stock price simulator will return the current price of the stock. The current prices is the prices of the requested ticker + a random number. 3.)We will assume that the stock price remains constant after the price check till your trade gets executed. Therefore, a buy or a sell order placed...

  • This project will use The Vigenere Cipher to encrypt passwords. Simple letter substitution ciphers are ones...

    This project will use The Vigenere Cipher to encrypt passwords. Simple letter substitution ciphers are ones in which one letter is substituted for another. Although their output looks impossible to read, they are easy to break because the relative frequencies of English letters are known. The Vigenere cipher improves upon this. They require a key word and the plain text to be encrypted. Create a Java application that uses: decision constructs looping constructs basic operations on an ArrayList of objects...

  • COP3337 Assignment 10 This is an additional assignment from the chapter on the Java Collections Framework....

    COP3337 Assignment 10 This is an additional assignment from the chapter on the Java Collections Framework. Suppose you buy 100 shares of a stock at $12 per share, then another 100 at $10 per share, then you sell 150 shares at $15. You have to pay taxes on the gain, but exactly what is the gain? In the United States, the FIFO rule holds: You first sell all shares of the first batch for a profit of $300, then 50...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT