Python provides several powerful tools and libraries for formatting and manipulating stock portfolio data. In this section, we will explore how to use Python to format a table of stock portfolio data.
Importing Required Libraries
To format the stock portfolio data, we will use the following Python libraries:
import pandas as pd
pandas
is a widely-used library for data manipulation and analysis in Python.
Creating a Sample Stock Portfolio Data
Let's start by creating a sample stock portfolio data in the form of a Python dictionary:
portfolio_data = {
'Ticker': ['AAPL', 'MSFT', 'AMZN', 'GOOG', 'TSLA'],
'Company Name': ['Apple Inc.', 'Microsoft Corporation', 'Amazon.com, Inc.', 'Alphabet Inc.', 'Tesla, Inc.'],
'Shares Owned': [100, 50, 25, 20, 15],
'Purchase Price': [120.50, 250.75, 3000.00, 2500.00, 650.00],
'Current Price': [135.25, 280.10, 3150.00, 2750.00, 750.00]
}
Creating a Pandas DataFrame
Next, we'll convert the dictionary into a pandas
DataFrame, which will provide a structured and tabular representation of the data:
df = pd.DataFrame(portfolio_data)
Now, let's format the portfolio data to make it more readable and informative:
df['Total Investment'] = df['Shares Owned'] * df['Purchase Price']
df['Current Value'] = df['Shares Owned'] * df['Current Price']
df['Unrealized Gain/Loss'] = df['Current Value'] - df['Total Investment']
df = df[['Ticker', 'Company Name', 'Shares Owned', 'Purchase Price', 'Current Price', 'Total Investment', 'Current Value', 'Unrealized Gain/Loss']]
df = df.round(2)
In this code, we:
- Calculate the 'Total Investment' and 'Current Value' for each stock.
- Calculate the 'Unrealized Gain/Loss' for each stock.
- Rearrange the columns to a more logical order.
- Round the numeric values to two decimal places.
The resulting DataFrame
will now have a well-formatted table of the stock portfolio data.