0

I borrowed some code from the web for this line chart animation, but unfortunately it came with some sort of count() for the x axis rather than the dates that I am importing from Yahoo. I'm new to this, can you help?

I get an okay plot, but I would rather have dates under the x axis.

import pandas_datareader.data as web
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
from pylab import legend
from matplotlib import animation
from matplotlib.animation import FuncAnimation
from itertools import count


plt.style.use('ggplot')
fig, axes = plt.subplots(nrows = 1, ncols = 1, figsize = (12,5))


# set up investment choice and start/end dates
choice = str(input('Please enter your investment symbol: '))
start = str(input('Please enter your comparison starting date(mm/dd/yyyy):'))
end = dt.date.today()
symbol = '^GSPC', choice #S&P500 symbol and your choice for comparison

# source of data and method of acqusition of data
source = 'yahoo'            
data = web.DataReader(symbol, source, start, end)['Adj Close']

#adjust data shares for even start:
numer = data.iat[0,0]
denom = data.iat[0,1]  #call starting date value for chosen symbol
shares = numer/denom #compute number of shares for even start  

data[choice] = shares*(pd.DataFrame(data[choice])) #Shares*share price
                                                    #for entire choice column
                                                   #for comparisons
for i in range(0, len(data)):  #set up animation steps
    l1 = data['^GSPC']
    l2 = data[choice]

x1,y1,y2,y3 = [], [], [], []
xval = count(0,1.37)


print(l1, l2)

def animate(i):
    x1.append(next(xval))
    y1.append((l1[i]))
    y2.append((l2[i]))

    axes.plot(x1,y1, color="red")
    axes.plot(x1,y2, color="blue")   
    

if __name__ == '__main__':
    try:
        anim = FuncAnimation(fig, animate, interval=1)                                         
        #plt.plot(data)
        plt.xlabel('Days')
        plt.ylabel('Dollars')
        plt.title('The S&P500 (red) vs. Your Investment (blue),'
              ' Using Adjusted Share Amounts for Even Start')
        #legend(['S&P500', choice])
        plt.show()
        
    except IndexError as e:
        print(e)
        print(sys.exc_type) 
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
gerald
  • 420
  • 2
  • 8

1 Answers1

2

Is your code failing with an error? I have this happening.I removed the extra function call def init().

import pandas_datareader.data as web
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import sys

plt.style.use('ggplot')
fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(12, 5))

# set up investment choice and start/end dates
choice = str(input('Please enter your investment symbol: '))
start = str(input('Please enter your comparison starting date(mm/dd/yyyy):'))
end = dt.date.today()
symbol = '^GSPC', choice  # S&P500 symbol and your choice for comparison

# source of data and method of acqusition of data
source = 'yahoo'
data = web.DataReader(symbol, source, start, end)['Adj Close']

# adjust data shares for even start:
numer = data.iat[0, 0]
denom = data.iat[0, 1]  # call starting date value for chosen symbol
shares = numer / denom  # compute number of shares for even start

data[choice] = shares * (pd.DataFrame(data[choice]))  # Shares*share price

x1, y1, y2, y3 = [], [], [], []

def init():
        pass

def animate(i):
        if (len(data) - 1) == i:
           anim.event_source.stop()
        x1.append(data['^GSPC'].index[i])
        y1.append((data['^GSPC'].values[i]))
        y2.append((data[choice].values[i]))

        axes.plot(x1, y1, color="red")
        axes.plot(x1, y2, color="blue")


if __name__ == '__main__':
        try:
                anim = FuncAnimation(fig, animate, init_func=init, interval=1)
                # plt.plot(data)
                plt.xlabel('Days')
                plt.ylabel('Dollars')
                plt.title('The S&P500 (red) vs. Your Investment (blue),'
                          ' Using Adjusted Share Amounts for Even Start')
                # legend(['S&P500', choice])
                plt.show()

        except IndexError as e:
                print(e)
                print(sys.exc_type)

If you don't need animation, then the code below is without animation. Changed your code somewhat. Removed the obviously unnecessary creation of arrays: x1,y1,y2,y3.

import pandas_datareader.data as web
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt


plt.style.use('ggplot')
fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(12, 5))

# set up investment choice and start/end dates
choice = str(input('Please enter your investment symbol: '))
start = str(input('Please enter your comparison starting date(mm/dd/yyyy):'))
end = dt.date.today()
symbol = '^GSPC', choice  # S&P500 symbol and your choice for comparison

# source of data and method of acqusition of data
source = 'yahoo'
data = web.DataReader(symbol, source, start, end)['Adj Close']

numer = data.iat[0, 0]
denom = data.iat[0, 1]  # call starting date value for chosen symbol
shares = numer / denom  # compute number of shares for even start

data[choice] = shares * (pd.DataFrame(data[choice]))  # Shares*share price

axes.plot(data['^GSPC'].index, data['^GSPC'], color="red")
axes.plot(data[choice].index, data[choice], color="blue")

plt.xlabel('Days')
plt.ylabel('Dollars')
plt.title('The S&P500 (red) vs. Your Investment (blue),' ' Using Adjusted Share Amounts for Even Start')
# legend(['S&P500', choice])
plt.show()
inquirer
  • 4,286
  • 2
  • 9
  • 16
  • I would be grateful if you vote for my answer! And I also added an animation stop when the graph was drawn: 'if (len(data) - 1) == i:'. So that there is no error at the end. The fact is that at the end there is an iteration on non-existent elements. Let's say you have an array length of 20 and when you try to access 21 non-existing elements, a failure occurs. Also removed unnecessary arrays l1, l2. – inquirer Mar 25 '22 at 08:21
  • 1
    I don't even have a 15 reputation yet so I can't post a vote :( but your help has been outstanding to say the least, thanks again! – gerald Mar 25 '22 at 10:41
  • Select the check mark so that it turns green. It is below two triangles. In any case, I am glad that your task has been solved. – inquirer Mar 25 '22 at 10:50
  • 1
    I'm only one point away apparently, but who knows how this works? Maybe you could vote for me somehow. – gerald Mar 25 '22 at 10:53
  • You voted for me, now the jackdaw has turned green. So the answer is counted. Thanks! – inquirer Mar 25 '22 at 10:57