Search code examples
pythonplotfinancestock

Mistake in plotting stocks


As I cannot find the mistake, I post it here. The task is relatively simple and from a python beginner program:

  1. Use pd.read_csv() to import 'stock_prices.csv', parsing the 'Date' column and also setting the 'Date' column as index before assigning the result to stock_prices. Inspect the result using .info().

  2. Calculate the price return for the index components by dividing the last row of stock_prices by the first, subtracting 1 and multiplying by 100. Assign the result to price_return. Plot a horizontal bar chart of the sorted returns with the title Stock Price Returns.

Here is my solution (wrong):

# Import prices and inspect result
stock_prices = pd.read_csv('stock_prices.csv', parse_dates=['Date'], index_col='Date')
print(stock_prices.info())

# Calculate the returns
price_return = stock_prices.iloc[-1].div(stock_prices.iloc[0]).sub(1).mul(100)
price_return.sort_values(inplace=True)

# Plot horizontal bar chart of sorted price_return   
price_return.plot.barh(title='Stock Price Returns')
plt.show()

And there ist a hint:

Have you calculated price_return according to the instructions? Use stock_prices.iloc[-1] and stock_prices.iloc[0] to access the last and then 1st rows of stock_prices. The arithmetic should be completed using .div(), .sub(), and .mul().

Can you help me with that task?

Try to followed the task and the hint


Solution

  • This worked for me

    Print tickers

    print(tickers)
    

    Import prices and inspect result

    stock_prices = pd.read_csv('stock_prices.csv',parse_dates=['Date'],index_col='Date')
    print(stock_prices.info())
    

    Calculate the returns

    price_return = stock_prices.iloc[-1].div(stock_prices.iloc[0]).sub(1).mul(100)  
    
    price_return.sort_values().plot(kind='barh',title='Stock Price Returns')
    plt.show()