Python Programming Mock Exam
Python Programming Mock Exam
Alexandre Landi
Question 1
What does this code snippet accomplish? (Select all that apply.)
1 xls = pd . ExcelFile ( ’ market_data . xlsx ’)
2 sheets = xls . sheet_names
3 data_frames = []
4
1. It reads all sheet names from the Excel file into a list.
3. It adds a new column to each DataFrame indicating the sheet name it came from.
4. It removes rows with missing values in the Market Capitalization column before combining the data.
5. It adds a new column to the combined DataFrame converting market capitalization to billions.
1
Question 2
What does this code snippet accomplish? (Select all that apply.)
1 df = pd . read_excel ( ’ company_list . xlsx ’)
2 df = df [ df [ ’ Sector ’] == ’ Technology ’]
3 df = df [ df [ ’ IPO Year ’] >= 2015]
4 df = df . sort_values ( ’ Market Capitalization ’ , ascending = False )
5 top_5 = df [[ ’ Company Name ’ , ’ Market Capitalization ’ , ’ IPO Year ’ ]]. head (5)
2. It further filters the dataset to include only companies that went public after 2015.
4. It selects the top 5 companies by market capitalization and includes their IPO year.
5. It adds a new column ranking companies within the Technology sector by market capitalization.
2
Question 3
What does this code snippet accomplish? (Select all that apply.)
1 stock_data = pd . read_csv ( ’ stock_prices . csv ’ , parse_dates =[ ’ date ’] , index_col = ’ date ’)
2 deciles = stock_data [ ’ Close ’ ]. quantile ([0.1 * i for i in range (1 , 10) ])
3 deciles . plot ( kind = ’ bar ’ , title = ’ Stock Price Deciles ’)
4 plt . xlabel ( ’ Quantile ’)
5 plt . ylabel ( ’ Stock Price ’)
6 plt . tight_layout ()
7 plt . show ()
1. It reads stock price data from a CSV file and sets the date column as the index.
4. It calculates and visualizes the average stock price for each quantile.
5. It saves the plotted deciles to an external image file for further use.
3
Question 4
What does this code snippet accomplish? (Select all that apply.)
1 from pa ndas_d atarea der . data import DataReader
2 from datetime import date
3
4 ticker = ’ AAPL ’
5 data_source = ’ yahoo ’
6 start_date = date (2018 , 1 , 1)
7 end_date = date (2020 , 12 , 31)
8
9 stock_data = DataReader ( ticker , data_source , start_date , end_date )
1. It retrieves historical stock price data for Apple Inc. (ticker: AAPL) from Yahoo Finance.
2. It fetches stock price data for the specified time period between January 1, 2018, and December 31,
2020.
3. It calculates daily returns for the Apple stock and adds them to the dataset.
5. It saves the retrieved stock price data to a local file for further analysis.
4
Question 5
What does this code snippet accomplish? (Select all that apply.)
1 data = pd . read_excel ( ’ industry_data . xlsx ’ , sheet_name = ’ Industry Overview ’)
2 data [ ’ Market Capitalization ’] = data [ ’ Market Capitalization ’] / 1 e6 # Convert to
million USD
3 top_by_sector = data . groupby ( ’ Sector ’) [ ’ Market Capitalization ’ ]. idxmax ()
4 top_companies = data . loc [ top_by_sector , [ ’ Company Name ’ , ’ Sector ’ , ’ Market
Capitalization ’ ]]
2. It converts the market capitalization values to millions of USD for easier readability.
3. It identifies the company with the highest market capitalization in each sector.
5. It filters out sectors with fewer than 5 companies before identifying the top company in each sector.
5
Question 6
What does this code snippet accomplish? (Select all that apply.)
1 from pa ndas_d atarea der . data import DataReader
2
3 tickers = [ ’ MSFT ’ , ’ GOOGL ’ , ’ AMZN ’]
4 data = DataReader ( tickers , ’ yahoo ’ , start = ’ 2019 -01 -01 ’ , end = ’ 2020 -12 -31 ’) [ ’ Close ’]
5 daily_returns = data . pct_change ()
6 correl at io n_ ma tr ix = daily_returns . corr ()
7
8 sns . heatmap ( correlation_matrix , annot = True )
9 plt . title ( ’ Correlation of Daily Returns ’)
10 plt . show ()
1. It retrieves historical stock price data for multiple companies from Yahoo Finance.
3. It computes and visualizes the correlation matrix of daily returns for the selected stocks.
4. It calculates the cumulative returns for each stock over the specified period.
6
Question 7
What does this code snippet accomplish? (Select all that apply.)
1 stock_data = pd . read_csv ( ’ stock_data . csv ’ , parse_dates =[ ’ date ’] , index_col = ’ date ’)
2 rolling_stats = stock_data [ ’ Close ’ ]. rolling ( ’ 180 D ’) . agg ([ ’ mean ’ , ’ std ’ ])
3 rolling_stats . plot ( subplots = True , title = ’ Rolling Statistics (180 Days ) ’)
4 plt . tight_layout ()
5 plt . show ()
1. It reads stock price data from a CSV file and sets the date column as the index.
2. It calculates the rolling mean and standard deviation of closing prices using a 180-day window.
3. It creates a DataFrame containing the rolling mean and standard deviation of closing prices.
4. It generates a plot of the rolling statistics, with separate subplots for mean and standard deviation.
5. It calculates cumulative returns for the stock prices over a 180-day period.
7
‘
Question 8
What does this code snippet accomplish? (Select all that apply.)
1 daily_returns = stock_data [ ’ Close ’ ]. pct_change ()
2 cumula ti ve _r et ur ns = ( daily_returns + 1) . cumprod () - 1
3 cumula ti ve _r et ur ns . plot ( title = ’ Cumulative Returns ’)
4 plt . xlabel ( ’ Date ’)
5 plt . ylabel ( ’ Cumulative Return ’)
6 plt . tight_layout ()
7 plt . show ()
1. It calculates the daily percentage changes (returns) for the stock’s closing prices.
5. It saves the cumulative returns data to a CSV file for further analysis.
8
Question 9
What does this code snippet accomplish? (Select all that apply.)
1 def c a l c u l a t e _ r o l l i n g _ r e t u r n ( returns , window ) :
2 return ( returns . rolling ( window ) . apply ( lambda x : ( x + 1) . prod () - 1) ) . mul (100)
3
4 daily_returns = stock_data [ ’ Close ’ ]. pct_change ()
5 rollin g_ 1y r_ re tu rn = c a l c u l a t e _ r o l l i n g _ r e t u r n ( daily_returns , 252)
6 rollin g_ 1y r_ re tu rn . plot ( title = ’ Rolling 1 - Year Return ’)
7 plt . xlabel ( ’ Date ’)
8 plt . ylabel ( ’ Return (%) ’)
9 plt . tight_layout ()
10 plt . show ()
1. It defines a custom function to calculate rolling compounded returns over a specified window.
2. It calculates daily percentage changes (returns) for the stock’s closing prices.
5. It saves the rolling 1-year return data to a local file for further analysis.
9
Question 10
What does this code snippet accomplish? (Select all that apply.)
1 from numpy . random import normal , seed
2
3 seed (123)
4 simulated _retur ns = normal ( loc =0.0005 , scale =0.02 , size =252)
5 price_series = ( si mulate d_retu rns + 1) . cumprod ()
6
7 plt . plot ( price_series , label = ’ Simulated Price Path ’)
8 plt . title ( ’ Simulated Stock Price Path ’)
9 plt . xlabel ( ’ Days ’)
10 plt . ylabel ( ’ Price ’)
11 plt . legend ()
12 plt . tight_layout ()
13 plt . show ()
1. It generates a series of 252 random daily returns with a mean of 0.0005 and a standard deviation of
0.02.
3. It converts the random returns into a simulated stock price path over time.
5. It calculates the average and standard deviation of the simulated stock price path.
10
Question 11
What does this code snippet accomplish? (Select all that apply.)
1 nyse_data = pd . read_excel ( ’ nyse_listings . xlsx ’ , sheet_name = ’ NY List ’)
2 nyse_data . set_index ( ’ Ticker ’ , inplace = True )
3 nyse_data . dropna ( subset =[ ’ Sector ’] , inplace = True )
4 top_by_sector = nyse_data . groupby ( ’ Sector ’) [ ’ Market Cap ’ ]. idxmax ()
5 top_companies = nyse_data . loc [ top_by_sector , [ ’ Company Name ’ , ’ Sector ’ , ’ Market Cap ’ ]]
6 top_companies . sort_values ( ’ Market Cap ’ , ascending = False , inplace = True )
1. It reads data from an Excel sheet and sets the ticker symbols as the DataFrame index.
3. It identifies the company with the highest market capitalization in each sector.
5. It saves the top companies’ data to an external file for reporting purposes.
11
Question 12
What does this code snippet accomplish? (Select all that apply.)
1 data . index = data . index . date # Convert index to date only
2 with pd . ExcelWriter ( ’ financial_data . xlsx ’) as writer :
3 data . to_excel ( writer , sheet_name = ’ Prices ’)
4 data . pct_change () . to_excel ( writer , sheet_name = ’ Daily Returns ’)
5 data . corr () . to_excel ( writer , sheet_name = ’ Correlations ’)
1. It modifies the index of the DataFrame to include only the date component.
4. It calculates the correlation matrix for the dataset and writes it to a sheet.
12
Question 13
What does this code snippet accomplish? (Select all that apply.)
1 nasdaq_data = pd . read_excel ( ’ nasdaq_listings . xlsx ’ , sheet_name = ’ NASDAQ ’)
2 nasdaq_data . dropna ( subset =[ ’ Sector ’] , inplace = True )
3 nasdaq_data [ ’ Market Cap ( M ) ’] = nasdaq_data [ ’ Market Cap ’] / 1 e6 # Convert to millions
4 largest_b y_sect or = nasdaq_data . groupby ( ’ Sector ’) [ ’ Market Cap ( M ) ’ ]. idxmax ()
5 sector_leaders = nasdaq_data . loc [ largest_by_sector , [ ’ Company Name ’ , ’ Sector ’ , ’ Market
Cap ( M ) ’ ]]
6 sector_leaders . sort_values ( ’ Market Cap ( M ) ’ , ascending = False , inplace = True )
1. It filters out rows where the Sector column has missing values.
2. It converts the market capitalization values to millions of USD for easier readability.
3. It identifies the company with the largest market capitalization in each sector.
5. It exports the data of sector leaders to a CSV file for reporting purposes.
13
Question 14
What does this code snippet accomplish? (Select all that apply.)
1 sector_avg = nasdaq_data . groupby ( ’ Sector ’) [ ’ Market Cap ’ ]. mean ()
2 sector_median = nasdaq_data . groupby ( ’ Sector ’) [ ’ Market Cap ’ ]. median ()
3 summary = pd . DataFrame ({ ’ Average Market Cap ’: sector_avg , ’ Median Market Cap ’:
sector_median })
4 summary . sort_values ( ’ Average Market Cap ’ , ascending = False , inplace = True )
3. It creates a DataFrame summarizing the average and median market capitalizations by sector.
5. It filters out sectors with fewer than 5 companies before calculating the statistics.
14
Question 15
What does this code snippet accomplish? (Select all that apply.)
1 import matplotlib . pyplot as plt
2
3 data [ ’ Sector Returns ’] = data . groupby ( ’ Sector ’) [ ’ Daily Return ’ ]. transform ( ’ mean ’)
4 sector_summary = data . groupby ( ’ Sector ’) [ ’ Sector Returns ’ ]. mean ()
5 sector_summary . plot ( kind = ’ bar ’ , title = ’ Average Sector Returns ’)
6 plt . xlabel ( ’ Sector ’)
7 plt . ylabel ( ’ Average Daily Return ’)
8 plt . tight_layout ()
9 plt . show ()
3. It generates a bar chart to visualize the average daily returns for each sector.
4. It saves the sector summary statistics to a CSV file for further analysis.
15
Question 16
What does this code snippet accomplish? (Select all that apply.)
1 daily_returns = data [ ’ Close ’ ]. pct_change ()
2 rollin g_ vo la ti li ty = daily_returns . rolling ( window =60) . std ()
3 ann ua l i z e d _ v o l a t i l i t y = r ol li ng _v ola ti li ty * (252**0.5)
4 ann ua l i z e d _ v o l a t i l i t y . plot ( title = ’60 - Day Annualized Volatility ’)
5 plt . xlabel ( ’ Date ’)
6 plt . ylabel ( ’ Volatility (%) ’)
7 plt . tight_layout ()
8 plt . show ()
1. It calculates daily percentage changes (returns) for the stock’s closing prices.
5. It saves the annualized volatility data to a CSV file for further analysis.
16
Question 17
What does this code snippet accomplish? (Select all that apply.)
1 sector_vo latili ty = data . groupby ( ’ Sector ’) [ ’ Daily Return ’ ]. std ()
2 sector_vo latili ty . sort_values ( ascending = False , inplace = True )
3 sector_vo latili ty . plot ( kind = ’ bar ’ , title = ’ Sector - Wise Volatility ’)
4 plt . xlabel ( ’ Sector ’)
5 plt . ylabel ( ’ Volatility ’)
6 plt . tight_layout ()
7 plt . show ()
1. It calculates the standard deviation of daily returns (volatility) for each sector.
4. It calculates cumulative volatility for each sector over the specified period.
5. It exports the sector volatility data to an Excel file for further analysis.
17
Question 18
What does this code snippet accomplish? (Select all that apply.)
1 rolling_corr = data [ ’ Stock A ’ ]. rolling ( window =90) . corr ( data [ ’ Stock B ’ ])
2 rolling_corr . plot ( title = ’90 - Day Rolling Correlation ’)
3 plt . xlabel ( ’ Date ’)
4 plt . ylabel ( ’ Correlation ’)
5 plt . tight_layout ()
6 plt . show ()
1. It calculates the rolling correlation between two stocks over a 90-day window.
2. It generates a time series plot of the rolling correlation between the two stocks.
3. It identifies periods of strong positive or negative correlation between the two stocks.
5. It saves the rolling correlation data to a local file for further analysis.
18
Question 19
What does this code snippet accomplish? (Select all that apply.)
1 from numpy . random import normal , seed
2
3 seed (10)
4 returns = normal ( loc =0.001 , scale =0.02 , size =252)
5 simulated_prices = pd . Series (( returns + 1) . cumprod () , name = ’ Simulated Prices ’)
6 simulated_prices . plot ( title = ’ Simulated Price Path ’)
7 plt . xlabel ( ’ Days ’)
8 plt . ylabel ( ’ Price ’)
9 plt . tight_layout ()
10 plt . show ()
1. It generates 252 random daily returns with a mean of 0.001 and a standard deviation of 0.02.
5. It saves the simulated prices to an external CSV file for further analysis.
19
Question 20
What does this code snippet accomplish? (Select all that apply.)
1 data [ ’3 - Day Return ’] = data [ ’ Close ’ ]. pct_change ( periods =3)
2 data [ ’ Shifted Price ’] = data [ ’ Close ’ ]. shift ( periods =3)
3 correlation = data [[ ’3 - Day Return ’ , ’ Shifted Price ’ ]]. corr () . iloc [0 , 1]
4 print ( f " Correlation between 3 - Day Return and Shifted Price : { correlation :.2 f } " )
3. It computes the correlation between the 3-day return and the shifted price.
4. It identifies the stock price with the highest return over a 3-day period.
5. It generates a line plot to visualize the relationship between 3-day returns and shifted prices.
20