\
import numpy as np
import pandas as pd
import cufflinks as cf
import plotly.offline as plyo
plyo.init_notebook_mode(connected=True)
a = np.random.standard_normal((250,5)).cumsum(axis=0)
"""create an array of dates hat repeat every business day from 2019-1-1 up to the number of rows in the a array"""
index = pd.date_range('2019-1-1',freq='B',periods=len(a))
df = pd.DataFrame(100+ 5 *a, columns = ["a","b","c","d","e"],index =index)
df.head()
""" using iplot from cufflinks to create interactive plots """
plyo.iplot(df.iplot(asFigure=True), image ='png', filename = "iplot_1")
import pandas as pd
import cufflinks as cf
import plotly.offline as plyo
plyo.init_notebook_mode(connected=True)
a = np.random.standard_normal((250,5)).cumsum(axis=0)
"""create an array of dates hat repeat every business day from 2019-1-1 up to the number of rows in the a array"""
index = pd.date_range('2019-1-1',freq='B',periods=len(a))
df = pd.DataFrame(100+ 5 *a, columns = ["a","b","c","d","e"],index =index)
df.head()
""" using iplot from cufflinks to create interactive plots """
plyo.iplot(
df[["a","b"]].iplot(asFigure=True,
theme ="polar",
mode={"a":"markers","b":"lines+markers"},
size=3.5),
image ='png',
filename = "iplot_2")
SP500_Data = pd.read_csv(r'C:\Users\Adam\Desktop\Personal\Python Syntax\Python Input Files\sp_500.csv', index_col="Date", parse_dates=True)
SP500_Quotes = SP500_Data.drop(["Adj Close","Volume"],axis=1)
#creating a qunat fig object
qf=cf.QuantFig(
SP500_Quotes,
title="SP500",
legend="top",
name="SP500")
plyo.iplot(
qf.iplot(asFigure=True))
# we can add bollinger bands to the plot
# period = the period over which you want the bollinder bands to be calculated in this case 15days
# boll_std = the number of standard deviations to be used for the band widths
qf.add_bollinger_bands(periods=15, boll_std=2)
plyo.iplot(
qf.iplot(asFigure=True))
# we can add RSI indicators to the plot
"""
The relative strength index (RSI) is a momentum indicator that measures the magnitude of recent price
changes to evaluate overbought or oversold conditions in the price of a stock or other asset.
The RSI is displayed as an oscillator (a line graph that moves between two extremes) and can have a
reading from 0 to 100
"""
# period = the period over which you want the bollinder bands to be calculated in this case 15days
#boll_std = the number of standard deviations to be used for the band widths
qf.add_rsi(periods=15, showbands=True)
plyo.iplot(
qf.iplot(asFigure=True))
"""resampling the time series to be on a weekly basis """
weekly_SP500_Quotes = SP500_Quotes.resample("1w").last()
print(weekly_SP500_Quotes.head())
qf=cf.QuantFig(
weekly_SP500_Quotes,
title="SP500",
legend="top",
name="SP500")
plyo.iplot(
qf.iplot(asFigure=True))
""" how to create rolling statistics """
# we can define avariable as the period we want the rolling stats to be, in this case 20business days
window = 20
SP500_Quotes["min"]=SP500_Quotes.Close.rolling(window=window).min() #the min close over the last 20 days
SP500_Quotes["max"]=SP500_Quotes.Close.rolling(window=window).max() #the min close over the last 20 days
SP500_Quotes["mean"]=SP500_Quotes.Close.rolling(window=window).mean() #the mean close over the last 20 days
SP500_Quotes["std"]=SP500_Quotes.Close.rolling(window=window).std() #the mean close over the last 20 days
SP500_Quotes["median"]=SP500_Quotes.Close.rolling(window=window).median() #the mean close over the last 20 days
ax = SP500_Quotes[["min","mean","max"]].plot(
figsize=(10,6),
style=["g--","r--","g--"],
lw=0.8)
SP500_Quotes.Open.plot(
ax=ax, #plot on the same axes as above
lw=2.0)
"""simple moving averages trading strategy"""
"""you chart an indices or stock etc with two moving averages one short term and one long term. You sell short when the short
term average is above the long term average and vice versa"""
SP500_Quotes["MA_14"]=SP500_Quotes.Close.rolling(window=14).mean() #the mean close over the last 14 days
SP500_Quotes["MA_60"]=SP500_Quotes.Close.rolling(window=60).mean() #the mean close over the last 60 days
ax = SP500_Quotes[["MA_14","MA_60"]].plot(
figsize=(10,6),
style=["r--","g--"],
lw=0.8)
SP500_Quotes.Open.plot(
ax=ax, #plot on the same axes as above
lw=2.0)
"""simple moving averages trading strategy"""
""""Marking the moving average trading positions"""
SP500_Quotes["positions"] = np.where(SP500_Quotes["MA_14"]>SP500_Quotes["MA_60"],1,-1) #1's signal a buying oppturunity -1's a shortselling
ax = SP500_Quotes[["MA_14","MA_60"]].plot(
figsize=(10,6),
style=["r--","g--"],
lw=0.8)
SP500_Quotes[["Open","positions"]].plot(
ax=ax, #plot on the same axes as above
lw=2.0,
secondary_y="positions") # plot the positions data on a secondary y axis
ax.get_legend().set_bbox_to_anchor((0.25,0.85));
""" Correlation analysis """
"""it is well known that the VIX and the SP500 are inversly correlated this is due to correlation not due to causation
one doesnt cause the other """
VIX_Data = pd.read_csv(r'C:\Users\Adam\Desktop\Personal\Python Syntax\Python Input Files\VIX_Index.csv', index_col="Date", parse_dates=True)
print(VIX_Data)
ax = SP500_Quotes["Open"].plot(figsize=(10,6),lw=0.8,style=["r--"])
VIX_Data["Open"].plot(
ax=ax, #plot on the same axes as above
lw=2.0,
secondary_y="Open")