DEV Community

Kai Py
Kai Py

Posted on • Edited on

8 5

Computing Daily Stock Market Returns in Python

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()

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay