Question

We say a portfolio matches the benchmark when the number of shares of each asset in...

We say a portfolio matches the benchmark when the number of shares of each asset in the portfolio matches the number of shares of each asset in the benchmark. Your question is to write a program that determines the transactions necessary to make a portfolio match a benchmark.

A portfolio is a collection of assets such as stocks and bonds. A portfolio could have 10 shares of Vodafone stock, 15 shares of Google stock and 15 shares of Microsoft bonds. A benchmark is also just a collection of assets. A benchmark could have 15 shares of Vodafone stock, 10 shares of Google stock and 15 shares of Microsoft bonds.

A transaction is when you “buy” or “sell” a particular asset of certain asset type (“stock” or “bond”). For instance, you can decide to buy 5 shares of Vodafone stock which, given the portfolio described above, would result in you having 15 shares of Vodafone stock. Correspondingly, you decide to sell 5 shares of Microsoft bonds, which would result in 10 shares of Microsoft bonds in the above portfolio.

Assumptions:

  • Shares are positive decimals
  • There will always be at least 1 asset present in the Portfolio and Benchmark
  • A particular asset can be bond, stock, or both. For example, 5 shares of Microsoft bonds and 10 shares of Microsoft stock can both be present in the portfolio/benchmark
  • The trades should be sorted in alphabetical order based on the names of the assets; if both bonds and stock are present for an asset, list bonds first

Input:

  • The first part of the input is the Portfolio holdings (in the format Name,AssetType,Shares where each asset is separated by '|' symbol)
  • The second part of the input is the Benchmark holdings (in the format Name,AssetType,Shares where each asset is separated by '|' symbol)

Example input: Vodafone,STOCK,10|Google,STOCK,15|Microsoft,BOND,15:Vodafone,STOCK,15|Google,STOCK,10|Microsoft,BOND,15

Note that the two parts are separated by the ':' symbol.

Output:

The output is a list of transactions (separated by new line) in the format TransactionType,Name,AssetType,Shares. Note that the TransactionType should only be BUY or SELL.

Example output: SELL,Google,STOCK,5 BUY,Vodafone,STOCK,5

Test 1

Test Input

Vodafone,STOCK,10|Google,STOCK,15|Microsoft,BOND,15:Vodafone,STOCK,15|Google,STOCK,10|Microsoft,BOND,15

Expected Output

SELL,Google,STOCK,5

BUY,Vodafone,STOCK,5

Test 2

Test Input

Vodafone,STOCK,10|Google,STOCK,15:Vodafone,STOCK,15|Vodafone,BOND,10|Google,STOCK,10

Expected Output

SELL,Google,STOCK,5

BUY,Vodafone,BOND,10

BUY,Vodafone,STOCK,5

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.nio.charset.StandardCharsets;

public class Main {

/**

   * Iterate through each line of input.

   */

public static void main(String[] args) throws IOException {

InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8);

BufferedReader in = new BufferedReader(reader);

String line;

while ((line = in.readLine()) != null) {

Main.matchBenchmark(line);

}

}

  

public static void matchBenchmark(String input) {

// Access your code here. Feel free to create other classes as required

}

}

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

code

solution

1/Main.java import java.io. BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.chaportfolio_Object.setno_of_assets (Integer.parseInt(port[i].spli t(,) [2]]); array_portfolio.add(portfolio_Object); for(intarray_benchmark.remove(ji); break; else if(differen < 0) System.out.println(\nBUY, + array_portfolio.get (il).get_portfoliofor(int jl=0; jl<array portfolio.size(); 11++) if(array_portfolio.get(il).get_portfolioName().equals(array_be nchmark.get (jlo.get (kl).get_Asset_Type ()+,+array_portfolio.get (kl).getno_o f assets()); array_portfolio.remove (kl); if(array_benchmar//Portfolio.java import java.util. Comparator; //declare the function name portfolio public class Portfolio i private String

//output

please Enter the transaction details Vodafone, STOCK, 10 Google, STOCK, 15 Microsoft, BOND, 15:Vodafone, STOCK, 15 Google, ST

//copyable code

//Main.java

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.nio.charset.StandardCharsets;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

public class Main {

   static ArrayList<Portfolio> array_portfolio = new ArrayList<Portfolio>();

   static ArrayList<Benchmark> array_benchmark = new ArrayList<Benchmark>();

   public static void main(String[] args) {

      

           System.out.println("\nplease Enter the transaction details\n");

           InputStreamReader re11 = new InputStreamReader(System.in, StandardCharsets.UTF_8);

           BufferedReader inp = new BufferedReader(re11);

           String line11;

           try {

               while ((line11 = inp.readLine()) != null) {

                   populate_obj(line11);

                   Benchmark_match();

               }

           } catch (IOException e) {

              

               e.printStackTrace();

           }     

     

   }

   public static void populate_obj(String line11)

   {

       String [] in_array = line11.split(":");

       String [] port=in_array[0].split("\\|");

       String [] bench=in_array[1].split("\\|");

     

       for(int i=0;i<port.length;i++)

       {

           Portfolio portfolio_Object = new Portfolio();

           portfolio_Object.set_Name(port[i].split(",")[0].toString());

           portfolio_Object.set_Asset_Type(port[i].split(",")[1].toString());

           portfolio_Object.setno_of_assets(Integer.parseInt(port[i].split(",")[2]));

           array_portfolio.add(portfolio_Object);

       }

     

       for(int i=0;i<bench.length;i++)

       {

       Benchmark bench_Object = new Benchmark();

       bench_Object.set_Name(bench[i].split(",")[0].toString());

       bench_Object.set_Asset_Type(bench[i].split(",")[1].toString());

       bench_Object.setno_of_assets(Integer.parseInt(bench[i].split(",")[2]));

       array_benchmark.add(bench_Object);

      }

     

   }

   public static void Benchmark_match()

   {

       int i1=0;

       int loop_end;

     

       Collections.sort(array_portfolio, Portfolio.PortfolioComparator);

        

       if(array_portfolio.size() < array_benchmark.size())

      {

           while(i1<array_portfolio.size())

           {

               for(int j1=0;j1<array_benchmark.size();j1++)

               {

                   if(array_portfolio.get(i1).get_portfolioName().equals(array_benchmark.get(j1).get_portfolioName()) && array_portfolio.get(i1).get_Asset_Type().equals(array_benchmark.get(j1).get_Asset_Type()))

                   {

                       int differen = array_portfolio.get(i1).getno_of_assets() - array_benchmark.get(j1).getno_of_assets();

                       if(differen > 0)

                       {

                           System.out.println("\nSELL," + array_portfolio.get(i1).get_portfolioName()+","+array_portfolio.get(i1).get_Asset_Type()+","+differen);

                           array_portfolio.remove(i1);

                           array_benchmark.remove(j1);

                           break;

                       }             

                       else if(differen < 0)

                       {

                           System.out.println("\nBUY," + array_portfolio.get(i1).get_portfolioName()+","+array_portfolio.get(i1).get_Asset_Type()+","+java.lang.Math.abs(differen));

                           array_portfolio.remove(i1);

                           array_benchmark.remove(j1);

                           break;

                       }

                   }

               }

           }

         

          

           if(array_portfolio.size() > 0)

           {

               for (int k1=0;k1<array_portfolio.size();k1++)

               {

                   System.out.println("\nSELL," + array_portfolio.get(k1).get_portfolioName()+","+array_portfolio.get(k1).get_Asset_Type()+","+array_portfolio.get(k1).getno_of_assets());

                   array_portfolio.remove(k1);

               }

           }

         

           if(array_benchmark.size() > 0)

           {

               for (int k1=0;k1<array_benchmark.size();k1++)

               {

                   System.out.println("\nBUY," + array_benchmark.get(k1).get_portfolioName()+","+array_benchmark.get(k1).get_Asset_Type()+","+array_benchmark.get(k1).getno_of_assets());

                   array_benchmark.remove(k1);

               }

           }

         

           array_portfolio.clear();

           array_benchmark.clear();

       }

       else

       {

           int exitvalue=0;

           while(i1<array_benchmark.size())

           {

               if(exitvalue == array_benchmark.size())

                   break;

             

               for(int j1=0;j1<array_portfolio.size();j1++)

               {

                   if(array_portfolio.get(i1).get_portfolioName().equals(array_benchmark.get(j1).get_portfolioName()) && array_portfolio.get(i1).get_Asset_Type().equals(array_benchmark.get(j1).get_Asset_Type()))

                   {

                       int differen = array_portfolio.get(i1).getno_of_assets() - array_benchmark.get(j1).getno_of_assets();

                       if(differen > 0)

                       {

                           System.out.println("\nSELL," + array_portfolio.get(i1).get_portfolioName()+","+array_portfolio.get(i1).get_Asset_Type()+","+differen);

                           array_portfolio.remove(i1);

                           array_benchmark.remove(j1);

                           break;

                       }             

                       else if(differen < 0)

                       {

                           System.out.println("\nBUY," + array_portfolio.get(i1).get_portfolioName()+","+array_portfolio.get(i1).get_Asset_Type()+","+java.lang.Math.abs(differen));

                           array_portfolio.remove(i1);

                           array_benchmark.remove(j1);

                           break;

                       }

                       else if (differen == 0)

                       {

                           array_portfolio.remove(i1);

                           array_benchmark.remove(j1);

                           break;

                       }

                       else

                           exitvalue++;

                          

                   }

               }

           }

         

          

           if(array_portfolio.size() > 0)

           {

               for (int k1=0;k1<array_portfolio.size();k1++)

               {

                   System.out.println("\nSELL," + array_portfolio.get(k1).get_portfolioName()+","+array_portfolio.get(k1).get_Asset_Type()+","+array_portfolio.get(k1).getno_of_assets());

                   array_portfolio.remove(k1);

               }

           }

          

           if(array_benchmark.size() > 0)

           {

               for (int k1=0;k1<array_benchmark.size();k1++)

               {

                   System.out.println("\nBUY," + array_benchmark.get(k1).get_portfolioName()+","+array_benchmark.get(k1).get_Asset_Type()+","+array_benchmark.get(k1).getno_of_assets());

                   array_benchmark.remove(k1);

               }

           }

         

           array_portfolio.clear();

           array_benchmark.clear();

       }

   }

}

//Benchmark.java

//declare the function name benchmark

public class Benchmark {

private String BName;

private String Asset_Type;

private int no_of_assets;

public String get_portfolioName() {

return BName;

}

public void set_Name(String name1) {

BName = name1;

}

public String get_Asset_Type() {

return Asset_Type;

}

public void set_Asset_Type(String asset_Type) {

Asset_Type = asset_Type;

}

public int getno_of_assets() {

return no_of_assets;

}

public void setno_of_assets(int no_of_assets) {

this.no_of_assets = no_of_assets;

}

}

//Portfolio.java

import java.util.Comparator;

//declare the function name portfolio

public class Portfolio {

private String Name1;

private String Asset_Type;

private int no_of_assets;

public String get_portfolioName() {

return Name1;

}

public void set_Name(String name1) {

Name1 = name1;

}

public String get_Asset_Type() {

return Asset_Type;

}

public void set_Asset_Type(String asset_Type) {

Asset_Type = asset_Type;

}

public int getno_of_assets() {

return no_of_assets;

}

public void setno_of_assets(int no_of_assets) {

this.no_of_assets = no_of_assets;

}

public static Comparator<Portfolio> PortfolioComparator = new Comparator<Portfolio>() {

public int compare(Portfolio p1, Portfolio p2) {

String Port_folio1 = p1.get_portfolioName().toUpperCase();

String Port_folio2 = p2.get_portfolioName().toUpperCase();

return (int) (p1.get_portfolioName().compareTo(p1.get_portfolioName()));

}};

}

Add a comment
Know the answer?
Add Answer to:
We say a portfolio matches the benchmark when the number of shares of each asset in...
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
  • Which of the following is not a benefit of ETFs to investors? (a) Diversification (b) The...

    Which of the following is not a benefit of ETFs to investors? (a) Diversification (b) The ability to short-sell large portfolios of assets relatively easily (c) Being available for both stocks AND bonds, as well as other asset classes (d) The ability to trade throughout the day for NAV (e) None of the above 7. Which of the following assets is most likely to trade over-the-counter but still have high liquidity? (a) A long-term corporate bond (b) A short-term corporate...

  • 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...

  • 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...

  • In java netbean8.1 or 8.2 please. The class name is Stock. It has 5 private attributes...

    In java netbean8.1 or 8.2 please. The class name is Stock. It has 5 private attributes (name, symbol, numberOfShares, currentPrice and boughtPrice)and one static private attribute (numberOfStocks). All attributes must be initialized (name and symbol to “No name/ symbol yet” and numberOfShares, currentPrice and boughtPrice to 0. Create two constructors, one with no arguments and the other with all the attributes. (However, remember to increase the numberOfStocks in both constructors. Write the necessary mutators and accessors (getters and setters) for...

  • Investments Treasury bonds pricing quotations reveal an ask price of 104.75 and a bid price of...

    Investments Treasury bonds pricing quotations reveal an ask price of 104.75 and a bid price of 104.150. As a seller of the bond, what is the dollar price you expect to receive? $1,048.00 $1,042.50 $1,041.50 $1,041.75 $1,040.40 Cynthia Stephen’s portfolio consists of 30% common stocks, 40% bonds, 15% foreign securities and 15% short-term securities. This asset allocation would be considered to be: aggressive. moderate conservative passive. The exchange is found to be paying a 1% real rate of return. Inflation...

  • You hold 1000 shares of Rusty Company and each is worth $5. You paid $1 for...

    You hold 1000 shares of Rusty Company and each is worth $5. You paid $1 for each share several years ago. You anticipate its stock price will increase by 10% per year. You would like to sell your Rusty Company stock and buy Geeky, Inc. stock with the proceeds because you see even more upside for Geeky, Inc. How fast must Geeky, Inc. stock grow for you to be indifferent (after-tax) between: (a) holding Rusty Company stock and doing nothing...

  • Answer with True or False only for each of the questions. 1) Ignoring the length of maturity all ...

    Answer with True or False only for each of the questions. 1) Ignoring the length of maturity all debt Treasury assets are the same. 2)Bonds can be traded in both Money market and Capital market. 3)Standard and Poor ratings are more reliable that Moody’s ratings. 4)Excluding Treasury bonds, total dollar value of bond market is less than stock market. 5)In riskier economic condition TED spread would be wider. 6)Firms sell their stocks in primary market lower than its real value....

  • French Balance of Payments calculation FRANCE Balance of Payments Current Account Goods & Services Factor Income...

    French Balance of Payments calculation FRANCE Balance of Payments Current Account Goods & Services Factor Income Unilateral transfers Subtotal Tranactions during 2016 1 French citizens send in remittances to family members abroad. 2 GM transfers from his French bank account to its U.K. account. 3 Foreign investors purchase Sanofi (French) stock. 4 Peugeot (French co.) builds a plant in South Carolina. 5 SocGen (French co.) pays dividends to foreign shareholders. 6 Danone (French Co.) builds a production facility in Brazil....

  • write this program in python plz Many investment management companies are switching from manual stock trading...

    write this program in python plz Many investment management companies are switching from manual stock trading done by humans to automatic stock trading by computers. You've been tasked to write a simple automatic stock trader function that determines whether to buy, sell, or do nothing (hold) for a particular account. It should follow the old saying "Buy low, sell high!" This function takes 4 input parameters in this order: current_shares - current number of shares of this stock in the...

  • Requires Python to answer A client wishes to keep track of his investment in shares. Write...

    Requires Python to answer A client wishes to keep track of his investment in shares. Write a program to help him manage his stock portfolio. You are to record both the shares that he is holding as well as shares that he has sold. For shares be is curreatly holding, record the following data: .a 3-character share code, share name, last purchase date, volume currently held and average purchase price (refer to description under part cii) option 2) For shares...

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