Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Challenge: Compute and Interpret Returns | Financial Data Analysis with Python
Python for Traders

bookChallenge: Compute and Interpret Returns

In this challenge, you will work with a hardcoded pandas DataFrame containing the closing prices of two different stocks over a period of 10 days. Your goal is to analyze these prices by calculating both the daily absolute returns and the daily percentage returns for each stock. Once you have these returns, you will identify which stock experienced the highest single-day percentage gain, and on which day that occurred. You will also add the calculated return columns to the original DataFrame and display the relevant results.

To begin, you need a DataFrame with closing prices for two stocks, labeled "StockA" and "StockB", with dates as the index. Calculating the daily absolute return involves subtracting the previous day's closing price from the current day's closing price. The daily percentage return is calculated by dividing the absolute return by the previous day's closing price and multiplying by 100 to express it as a percent.

123456789101112131415161718192021222324252627282930313233343536373839
import pandas as pd # Create the DataFrame with closing prices data = { "StockA": [100, 102, 101, 105, 107, 110, 108, 111, 115, 117], "StockB": [50, 51, 53, 52, 56, 58, 57, 59, 60, 62] } dates = pd.date_range(start="2023-01-01", periods=10, freq="D") df = pd.DataFrame(data, index=dates) # Calculate daily absolute returns df["StockA_AbsReturn"] = df["StockA"].diff() df["StockB_AbsReturn"] = df["StockB"].diff() # Calculate daily percentage returns df["StockA_PctReturn"] = df["StockA"].pct_change() * 100 df["StockB_PctReturn"] = df["StockB"].pct_change() * 100 # Identify the highest single-day percentage gain stock_a_max = df["StockA_PctReturn"].idxmax() stock_b_max = df["StockB_PctReturn"].idxmax() stock_a_gain = df.loc[stock_a_max, "StockA_PctReturn"] stock_b_gain = df.loc[stock_b_max, "StockB_PctReturn"] if stock_a_gain > stock_b_gain: best_stock = "StockA" best_day = stock_a_max best_gain = stock_a_gain else: best_stock = "StockB" best_day = stock_b_max best_gain = stock_b_gain # Print the DataFrame with new columns print(df) # Print the result for the highest single-day percentage gain print(f"\nThe highest single-day percentage gain was for {best_stock} on {best_day.date()} with a return of {best_gain:.2f}%")
copy

This approach allows you to observe the day-to-day changes in both absolute and percentage terms for each stock. By comparing the maximum values in the percentage return columns, you can determine which stock had the most significant single-day jump, which is an important metric for understanding volatility and potential trading opportunities. The DataFrame now contains all the calculated columns, making it easy for you to review the results and interpret the performance of each stock over the given period.

Завдання

Swipe to start coding

  • Create a pandas DataFrame with the provided closing prices for "StockA" and "StockB" over 10 days.
  • Calculate the daily absolute returns and daily percentage returns for both stocks, adding them as new columns.
  • Identify which stock had the highest single-day percentage gain and on which day it occurred.
  • Print the updated DataFrame and display the highest single-day percentage gain with its corresponding stock and date.

Рішення

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 3
single

single

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Suggested prompts:

Can you explain how the daily absolute and percentage returns are calculated?

What does a high single-day percentage gain indicate about a stock?

Can you help me interpret the results in the DataFrame?

close

bookChallenge: Compute and Interpret Returns

Свайпніть щоб показати меню

In this challenge, you will work with a hardcoded pandas DataFrame containing the closing prices of two different stocks over a period of 10 days. Your goal is to analyze these prices by calculating both the daily absolute returns and the daily percentage returns for each stock. Once you have these returns, you will identify which stock experienced the highest single-day percentage gain, and on which day that occurred. You will also add the calculated return columns to the original DataFrame and display the relevant results.

To begin, you need a DataFrame with closing prices for two stocks, labeled "StockA" and "StockB", with dates as the index. Calculating the daily absolute return involves subtracting the previous day's closing price from the current day's closing price. The daily percentage return is calculated by dividing the absolute return by the previous day's closing price and multiplying by 100 to express it as a percent.

123456789101112131415161718192021222324252627282930313233343536373839
import pandas as pd # Create the DataFrame with closing prices data = { "StockA": [100, 102, 101, 105, 107, 110, 108, 111, 115, 117], "StockB": [50, 51, 53, 52, 56, 58, 57, 59, 60, 62] } dates = pd.date_range(start="2023-01-01", periods=10, freq="D") df = pd.DataFrame(data, index=dates) # Calculate daily absolute returns df["StockA_AbsReturn"] = df["StockA"].diff() df["StockB_AbsReturn"] = df["StockB"].diff() # Calculate daily percentage returns df["StockA_PctReturn"] = df["StockA"].pct_change() * 100 df["StockB_PctReturn"] = df["StockB"].pct_change() * 100 # Identify the highest single-day percentage gain stock_a_max = df["StockA_PctReturn"].idxmax() stock_b_max = df["StockB_PctReturn"].idxmax() stock_a_gain = df.loc[stock_a_max, "StockA_PctReturn"] stock_b_gain = df.loc[stock_b_max, "StockB_PctReturn"] if stock_a_gain > stock_b_gain: best_stock = "StockA" best_day = stock_a_max best_gain = stock_a_gain else: best_stock = "StockB" best_day = stock_b_max best_gain = stock_b_gain # Print the DataFrame with new columns print(df) # Print the result for the highest single-day percentage gain print(f"\nThe highest single-day percentage gain was for {best_stock} on {best_day.date()} with a return of {best_gain:.2f}%")
copy

This approach allows you to observe the day-to-day changes in both absolute and percentage terms for each stock. By comparing the maximum values in the percentage return columns, you can determine which stock had the most significant single-day jump, which is an important metric for understanding volatility and potential trading opportunities. The DataFrame now contains all the calculated columns, making it easy for you to review the results and interpret the performance of each stock over the given period.

Завдання

Swipe to start coding

  • Create a pandas DataFrame with the provided closing prices for "StockA" and "StockB" over 10 days.
  • Calculate the daily absolute returns and daily percentage returns for both stocks, adding them as new columns.
  • Identify which stock had the highest single-day percentage gain and on which day it occurred.
  • Print the updated DataFrame and display the highest single-day percentage gain with its corresponding stock and date.

Рішення

Switch to desktopПерейдіть на комп'ютер для реальної практикиПродовжуйте з того місця, де ви зупинились, використовуючи один з наведених нижче варіантів
Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 3
single

single

some-alt