Bird
Raised Fist0
Data Analysis Pythondata~20 mins

Financial data analysis pattern in Data Analysis Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Financial Data Analysis Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Calculate Moving Average of Stock Prices
Given daily closing prices of a stock, what is the output of the following code that calculates a 3-day moving average?
Data Analysis Python
import pandas as pd
prices = pd.Series([100, 102, 101, 105, 107])
moving_avg = prices.rolling(window=3).mean()
print(moving_avg.tolist())
A[nan, nan, 101.0, 103.0, 106.0]
B[100, 102, 101, 105, 107]
C[100.0, 101.0, 101.0, 102.66666666666667, 104.33333333333333]
D[nan, nan, 101.0, 102.66666666666667, 104.33333333333333]
Attempts:
2 left
💡 Hint
Think about how rolling averages handle the first few values when the window is not full.
❓ data_output
intermediate
2:00remaining
Identify the Date with Highest Daily Return
Given a DataFrame of stock closing prices indexed by date, which date has the highest daily return calculated by percentage change?
Data Analysis Python
import pandas as pd

data = {'Close': [100, 105, 103, 110, 108]}
dates = pd.to_datetime(['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05'])
df = pd.DataFrame(data, index=dates)
df['Return'] = df['Close'].pct_change()
max_return_date = df['Return'].idxmax()
print(max_return_date.strftime('%Y-%m-%d'))
A2024-01-04
B2024-01-02
C2024-01-05
D2024-01-03
Attempts:
2 left
💡 Hint
Calculate percentage change between consecutive days and find the max.
❓ visualization
advanced
3:00remaining
Plot Cumulative Returns Over Time
Which option produces the correct plot of cumulative returns from daily returns in a DataFrame?
Data Analysis Python
import pandas as pd
import matplotlib.pyplot as plt

returns = pd.Series([0.01, -0.005, 0.02, -0.01, 0.015])
cum_returns = (1 + returns).cumprod() - 1
plt.plot(cum_returns)
plt.title('Cumulative Returns')
plt.xlabel('Days')
plt.ylabel('Cumulative Return')
plt.show()
ALine plot starting near 0 and ending around 0.03 showing cumulative growth
BBar plot showing daily returns as bars
CScatter plot of daily returns with no cumulative calculation
DPie chart showing proportion of positive vs negative returns
Attempts:
2 left
💡 Hint
Cumulative returns multiply daily returns over time, showing growth trend.
🔧 Debug
advanced
2:00remaining
Identify the Error in Volatility Calculation
What error does the following code raise when calculating volatility (standard deviation of returns)?
Data Analysis Python
import pandas as pd
prices = pd.Series([100, 102, 101, 105])
returns = prices.pct_change()
volatility = returns.std(ddof=0)
print(volatility.values)
AValueError: std() got an unexpected keyword argument 'ddof'
BTypeError: pct_change() missing required argument
CAttributeError: 'float' object has no attribute 'values'
DNo error, prints the volatility value
Attempts:
2 left
💡 Hint
Check the type of the volatility variable before accessing .values.
🚀 Application
expert
2:30remaining
Determine the Number of Trading Days with Positive Returns
Given a DataFrame of daily closing prices, how many days have positive returns?
Data Analysis Python
import pandas as pd
prices = pd.Series([100, 101, 99, 102, 104, 103])
returns = prices.pct_change()
positive_days = returns[returns > 0].count()
print(positive_days)
A5
B3
C2
D4
Attempts:
2 left
💡 Hint
Count how many daily returns are greater than zero, ignoring the first NaN.

Practice

(1/5)
1. What is the main purpose of analyzing financial data in Python?
easy
A. To write novels
B. To create video games
C. To design websites
D. To understand money trends and make informed decisions

Solution

  1. Step 1: Understand the goal of financial data analysis

    Financial data analysis focuses on studying money-related data to find patterns and trends.
  2. Step 2: Match the goal with the options

    Only To understand money trends and make informed decisions talks about understanding money trends and making decisions, which fits the purpose.
  3. Final Answer:

    To understand money trends and make informed decisions -> Option D
  4. Quick Check:

    Financial data analysis = Understand money trends [OK]
Hint: Focus on money trends and decisions for financial analysis [OK]
Common Mistakes:
  • Confusing financial analysis with unrelated fields
  • Ignoring the purpose of data analysis
  • Choosing options unrelated to money or data
