Source Code

/Stock Downloader/examples/interactivegraph/

main.py

import stockdownloader
import pandas as pd
pd.options.plotting.backend = "plotly"
 
def calculatePercentage(df):
 
    #Sort the stock prices by date
    df = df.sort_values(by="Date", ascending = False)
 
    #Create a new data frame that only stores the date values
    #The relative performance will be added to this new data frame later
    newdf = pd.DataFrame()
    newdf['Date'] = df['Date']
 
    #Loop over all columns of the data frame
    for colindex in range(len(df.columns)):
 
        #Get the name of the column
        colname = df.columns[colindex]
 
        #If the column contains a close price then calculate the 
        #relative performance to first closing price 
        if("Close" in colname):
            colname = colname.replace('Close', '') 
            column = df.iloc[:, colindex]
            lastindex = column.last_valid_index()
            lastclose = column.loc[lastindex]
            newdf[colname+"Percent"] = (df[df.columns[colindex]] / lastclose) - 1
 
    #Add a column that contains the average over all stocks 
    newdf['AllStocksAverage'] = newdf.mean(axis=1)
 
    return newdf
 
def createDiagrams(df):
 
    #Change the column names to get a more readable legend 
    for colindex in range(len(df.columns)):
        if(colindex != 0):
            oldcolname = df.columns[colindex]
            newcolname = oldcolname.replace('Percent', '') 
            df.rename(columns = {oldcolname:newcolname}, inplace = True)
    columnlist = list(df.columns.values)
    columnlist.remove("Date")
    columnlist.remove("AllStocksAverage")
 
    #Plot the mix of stocks as line graph
    fig = df.plot(
        kind='line', 
        x = 'Date', 
        y = columnlist, 
        title=None, 
        labels={'variable':'Stocks','value':'Relative Performance [in %]'}
    )
    fig.add_hline(y=0)
    fig.update_layout(
        margin=dict(l=0, r=0, t=0, b=0),
        plot_bgcolor='White',
        yaxis={
            'visible': True, 
            'showticklabels': True, 
            'title': None, 
            'showline':True, 
            'linewidth':2, 
            'linecolor':'White', 
            'gridcolor':'rgba(237,237,237,1)',
            'ticklabelposition':'inside',
            'tickformat':'.1%'
        },
        xaxis={
            'visible': True, 
            'showticklabels': True, 
            'title': None, 
            'showline':True, 
            'linewidth':2, 
            'linecolor':'White', 
            'gridcolor':'rgba(237,237,237,1)',
            'ticklabelposition':'inside'
        },
        legend=dict(
            bgcolor = 'rgba(255,255,255,1)',
            orientation="h",
            yanchor="bottom",
            y=1.02,
            xanchor="right",
            x=1,
            title = None
        )
    )
    fig.write_html('output_mix.html')
 
    #Plot the total of all stock prices combines as line graph
    fig = df.plot(kind='line', x = 'Date', y = "AllStocksAverage", title=None,labels={'variable':'Stocks','value':'Relative Performance [in %]'})
    fig.add_hline(y=0)
    fig.update_layout(
        margin=dict(l=0, r=0, t=0, b=0),
        plot_bgcolor='White',
        yaxis={
            'visible': True, 
            'showticklabels': True, 
            'title': None, 
            'showline':True, 
            'linewidth':2, 
            'linecolor':'White', 
            'gridcolor':'rgba(237,237,237,1)',
            'ticklabelposition':'inside',
            'tickformat':'.1%'
        },
        xaxis={
            'visible': True, 
            'showticklabels': True, 
            'title': None, 
            'showline':True, 
            'linewidth':2, 
            'linecolor':'White', 
            'gridcolor':'rgba(237,237,237,1)',
            'ticklabelposition':'inside'
        },
        legend=dict(
            bgcolor = 'rgba(255,255,255,1)',
            orientation="h",
            yanchor="bottom",
            y=1.02,
            xanchor="right",
            x=1,
            title = None
        )
    )
    fig.write_html('output_total.html')
 
def main():
 
    #Variables
    stocks = {
        "MMM":"3M",
        "AXP":"AmericanExpress",
        "AMGN":"Amgen",
        "AAPL":"Apple",
        "BA":"Boeing",
        "CAT":"Caterpillar",
        "CVX":"Chevron",
        "CSCO":"Cisco",
        "KO":"CocaCola",
        "DOW":"Dow",
        "GS":"GoldmanSachs",
        "HD":"HomeDepot",
        "HON":"Honeywell",
        "IBM":"IBM",
        "INTC":"Intel",
        "JNJ":"JohnsonJohnson",
        "JMP":"JPMorganChase",
        "MCD":"MCDonalds",
        "MRK":"Merck",
        "MSFT":"Microsoft",
        "NKE":"Nike",
        "PG":"ProcterGamble",
        "CRM":"Salesforce",
        "TRV":"Travelers",
        "UNH":"UnitedHealthGroup",
        "VZ":"Verizon",
        "V":"Visa",
        "WBA":"Walgreens",
        "WMT":"Walmart",
        "DIS":"WaltDisney"
    }
    startdate="2019-08-14"
    enddate="2021-08-08"
 
    #Download the stock data    
    dataframe = stockdownloader.downloadFromDict(stocks,apikey="key",startdate=startdate,enddate=enddate)
 
    #Calculate the relative performance of each stock
    print("\n Calculating performance")
    dataframe = calculatePercentage(dataframe)
    print("> Performance was calculated")
 
    #Create interactive plotly graphs from the data
    print("\n Creating diagrams")
    createDiagrams(dataframe)
    print("> Diagrams were created")
 
main()