

























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


























































































Question 1. Which Python data type is most appropriate for storing a series of daily closing prices that will never be altered after creation? A) list B) tuple C) set D) dictionary Answer: B Explanation: A tuple is immutable, making it ideal for data that should remain unchanged, such as a fixed series of closing prices. Question 2. In Python, what is the result of the expression 0.1 + 0.2 == 0.3? A) True B) False C) Raises a TypeError D) Returns None Answer: B Explanation: Due to floating‑point precision, 0.1 + 0.2 yields 0.30000000000000004, which is not exactly equal to 0.3. Question 3. Which operator would you use to test if a variable price is greater than or equal to a threshold value of 100? A) = B) == C) >= D) <>
Answer: C Explanation: The >= operator checks for “greater than or equal to” relationships. Question 4. In a for loop iterating over prices = [101, 102, 98], which statement correctly prints each price? A) for i in prices: print(i) B) for i in range(prices): print(i) C) while i < len(prices): print(prices[i]) D) for i in prices: print(prices[i]) Answer: A Explanation: for i in prices iterates directly over list elements; print(i) outputs each price. Question 5. Which of the following best describes the purpose of a try/except block in financial data processing? A) To speed up calculations B) To handle anticipated runtime errors such as missing data C) To create graphical plots D) To encrypt sensitive information Answer: B Explanation: try/except allows graceful handling of errors like KeyError or division by zero that may arise with financial datasets. Question 6. What is the output type of np.mean(np.array([1,2,3]))? A) list
Question 9. Which of the following statements correctly creates a Pandas Series named returns from a Python list r = [0.01, - 0.02, 0.03]? A) returns = pd.Series(r, index=['Day1','Day2','Day3']) B) returns = pd.DataFrame(r) C) returns = pd.Series(r).astype(str) D) returns = pd.Series(r).set_index('Day') Answer: A Explanation: pd.Series converts a list to a Series; providing a custom index labels each element. Question 10. Which Pandas function would you use to compute the correlation matrix of a DataFrame df containing asset returns? A) df.cov() B) df.mean() C) df.corr() D) df.describe() Answer: C Explanation: df.corr() returns the pairwise correlation coefficients between columns. Question 11. When resampling a daily price series to monthly frequency, which Pandas method and rule would you typically apply? A) df.resample('M').sum() B) df.resample('M').last() C) df.resample('D').first() D) df.resample('W').mean()
Answer: B Explanation: Resampling with 'M' groups by month; .last() captures the final (closing) price of each month. Question 12. In a rolling window calculation, what does df['MA20'] = df['Close'].rolling(window=20).mean() compute? A) 20‑day exponential moving average B) Simple moving average of the last 20 closing prices C) Standard deviation of the last 20 closing prices D) Cumulative sum of closing prices over 20 days Answer: B Explanation: .rolling(window=20).mean() calculates a simple moving average over the specified window size. Question 13. Which of the following best describes the Sharpe Ratio? A) Return divided by total assets B) Excess return over risk‑free rate per unit of volatility C) Maximum drawdown divided by portfolio value D) Ratio of winning trades to total trades Answer: B Explanation: Sharpe Ratio = (Portfolio Return – Risk‑Free Rate) / Standard Deviation of Returns. Question 14. How do you compute log returns from a price series P using NumPy? A) np.diff(P) / P[:-1]
Question 17. Which NumPy function would you use to generate 1,000 random draws from a standard normal distribution? A) np.random.rand(1000) B) np.random.normal(0, 1, 1000) C) np.random.uniform(-1, 1, 1000) D) np.random.binomial(1, 0.5, 1000) Answer: B Explanation: np.random.normal allows specification of mean and standard deviation; (0,1) yields a standard normal. Question 18. In a Monte Carlo simulation of portfolio returns, which step is essential before aggregating results? A) Sorting the returns alphabetically B) Converting all returns to percentages C) Randomly sampling correlated asset returns using a Cholesky‑decomposed covariance matrix D) Removing all negative returns Answer: C Explanation: To preserve correlation structure, one multiplies standard normal draws by the Cholesky factor of the covariance matrix. Question 19. Which of the following best describes Geometric Brownian Motion (GBM) in asset price modeling? A) Prices follow a deterministic linear trend B) Log returns are normally distributed with constant drift and volatility C) Prices revert to a long‑term mean
D) Prices jump discontinuously at random times Answer: B Explanation: GBM assumes continuous compounding, with log returns normally distributed, capturing drift (μ) and volatility (σ). Question 20. When using the Yahoo Finance API via yfinance, which method retrieves historical daily data for ticker "AAPL"? A) yf.download('AAPL', period='1d') B) yf.Ticker('AAPL').history(interval='1d') C) yf.get('AAPL', start='2020- 01 - 01') D) yf.fetch('AAPL', freq='daily') Answer: B Explanation: Ticker.history with interval='1d' returns daily OHLCV data for the specified ticker. Question 21. In a backtesting loop, why is it important to separate “signal generation” from “order execution”? A) To improve plot aesthetics B) To avoid look‑ahead bias by ensuring decisions are based only on information available at that time C) To reduce file size of logs D) To increase CPU usage Answer: B Explanation: Keeping signal and execution distinct ensures the strategy does not inadvertently use future data.
D) read('prices.csv') Answer: B Explanation: The with context manager automatically closes the file when the block exits. Question 25. In the context of portfolio optimization, what does the term “efficient frontier” refer to? A) The set of portfolios with the highest possible return for a given level of risk B) The line connecting the minimum and maximum asset weights C) The curve showing transaction costs over time D) The boundary where all assets have equal weight Answer: A Explanation: The efficient frontier represents optimal risk‑return trade‑offs under mean‑variance theory. Question 26. Which of the following is a valid way to create a dictionary that maps ticker symbols to their market caps using a list of tuples data = [('AAPL', 2.4e12), ('MSFT', 2.1e12)]? A) dict(data) B) {data} C) list(data) D) set(data) Answer: A Explanation: Passing an iterable of key‑value pairs to dict() constructs the desired mapping. Question 27. When performing a left join between DataFrames prices and fundamentals on column ticker, which Pandas method is appropriate?
A) prices.merge(fundamentals, on='ticker', how='right') B) prices.concat(fundamentals, axis=1) C) prices.merge(fundamentals, on='ticker', how='left') D) prices.join(fundamentals, on='ticker') Answer: C Explanation: merge with how='left' keeps all rows from prices and adds matching rows from fundamentals. Question 28. Which of the following best describes a “set” in Python? A) An ordered collection that allows duplicates B) An unordered collection of unique elements C) A mutable mapping from keys to values D) A fixed‑size array of numbers Answer: B Explanation: Sets store each element only once and have no defined order. Question 29. In Matplotlib, which function would you use to create a histogram of daily returns stored in a NumPy array ret? A) plt.plot(ret) B) plt.scatter(ret) C) plt.hist(ret, bins=30) D) plt.bar(ret) Answer: C Explanation: plt.hist plots the distribution of data as a histogram; bins controls granularity.
C) replace(np.nan, 0) D) interpolate() Answer: B Explanation: method='ffill' propagates the last valid observation forward. Question 33. In a binomial option pricing model, what does the parameter u typically represent? A) The risk‑free rate per period B) The up‑move factor for the underlying asset price C) The probability of an up move D) The dividend yield Answer: B Explanation: In the Cox‑Ross‑Rubinstein model, u is the factor by which the price increases on an up‑move. Question 34. Which of the following is the correct way to compute the covariance matrix of a DataFrame returns using NumPy? A) np.cov(returns) B) np.cov(returns.T) C) np.cov(returns.values) D) np.cov(returns.values.T) Answer: D Explanation: np.cov expects variables in rows; transposing the values matrix aligns assets as rows.
Question 35. Which of the following Python list comprehensions creates a list of squared returns from a list r = [0.01, - 0.02, 0.03]? A) [x**2 for x in r] B) [x*2 for x in r] C) [r**2 for r in r] D) list(map(lambda x: x**2, r)) Answer: A Explanation: The comprehension iterates over each element x and computes x**2. Question 36. In the context of time‑series analysis, what does the term “stationary” mean? A) The series has a constant mean and variance over time B. The series never changes its values C. The series only moves upward D. The series is stored in a stationary file format Answer: A Explanation: Stationarity implies statistical properties (mean, variance, autocorrelation) are time‑invariant, a key assumption for many models. Question 37. Which of the following best describes the purpose of the iloc accessor in Pandas? A) Select rows and columns by label names B) Select rows and columns by integer‑based position C) Perform a left join on two DataFrames D) Convert a DataFrame to a NumPy array
B) except KeyError and ZeroDivisionError: C) except KeyError, ZeroDivisionError: D) except KeyError | ZeroDivisionError: Answer: A Explanation: Parentheses allow multiple exception types to be handled together. Question 41. When using np.linalg.eig on a covariance matrix, what does the resulting eigenvector matrix represent in finance? A) The original price series B) Principal components that explain variance in asset returns C) The dividend yield of each asset D) The risk‑free rate over time Answer: B Explanation: Eigenvectors of the covariance matrix are the directions of maximal variance, forming the basis for PCA. Question 42. Which of the following is the most efficient way to compute the cumulative product of daily gross returns stored in a Pandas Series gross? A) gross.cumprod() B) np.cumprod(gross) C) gross.apply(lambda x: x.prod()) D) gross.sum() Answer: A Explanation: cumprod directly returns the running product, ideal for compounding returns.
Question 43. In a Python script, which statement correctly checks whether a variable price is a float before performing a calculation? A) if type(price) == float: B) if isinstance(price, float): C) if price.is_float(): D) if price instanceof float: Answer: B Explanation: isinstance safely checks object type, supporting subclassing. Question 44. Which of the following Pandas functions would you use to convert a column date_str containing strings like "2023- 01 - 31" into proper datetime objects? A) pd.to_datetime(df['date_str']) B) df['date_str'].astype(datetime) C) datetime.strptime(df['date_str']) D) df['date_str'].convert() Answer: A Explanation: pd.to_datetime parses strings into pandas datetime64[ns] values. Question 45. In a Monte Carlo simulation of GBM, which discretized formula correctly updates the price S_t to S_{t+Δt}? A) S_t * np.exp((mu - 0.5*sigma**2)*dt + sigma*np.sqrt(dt)*z) where z ~ N(0,1) B) S_t + mu*dt + sigma*z*dt C) S_t * (1 + mu*dt + sigma*z*dt)
Question 48. In Pandas, which method would you use to obtain a DataFrame that contains only the rows where the column volume exceeds 1,000,000? A) df.where(df['volume'] > 1_000_000) B) df.loc[df['volume'] > 1_000_000] C) df.filter(df['volume'] > 1_000_000) D) df.select(df['volume'] > 1_000_000) Answer: B Explanation: Boolean indexing with .loc returns rows meeting the condition. Question 49. Which of the following NumPy functions would you use to compute the element‑wise maximum between two arrays a and b? A) np.max(a, b) B) np.maximum(a, b) C) np.max([a, b]) D) np.where(a > b, a, b) Answer: B Explanation: np.maximum returns an array containing the larger element from each pair. Question 50. When creating a line chart of stock prices over time with Matplotlib, which command sets the x‑axis label to “Date”? A) plt.xlabel('Date') B) plt.title('Date') C) plt.xaxis('Date') D) plt.axis('Date')
Answer: A Explanation: plt.xlabel defines the label for the horizontal axis. Question 51. Which of the following best explains why vectorized operations in NumPy are generally faster than Python loops? A) They use compiled C code and avoid Python interpreter overhead B) They automatically run on GPU without extra libraries C) They store data in text files for faster access D) They parallelize across multiple processes automatically Answer: A Explanation: NumPy operations are executed in optimized C loops, reducing interpreter overhead. Question 52. In a Pandas groupby operation, which method would you use to compute the mean return for each sector stored in column sector? A) df.groupby('sector').mean() B) df.groupby('sector').agg('mean') C) Both A and B D) df.groupby('sector').sum() Answer: C Explanation: Both mean() and agg('mean') produce the same result for grouped means. Question 53. Which of the following statements correctly creates a set of unique ticker symbols from a list tickers = ['AAPL','MSFT','AAPL','GOOG']? A) unique = set(tickers)