2. Which of the following is the correct way to import pandas for financial data analysis in Python?
easy
A. import pandas as pd
B. import panda as pd
C. import pd as pandas
D. import pandas

Solution

  1. Step 1: Recall the standard pandas import syntax

    The common way to import pandas is using 'import pandas as pd' for easy reference.
  2. Step 2: Check each option for correctness

    import pandas as pd matches the standard syntax. Options B and C have wrong module names or order. import pandas imports pandas but without alias, which is less common.
  3. Final Answer:

    import pandas as pd -> Option A
  4. Quick Check:

    Standard pandas import = import pandas as pd [OK]
Hint: Use 'import pandas as pd' for standard data analysis [OK]
Common Mistakes:
  • Misspelling 'pandas' as 'panda'
  • Reversing import order
  • Not using alias 'pd' which is common practice
3. Given the code:
import pandas as pd

data = {'Date': ['2024-01-01', '2024-01-02'], 'Price': [100, 105]}
df = pd.DataFrame(data)
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)
print(df.loc['2024-01-02'])

What will be the output?
medium
A. Error: KeyError
B. Price 105 Name: 2024-01-02 00:00:00, dtype: int64
C. Date 2024-01-02 Price 105
D. Price 100 Name: 2024-01-01 00:00:00, dtype: int64

Solution

  1. Step 1: Understand DataFrame creation and index setting

    The DataFrame has dates converted to datetime and set as index. So rows are accessed by date index.
  2. Step 2: Access row with loc for '2024-01-02'

    Using df.loc['2024-01-02'] returns the row with Price 105 and index as Timestamp '2024-01-02 00:00:00'.
  3. Final Answer:

    Price 105 Name: 2024-01-02 00:00:00, dtype: int64 -> Option B
  4. Quick Check:

    df.loc['2024-01-02'] = Price 105 [OK]
Hint: Remember loc uses index; datetime index returns full timestamp row [OK]
Common Mistakes:
  • Expecting a DataFrame instead of a Series output
  • Not converting 'Date' to datetime before indexing
  • Using wrong date format causing KeyError
4. Identify the error in this code snippet for calculating daily returns:
import pandas as pd
prices = pd.Series([100, 105, 103, 108])
returns = prices.pct_change()
print(returns)
medium
A. No error; code correctly calculates daily returns
B. pct_change() should be pct_change(1)
C. prices should be a DataFrame, not Series
D. Missing import for numpy

Solution

  1. Step 1: Understand pct_change() method

    pct_change() calculates percentage change between current and prior element by default (periods=1).
  2. Step 2: Check code correctness

    prices is a Series, which supports pct_change(). No import or DataFrame needed. Code runs fine and prints daily returns.
  3. Final Answer:

    No error; code correctly calculates daily returns -> Option A
  4. Quick Check:

    pct_change() default periods=1 works [OK]
Hint: pct_change() defaults to 1 period; no extra args needed [OK]
Common Mistakes:
  • Thinking pct_change needs argument 1 explicitly
  • Confusing Series with DataFrame necessity
  • Assuming numpy import is required for pct_change
5. You have a DataFrame df with columns Date (string), Open, and Close prices. How do you create a new column Daily_Return that shows the percentage change from Open to Close for each day?
hard
A. df['Daily_Return'] = df['Close'].pct_change()
B. df['Daily_Return'] = df['Open'] / df['Close']
C. df['Daily_Return'] = (df['Close'] - df['Open']) / df['Open'] * 100
D. df['Daily_Return'] = df['Close'] - df['Open']

Solution

  1. Step 1: Understand daily return calculation

    Daily return is the percent change from Open to Close price: ((Close - Open) / Open) * 100.
  2. Step 2: Match formula with options

    df['Daily_Return'] = (df['Close'] - df['Open']) / df['Open'] * 100 correctly applies the formula. df['Daily_Return'] = df['Close'].pct_change() calculates percent change between rows, not within a row. Options C and D do not calculate percentage change correctly.
  3. Final Answer:

    df['Daily_Return'] = (df['Close'] - df['Open']) / df['Open'] * 100 -> Option C
  4. Quick Check:

    Daily return = ((Close - Open)/Open)*100 [OK]
Hint: Use (Close - Open) / Open * 100 for daily percent return [OK]
Common Mistakes:
  • Using pct_change() which compares different rows
  • Dividing Open by Close instead of difference over Open
  • Not multiplying by 100 for percentage
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard