Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Python Programming Mock Exam

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Python Programming Mock Exam

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Python Programming Mock Exam

Alexandre Landi

Skema Business School

Programme Grande Ecole - Master 1 (PGE M1)

Academic Year 2024-25 - Fall Term

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

5 for sheet in sheets :


6 df = pd . read_excel ( xls , sheet_name = sheet )
7 df [ ’ Sheet Name ’] = sheet
8 df . dropna ( subset =[ ’ Market Capitalization ’] , inplace = True )
9 data_frames . append ( df )
10

11 combined_data = pd . concat ( data_frames )


12 combined_data [ ’ Market Cap ( Billion ) ’] = combined_data [ ’ Market Capitalization ’] / 1 e9

1. It reads all sheet names from the Excel file into a list.

2. It reads data from each sheet and appends it to a list of DataFrames.

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)

1. It filters the dataset to include only companies in the Technology sector.

2. It further filters the dataset to include only companies that went public after 2015.

3. It sorts the filtered dataset by market capitalization in descending order.

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.

2. It calculates decile-based quantiles for the closing stock prices.

3. It generates a bar plot of the calculated deciles.

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.

4. It retrieves data from multiple data sources simultaneously.

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 ’ ]]

1. It reads data from an Excel sheet named ’Industry Overview’.

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.

4. It calculates the average market capitalization for 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.

2. It calculates daily percentage changes (returns) for the selected stocks.

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.

5. It saves the correlation matrix to an Excel file for further analysis.

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.

2. It calculates cumulative returns by compounding daily returns over time.

3. It generates a time series plot of the cumulative returns.

4. It calculates the rolling average of daily returns over a fixed window.

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.

3. It computes rolling 1-year returns (as a percentage) using a 252-day window.

4. It generates a bar plot of rolling returns over the specified window.

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.

2. It uses a seed value to ensure reproducibility of the random number generation.

3. It converts the random returns into a simulated stock price path over time.

4. It visualizes the simulated stock price path as a line plot.

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.

2. It removes rows where the Sector column has missing values.

3. It identifies the company with the highest market capitalization in each sector.

4. It creates a ranking of companies by market capitalization across all sectors.

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.

2. It creates an Excel file named financial_data.xlsx with multiple sheets.

3. It calculates daily percentage changes (returns) and writes them to a sheet.

4. It calculates the correlation matrix for the dataset and writes it to a sheet.

5. It saves the Excel file to a specified directory for later use.

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.

4. It creates a ranking of all companies by market capitalization across sectors.

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 )

1. It calculates the average market capitalization for each sector.

2. It calculates the median market capitalization for each sector.

3. It creates a DataFrame summarizing the average and median market capitalizations by sector.

4. It sorts the sectors by average market capitalization in descending order.

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 ()

1. It calculates the average daily return for each sector.

2. It creates a new column in the dataset to store sector-level average returns.

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.

5. It calculates cumulative sector returns over the specified period.

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.

2. It computes rolling volatility using a 60-day window.

3. It calculates annualized volatility from the rolling 60-day volatility.

4. It generates a time series plot of the annualized volatility.

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.

2. It creates a ranking of sectors based on their volatility.

3. It generates a bar chart to visualize sector-wise volatility.

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.

4. It calculates the average correlation over the entire dataset.

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.

2. It creates a simulated stock price path based on the random returns.

3. It visualizes the simulated stock price path as a line plot.

4. It calculates the average return for the simulated stock prices.

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 } " )

1. It calculates the percentage change in stock prices over a 3-day period.

2. It creates a new column for the stock price shifted by 3 days.

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

You might also like