menu
Data

Charting Data

A simple way to chart data in GS Quant is by installing matplotlib. This plotting library can be used to easily generate plots, histograms, power spectra, bar charts, error charts, scatter plots, etc.

Let's use this library to chart calculated implied volatility from GS Quant.

info

Note

Examples require an initialized GsSession and data subscription. Please refer to Sessions for details.

Querying Data

First, let's retrieve S&P 500 end of day implied volatility for 1 month tenor with forward strike:

from gs_quant.data import Dataset
from gs_quant.markets import PricingContext


market_date = PricingContext.current.market.date  # Determine current market date

vol_dataset = Dataset(Dataset.GS.EDRVOL_PERCENT_STANDARD)  # Initialize the equity implied volatility dataset
vol_data = vol_dataset.get_data(market_date, market_date, ticker='SPX', tenor='1m', strikeReference='forward')

print(vol_data.tail())

Output:

    absoluteStrike              assetId  ... ticker            updateTime
21     4049.365704  MA4B66MW5E27U8P32SB  ...    SPX  2019-06-17T22:18:01Z
22     4193.985908  MA4B66MW5E27U8P32SB  ...    SPX  2019-06-17T22:18:01Z
23     4338.606111  MA4B66MW5E27U8P32SB  ...    SPX  2019-06-17T22:18:01Z
24     5061.707130  MA4B66MW5E27U8P32SB  ...    SPX  2019-06-17T22:18:01Z
25     5784.808149  MA4B66MW5E27U8P32SB  ...    SPX  2019-06-17T22:18:01Z

[5 rows x 9 columns]

Charting Data

Implied Volatility By Strike

Now, let's use vol_data to chart the implied volatility by relative strike:

info

Note

Remember to install matplotlib.

add the following import statement to have matplot available:

import matplotlib.pyplot as plt

then plot your data like so:

strikes = vol_data['relativeStrike']
vols = vol_data['impliedVolatility'] * 100

plt.plot(strikes, vols, label='Implied Volatility by Strike')
plt.xlabel('Relative Strike')
plt.ylabel('Implied Volatility')
plt.title('Implied Volatility by Strike')

plt.show()

Which will create a plot like this:

Implied Volatility By Tenor

Likewise we can use the same technique to chart the implied volatility by tenor:

from gs_quant.timeseries.measures import _to_offset

vol_data = vol_dataset.get_data(market_date, market_date, ticker='SPX', relativeStrike=1.0, strikeReference='forward')
# Create a new column converting relative dates to actual date times
vol_data.loc[:, 'tenorDate'] = vol_data.index + vol_data['tenor'].map(_to_offset)
# Sort the data frame by the newly created column
vol_data = vol_data.sort_values(by=['tenorDate'])
tenors = vol_data['tenor']
vols = vol_data['impliedVolatility'] * 100
plt.plot(tenors, vols, label='Implied Volatility by Tenor')
plt.xlabel('Tenor')
plt.ylabel('Implied Volatility')
plt.title('Implied Volatility by Tenor')
plt.show()

Producing:

Implied Volatility Area By Tenor And Strike

Now, let's combine the two and plot a vol surface to chart the implied volatility by tenor and strike:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm

from gs_quant.data import Dataset
from gs_quant.datetime import point_sort_order
from gs_quant.markets import PricingContext

# Initialize the dataset for equity implied volatility
vol_dataset = Dataset(Dataset.GS.EDRVOL_PERCENT_STANDARD)

market_date = PricingContext.current.market.date
tenors_to_plot = ["2w", "1m", "2m", "3m", "4m", "5m", "6m", "9m", "1y"]
fig = plt.figure(figsize=(16, 9))
ax = fig.add_subplot(111, projection='3d')

# Implied vol data for the current market data date
vol_data = vol_dataset.get_data(market_date, market_date, ticker='SPX', strikeReference='forward')
vol_data = vol_data[vol_data.tenor.isin(tenors_to_plot)]
vol_data['tenorDays'] = vol_data.tenor.map(lambda t: point_sort_order(t))

# Reformat the data
X = vol_data.relativeStrike.unique()
Y = vol_data.tenorDays.unique()
Z = np.array([vol_data[vol_data.tenorDays == y].impliedVolatility.values.tolist() for y in Y]) * 100
X, Y = np.meshgrid(X, Y)

# Plot the surface
ax.xaxis.set_label_text("Strike")
ax.yaxis.set_label_text("Tenor")
ax.zaxis.set_label_text("Implied Vol")
ax.set_zlim(0, 75)
ax.set_yticks(vol_data.tenorDays.unique())
ax.set_yticklabels(vol_data.tenor.unique())
surface = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)

plt.show()

The previous example should produce a 3D graph similar to this:


Related Content


This site is for informational purposes only and does not constitute an offer to sell, or the solicitation of an offer to buy, any security. The Goldman Sachs Marquee® platform is for institutional and professional clients only. Some of the services and products described on this site may not be available in certain jurisdictions or to certain types of client. Please contact your Goldman Sachs sales representative with any questions. Nothing on this site constitutes an offer, or an invitation to make an offer from Goldman Sachs to purchase or sell a product. This site is given for purely indicative purposes and does not create any contractual relationship between you and Goldman Sachs. Any market information contained on the site (including but not limited to pricing levels) is based on data available to Goldman Sachs at a given moment and may change from time to time. There is no representation that any transaction can or could have been effected on such terms or at such prices. Please see https://www.goldmansachs.com/disclaimer/sec-div-disclaimers-for-electronic-comms.html for additional information. © 2023 Goldman Sachs. All rights reserved.
Transaction Banking services are offered by Goldman Sachs Bank USA (“GS Bank”). GS Bank is a New York State chartered bank, a member of the Federal Reserve System and a Member FDIC. © 2023 Goldman Sachs. All rights reserved.
Not all products and functionality mentioned on this website are currently available through our API platform.
All loans and deposit products are provided by Goldman Sachs Bank USA, Salt Lake City Branch. Member FDIC.
Brokerage and investment advisory services offered by our investment products are provided by Goldman Sachs & Co. LLC (`‘GS&CO.`’), which is an SEC registered broker-dealer and investment adviser, and member FINRA/SIPC. Research our firm at FINRA's BrokerCheck. Custody and clearing services are provided by Apex Clearing Corporation, a registered broker-dealer and member FINRA/SIPC. Please consider your objectives before investing. A diversified portfolio does not ensure a profit or protect against a loss. Past performance does not guarantee future results. Investment outcomes and projections are forward-looking statements and hypothetical in nature. Neither this website nor any of its contents shall constitute an offer, solicitation, or advice to buy or sell securities in any jurisdictions where GS&Co. is not registered. Any information provided prior to opening an investment account is on the basis that it will not constitute investment advice and that GS&Co. is not a fiduciary to any person by reason of providing such information. For more information about our investment offerings, visit our Full Disclosures.
Investment products are: NOT FDIC INSURED ∙ NOT A DEPOSIT OR OTHER OBLIGATION OF, OR GUARANTEED BY, GOLDMAN SACHS BANK USA ∙ SUBJECT TO INVESTMENT RISKS, INCLUDING POSSIBLE LOSS OF THE PRINCIPAL AMOUNT INVESTED