Implementing standard derivatives

Let's have a look at the following code, which demonstrates the implementation of standard derivatives.

We are going to import the statistics and the math library we need to perform basic mathematical operations. We are defining the loopback period with the variable time_period, and we will store the past prices in the list history, while we will store the SMA and the standard deviation in sma_values and stddev_valuesIn the code, we calculate the variance, and then we calculate the standard deviation. To finish, we append to the goog_data data frame that we will use to display the chart:

import statistics as stats
import math as math

time_period = 20 # look back period

history = [] # history of prices
sma_values = [] # to track moving average values for visualization purposes
stddev_values = [] # history of computed stdev values
for close_price in close:
history.append(close_price)
if len(history) > time_period: # we track at most 'time_period' number of prices
del (history[0])

sma = stats.mean(history)
sma_values.append(sma)

variance = 0 # variance is square of standard deviation
for hist_price in history:
variance = variance + ((hist_price - sma) ** 2)

stdev = math.sqrt(variance / len(history))
stddev_values.append(stdev)

goog_data = goog_data.assign(ClosePrice=pd.Series(close, index=goog_data.index))
goog_data = goog_data.assign(StandardDeviationOver20Days=pd.Series(stddev_values, index=goog_data.index))
close_price = goog_data['ClosePrice']
stddev = goog_data['StandardDeviationOver20Days']

The preceding code will build the final visualizations:

import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(211, ylabel='Google price in $')
close_price.plot(ax=ax1, color='g', lw=2., legend=True)
ax2 = fig.add_subplot(212, ylabel='Stddev in $')
stddev.plot(ax=ax2, color='b', lw=2., legend=True)
plt.show()

The preceding code will return the following output. Let's have a look at the plot:

Here, the standard deviation quantifies the volatility in the price moves during the last 20 days. Volatility spikes when the Google stock prices spike up or spike down or go through large changes over the last 20 days. We will revisit the standard deviation as an important volatility measure in later chapters.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.30.162