Data visualisation and Analysis toolbox for all things time series

image.png\

In [1]:
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")
In [5]:
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")
In [21]:
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))
                   Open         High          Low        Close
Date                                                          
2019-03-12  2787.340088  2798.320068  2786.729980  2791.520020
2019-03-13  2799.780029  2821.239990  2799.780029  2810.919922
2019-03-14  2810.379883  2815.000000  2803.459961  2808.479980
2019-03-15  2810.790039  2830.729980  2810.790039  2822.479980
2019-03-18  2822.610107  2835.409912  2821.989990  2832.939941
...                 ...          ...          ...          ...
2020-03-05  3075.699951  3083.040039  2999.830078  3023.939941
2020-03-06  2954.199951  2985.929932  2901.540039  2972.370117
2020-03-09  2863.889893  2863.889893  2734.429932  2746.560059
2020-03-10  2813.479980  2882.590088  2734.000000  2882.229980
2020-03-11  2825.600098  2825.600098  2707.219971  2741.379883

[253 rows x 4 columns]
Open     2979.770020
High     2980.760010
Low      2970.090088
Close    2975.949951
Name: 2019-07-08 00:00:00, dtype: float64
In [22]:
# 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))
In [23]:
# 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))
In [30]:
"""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))
                   Open         High          Low        Close
Date                                                          
2019-03-17  2810.790039  2830.729980  2810.790039  2822.479980
2019-03-24  2844.520020  2846.159912  2800.469971  2800.709961
2019-03-31  2828.270020  2836.030029  2819.229980  2834.399902
2019-04-07  2884.159912  2893.239990  2882.989990  2892.739990
2019-04-14  2900.860107  2910.540039  2898.370117  2907.409912
In [34]:
""" 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)
Out[34]:
<matplotlib.axes._subplots.AxesSubplot at 0x252212d63c8>
In [36]:
"""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)
Out[36]:
<matplotlib.axes._subplots.AxesSubplot at 0x2522043bc88>
In [53]:
"""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));
In [62]:
""" 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")           
            Price   Open   High    Low Vol. Change %
Date                                                
2020-04-02  56.22  54.46  57.24  52.55    -   -1.47%
2020-04-01  57.06  57.38  60.59  52.76    -    6.57%
2020-03-31  53.54  56.69  58.75  50.88    -   -6.20%
2020-03-30  57.08  66.30  67.69  56.60    -  -12.91%
2020-03-27  65.54  64.95  69.10  61.80    -    7.44%
...           ...    ...    ...    ...  ...      ...
2019-03-18  13.10  13.13  13.80  13.00    -    1.71%
2019-03-15  12.88  13.21  13.28  12.50    -   -4.59%
2019-03-14  13.50  13.35  13.84  13.16    -    0.67%
2019-03-13  13.41  14.00  14.05  13.25    -   -2.61%
2019-03-12  13.77  13.97  14.70  13.61    -   -3.91%

[270 rows x 6 columns]
Out[62]:
<matplotlib.axes._subplots.AxesSubplot at 0x25221b49808>
In [ ]: