Calculating Percent Change in Stock Prices

To calculate the percent change in stock prices, we can simply subtract the stock price on the previous day from the stock price on the current day, and divide by the previous day's stock price .

Problem

Given a dataframe of stock prices, return a new dataframe with the percent change in stock price for each day.
Input:
| Date       | Stock Price |
|------------|-------------|
| 1/1/2018   | 10          |
| 1/2/2018   | 11          |
| 1/3/2018   | 12          |
Output:
| Date       | Percent Change |
|------------|----------------|
| 1/1/2018   | 0              |
| 1/2/2018   | 0.1            |
| 1/3/2018   | 0.0833333333   |

Solution

This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
import pandas as pd

def percent_change(df):
    df['Percent Change'] = df['Stock Price'].pct_change()
    return df

df = pd.DataFrame({'Date': ['1/1/2018', '1/2/2018', '1/3/2018'], 'Stock Price': [10, 11, 12]})
print(percent_change(df))


The solution is optimal because it uses the built-in pct_change() function in pandas.

A.I. Evaluation of the Solution

The candidate's solution is optimal because it uses the built-in pct_change() function in pandas.

Evaluated at: 2022-11-14 04:15:59