<jupyter_start><jupyter_text>Behaviour of the S&P500 in the close<jupyter_code>import sys
sys.executable # Check in which virtual environment I am operating
import numpy as np
import pandas as pd
# Module to retrieve data on financial instruments (similar to 'yahoo finance')
import yfinance as yf 
import matplotlib
from matplotlib import pyplot as plt
import datetime<jupyter_output><empty_output><jupyter_text>Import data<jupyter_code>df = yf.download(tickers='^GSPC', period='1y', interval='1d')
df.drop(columns=['Adj Close', 'Open', 'High', 'Low'], inplace = True)
dft = yf.download(tickers='^GSPTSE', period='1y', interval='1d')
dft.drop(columns=['Adj Close', 'Open', 'High', 'Low'], inplace = True)
print(f"Data from {df.index[0]} to {df.index[-1]}")
df.tail()
print(f"Data from {dft.index[0]} to {dft.index[-1]}")
dft.tail()<jupyter_output>Data from 2019-04-15 00:00:00 to 2020-04-14 00:00:00<jupyter_text>Manipulate Data<jupyter_code>def add_Change(df):
    df['Change'] = ((df['Close'] - df['Close'].shift(1)) / df['Close'].shift(1)) * 100
    return df
def add_SMA(df):
    df['SMA'] = (df['Change'] + df['Change'].shift(1) + df['Change'].shift(2)) * 1/3
    return df
df = add_Change(df)
df = add_SMA(df)

dft = add_Change(dft)
dft = add_SMA(dft)
df.tail()
dft.tail()<jupyter_output><empty_output><jupyter_text>PLOT<jupyter_code>from matplotlib.ticker import PercentFormatter
from matplotlib.dates import AutoDateLocator, AutoDateFormatter, ConciseDateFormatter
def manage_patches_color(patches):
    
    for patch in patches:
        if patch.get_height() >= 0:
            patch.set_color('#1E8449')
        else: 
            patch.set_color('#D13B1B')
def my_plotter(fig, ax, df, start_date, end_date, title):
    
    fig.set_size_inches(16,8)
    bar_output = ax.bar(x=df.loc[start_date:end_date].index, 
                 height=df.loc[start_date:end_date, 'Change'], alpha=0.8)
    manage_patches_color(patches=bar_output.patches)
    ax.plot(df.loc[start_date:end_date].index, df.loc[start_date:end_date, 'SMA'], color='#2D2624', linestyle='--', alpha=1)
    ax.yaxis.set_major_formatter(PercentFormatter())
    ax.xaxis.set_major_locator(AutoDateLocator())
    ax.xaxis.set_major_formatter(ConciseDateFormatter(AutoDateLocator()))
    ax.grid(b=False, axis='x')
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.spines['bottom'].set_visible(True)
    ax.set_title(title)
    
    return bar_output

matplotlib.style.use('seaborn-whitegrid')
# specify the custom font to use
# plt.rcParams['font.family'] = 'Andale Mono'
# plt.rcParams['font.sans-serif'] = 'Regular'
plt.rcParams['font.size'] = 14

fig, ax = plt.subplots()
out = my_plotter(fig, ax, df, '2020-01', '2020-05', 'S&P500')
fig, ax = plt.subplots()
out = my_plotter(fig, ax, dft, '2020-01', '2020-05', 'S&P/TSX')<jupyter_output><empty_output><jupyter_text>TSLA vs normal stock over a year<jupyter_code>tsla = yf.download(tickers='TSLA', period='1y', interval='1d')
aapl = yf.download(tickers='AAPL', period='1y', interval='1d')
tsla.drop(columns=['Adj Close', 'Open', 'High', 'Low'], inplace = True)
aapl.drop(columns=['Adj Close', 'Open', 'High', 'Low'], inplace = True)
tsla.tail()
aapl.tail()
tsla_origin = tsla.loc['20200302', 'Close']
aapl_origin = aapl.loc['20200302', 'Close']
tsla['Change over 1y'] = ((tsla['Close'] - tsla_origin) / tsla_origin) * 100
aapl['Change over 1y'] = ((aapl['Close'] - aapl_origin) / aapl_origin) * 100
# %matplotlib inline
fig, ax = plt.subplots()
fig.set_size_inches(16,8)
ax.plot(tsla.loc['20200301':].index, tsla.loc['20200301':, 'Change over 1y'], color='#f54242', linestyle='-', alpha=1, label='Tesla')
ax.plot(aapl.loc['20200301':].index, aapl.loc['20200301':, 'Change over 1y'], color='#2b2424', linestyle='-', alpha=1, label='Apple')
ax.yaxis.set_major_formatter(PercentFormatter())
ax.xaxis.set_major_locator(AutoDateLocator())
ax.xaxis.set_major_formatter(ConciseDateFormatter(AutoDateLocator()))
ax.grid(b=False, axis='x')
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(True)
ax.legend()
txt_out = ax.set_title("TSLA vs AAPL % Change over one year")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.17736289381563594, 'fraction_numerical': 0.04060676779463244, 'mean_word_length': 5.957792207792208, 'pattern_counts': {'":': 0, '<': 20, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '379791', 'license': 'MIT', 'n_tokens_mistral': 1777, 'n_tokens_neox': 1650, 'n_words': 296, 'path': 'sp500-analysis.ipynb', 'repo_name': 'mtlberri/sp500-in-the-close', 'size': '4285'}