Computing stock market returns in Python is simple. The first step is to import the required libraries.
import pandas as pd
import numpy as np
import datetime
import matplotlib.pyplot as plt
from pandas_datareader import data as pdr
The next step is to get the stock data. I prefer to use yahoo as the source of my data. We use the get_data_yahoo method from the pandas_datareader library which has been imported as pdr. We also specify the start and end date using the datetime method. We will be getting the data for Apple. Therefore, all this is stored in the appl variable.
aapl = pdr.get_data_yahoo('AAPL',
start=datetime.datetime(2006, 10, 1),
end=datetime.datetime(2012, 1, 1))
daily_close = aapl[['Adj Close']]
Next is to get the returns. Firstly, we extract the daily close quote from the aapl data frame . Then, we apply the pct_change() method on daily_close and store it in the returns variable.
returns = daily_close.pct_change()
Finally, we can apply the plot method on the returns variable to plot the returns of apple within the time frame
returns.plot()
Top comments (0)