In: Computer Science
write a python script to calculate the return of a stock with 10years of historical data/returns
#consider the stocks example as netflix data or use a stock of your desire like apple etc,.
#import necessary packages like pandas,numpy and matplotlib for plotting charts
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pandas_datareader as web
#getting the required data during a certain period of time
netflix = web.get_data_yahoo("NFLX",start = "2010-01-01", end = "2019-01-01")
#see the top 5 rows of the table
print(netflix.head())
#charting the Netflix closing adjusted price
#to observe it we are plotting a graph
netflix['Adj Close'].plot()
plt.xlabel("Date")
plt.ylabel("Adjusted")
plt.title("Netflix Price data")
plt.show()
#calculate the returns
netflix_daily_returns = netflix['Adj Close'].pct_change()
netflix_monthly_returns = netflix['Adj Close'].resample('M').ffill().pct_change()
#to see the top five rows of the netflix daily returns
print(netflix_daily_returns.head())
print(netflix_monthly_returns.head())
\
fig = plt.figure()
ax1 = fig.add_axes([0.1,0.1,0.8,0.8])
ax1.plot(netflix_daily_returns)
ax1.set_xlabel("Date")
ax1.set_ylabel("Percent")
ax1.set_title("Netflix daily returns data")
plt.show()
fig = plt.figure()
ax1 = fig.add_axes([0.1,0.1,0.8,0.8])
ax1.plot(netflix_monthly_returns)
ax1.set_xlabel("Date")
ax1.set_ylabel("Percent")
ax1.set_title("Netflix monthly returns data")
plt.show()
#calculate the cumulative returns we will use the cumprod() function
netflix_cum_returns = (netflix_daily_returns + 1).cumprod()
#charting the monthly cummulative returns data these are optional to use
fig = plt.figure()
ax1 = fig.add_axes([0.1,0.1,0.8,0.8])
netflix_cum_returns = (netflix_monthly_returns + 1).cumprod()
ax1.plot(netflix_cum_returns)
ax1.set_xlabel("Date")
ax1.set_ylabel("Growth of $1 investment")
ax1.set_title("Netflix Monthly cumulative returns data")
plt.show()
This maybe useful for your guidance and you can try any kind of stocks in the place of netflix stocks.