Introduction
In this lab, you will learn to enhance a Stock class designed to represent stock holdings. You'll add new methods and functionality to this class, making it more versatile and useful.
The objectives of this lab include adding a sell method to the existing Stock class, creating a function to read stock portfolio data from a CSV file, and another function to display the portfolio data in a formatted table. The file to be modified is stock.py.
Adding a sell Method to the Stock Class
In this step, we're going to enhance the Stock class by adding a new method. A method is like a special function that belongs to a class and can work with the objects created from that class. We'll create a method named sell(nshares) which will help us simulate the action of selling shares of a stock. When you sell shares, the number of shares you own decreases, and this method will handle that reduction for us.
What is a Method?
Let's first understand what a method is. A method is a function that is defined inside a class. It's designed to operate on instances (which are like individual copies) of that class. When a method is called on an object, it can access all the attributes (characteristics) of that object. It does this through the self parameter. The self parameter is a reference to the object on which the method is being called. So, when you use self inside a method, you're referring to the specific object that the method is acting on.
Implementation Instructions
- First, we need to open the
stock.pyfile in the editor. To do this, we'll use the command line. Open your terminal and run the following command. This command changes the directory to theprojectfolder where thestock.pyfile is located.
cd ~/project
Once you have the
stock.pyfile open, you need to find a specific comment in theStockclass. Look for the comment## TODO: Add sell(nshares) method here. This comment is a placeholder that indicates where we should add our newsellmethod.Now, it's time to add the
sellmethod. This method will take a parameter callednshares, which represents the number of shares you want to sell. The main job of this method is to decrease thesharesattribute of theStockobject by the number of shares you're selling.
Here's the code for the sell method that you need to add:
def sell(self, nshares):
self.shares -= nshares
In this code, self.shares refers to the shares attribute of the Stock object. The -= operator subtracts the value of nshares from the current value of self.shares.
After adding the
sellmethod, you need to save thestock.pyfile. You can do this by pressingCtrl+Son your keyboard or by selecting "File > Save" from the menu in your editor.To make sure our
sellmethod works correctly, we'll create a test script. Create a new Python file calledtest_sell.pyand add the following code to it:
## test_sell.py
from stock import Stock
## Create a stock object
s = Stock('GOOG', 100, 490.10)
print(f"Initial shares: {s.shares}")
## Sell 25 shares
s.sell(25)
print(f"Shares after selling: {s.shares}")
In this script, we first import the Stock class from the stock.py file. Then we create a Stock object named s with the stock symbol GOOG, 100 shares, and a price of 490.10. We print the initial number of shares. After that, we call the sell method on the s object to sell 25 shares. Finally, we print the number of shares after the sale.
- Now, we'll run the test script to see if our
sellmethod is working as expected. Open your terminal again and run the following command:
python3 test_sell.py
If everything is working correctly, you should see output similar to this:
Initial shares: 100
Shares after selling: 75
This output confirms that our sell method is working correctly. It has successfully reduced the number of shares by the amount we specified.
Reading a Portfolio from a CSV File
In this step, we're going to create a function that reads stock data from a CSV file and returns a list of Stock objects. A Stock object represents a stock holding, and by the end of this step, you'll be able to read a portfolio of stocks from a CSV file.
Understanding CSV Files
CSV, which stands for Comma-Separated Values, is a very common format for storing tabular data. Think of it like a simple spreadsheet. Each line in a CSV file represents a row of data, and the columns within that row are separated by commas. Usually, the first line of a CSV file contains headers. These headers describe what kind of data is in each column. For example, in a stock portfolio CSV, the headers might be "Name", "Shares", and "Price".
Implementation Instructions
First, open the
stock.pyfile in your code editor. If it's already open, that's great! If not, find it and open it up. This is where we'll be adding our new function.Once the
stock.pyfile is open, look for the comment## TODO: Add read_portfolio(filename) function here. This comment is a placeholder that tells us where to put our new function.Below that comment, add the following function. This function is called
read_portfolio, and it takes a filename as an argument. The purpose of this function is to read the CSV file, extract the stock data, and create a list ofStockobjects.
def read_portfolio(filename):
"""
Read a CSV file containing portfolio data and return a list of Stock objects.
Args:
filename (str): Path to the CSV file
Returns:
list: A list of Stock objects
"""
portfolio = []
with open(filename, 'r') as f:
headers = next(f).strip().split(',') ## Skip the header line
for line in f:
row = line.strip().split(',')
name = row[0]
shares = int(row[1])
price = float(row[2])
## Create a Stock object and add it to the portfolio list
stock = Stock(name, shares, price)
portfolio.append(stock)
return portfolio
Let's break down what this function does. First, it creates an empty list called portfolio. Then, it opens the CSV file in read mode. The next(f) statement skips the first line, which is the header line. After that, it loops through each line in the file. For each line, it splits the line into a list of values, extracts the name, number of shares, and price, creates a Stock object, and adds it to the portfolio list. Finally, it returns the portfolio list.
After adding the function, save the
stock.pyfile. You can do this by pressingCtrl+Son your keyboard or by selecting "File > Save" from the menu in your code editor. Saving the file ensures that your changes are preserved.Now, we need to test our
read_portfoliofunction. Create a new Python script calledtest_portfolio.py. This script will import theread_portfoliofunction from thestock.pyfile, read the portfolio from a CSV file, and print information about each stock in the portfolio.
## test_portfolio.py
from stock import read_portfolio
## Read the portfolio from the CSV file
portfolio = read_portfolio('portfolio.csv')
## Print information about each stock
for stock in portfolio:
print(f"Name: {stock.name}, Shares: {stock.shares}, Price: ${stock.price:.2f}")
## Print the total number of stocks in the portfolio
print(f"\nTotal number of stocks in portfolio: {len(portfolio)}")
In this script, we first import the read_portfolio function. Then, we call the function with the filename portfolio.csv to get the list of Stock objects. After that, we loop through the list and print information about each stock. Finally, we print the total number of stocks in the portfolio.
- To run the test script, open your terminal or command prompt, navigate to the directory where the
test_portfolio.pyfile is located, and run the following command:
python3 test_portfolio.py
If everything is working correctly, you should see output that lists all the stocks from the portfolio.csv file, along with their names, number of shares, and prices. You should also see the total number of stocks in the portfolio.
Name: AA, Shares: 100, Price: $32.20
Name: IBM, Shares: 50, Price: $91.10
Name: CAT, Shares: 150, Price: $83.44
Name: MSFT, Shares: 200, Price: $51.23
Name: GE, Shares: 95, Price: $40.37
Name: MSFT, Shares: 50, Price: $65.10
Name: IBM, Shares: 100, Price: $70.44
Total number of stocks in portfolio: 7
This output confirms that your read_portfolio function is correctly reading the CSV file and creating Stock objects from its data.
Formatting and Printing the Portfolio Data
In this step, we're going to create a function that will help us display portfolio data in a well - organized table. A portfolio is a collection of stocks, and it's important to present this data in a clear and readable way. That's where the print_portfolio(portfolio) function comes in. This function will take a portfolio as input and display it in a table with headers and proper alignment.
String Formatting in Python
In Python, there are multiple ways to format strings. String formatting is a crucial skill as it allows you to present data in a more organized and user - friendly manner.
- The
%operator is an older style of string formatting. It's like a template where you can insert values into specific places in a string. - The
str.format()method is another way. It provides more flexibility and a cleaner syntax for formatting strings. - f - strings are a feature introduced in Python 3.6 and later. They are very convenient as they allow you to embed expressions inside string literals.
For this exercise, we'll use the % operator. It's particularly useful when you want to create fixed - width columns, which is exactly what we need for our portfolio table.
Implementation Instructions
First, open the
stock.pyfile in your editor. If it's already open, that's great. This file is where we'll write ourprint_portfoliofunction.Once the file is open, look for the
## TODO: Add print_portfolio(portfolio) function herecomment. This comment is a marker that tells us where to add our new function.Below that comment, add the following function:
def print_portfolio(portfolio):
"""
Print the portfolio data in a nicely formatted table.
Args:
portfolio (list): A list of Stock objects
"""
## Print the header row
print('%10s %10s %10s' % ('name', 'shares', 'price'))
## Print a separator line
print('-' * 10 + ' ' + '-' * 10 + ' ' + '-' * 10)
## Print each stock in the portfolio
for stock in portfolio:
print('%10s %10d %10.2f' % (stock.name, stock.shares, stock.price))
This function first prints the header row of the table, then a separator line, and finally, it loops through each stock in the portfolio and prints its details in a formatted way.
After adding the function, save the file. You can do this by pressing
Ctrl+Sor by selecting "File > Save" from the menu. Saving the file ensures that your changes are preserved.Now, we need to test our function. Create a new file called
test_print.py. This file will be our test script. Add the following code to it:
## test_print.py
from stock import read_portfolio, print_portfolio
## Read the portfolio from the CSV file
portfolio = read_portfolio('portfolio.csv')
## Print the portfolio as a formatted table
print_portfolio(portfolio)
This script imports the read_portfolio and print_portfolio functions from the stock.py file. It then reads the portfolio data from a CSV file and uses our newly created print_portfolio function to display it.
- Finally, run the test script. Open your terminal and enter the following command:
python3 test_print.py
If everything is working correctly, you should see output like this:
name shares price
---------- ---------- ----------
AA 100 32.20
IBM 50 91.10
CAT 150 83.44
MSFT 200 51.23
GE 95 40.37
MSFT 50 65.10
IBM 100 70.44
This output confirms that your print_portfolio function is working as expected. It formats and displays the portfolio data in a table with headers and aligned columns, making it easy to read.
Understanding the String Formatting
Let's take a closer look at how the string formatting works in the print_portfolio function.
%10sis used to format a string. The10indicates the width of the field, and thesstands for string. It aligns the string to the right within a field of width 10.%10dis for formatting an integer. The10is the field width, anddrepresents an integer. It also aligns the integer to the right in a field of width 10.%10.2fis used for formatting a float. The10is the field width, and the.2specifies that we want to display the float with 2 decimal places. It aligns the float to the right in a field of width 10.
This formatting ensures that all columns in our table are properly aligned, which makes the output much easier to read and understand.
Summary
In this lab, you have learned how to enhance a Stock class with new functionality. You added a sell method to simulate selling shares, created a read_portfolio function to read stock data from a CSV file and convert it into Stock objects, and developed a print_portfolio function to display portfolio data in a well - formatted table.
These skills, including defining methods in a class, working with files and parsing data, and formatting output for better readability, are fundamental to object - oriented programming in Python. You can now apply these concepts to create more complex classes and utilities in your Python programs.