I was writing this code for downloading the stock data and finding the percentage change in the price over the given time span. After doing all the calculations, retrievals, and storing the final data in a list, I wanted to sort the change list, but I was unable to do so. Please help me!
from pandas_datareader import data
import matplotlib.pyplot as plt
import pandas as pd
from datetime import date
import numpy as np
change=[]
today = date.today()
tickers = ['^GSPC', 'AAPL', 'MSFT', 'GOOG', 'MS', 'JPM']
for tick in tickers:
start_date = '2012-01-01'
end_date = today
dataset = data.DataReader(tickers, 'yahoo', start_date, end_date)
close=dataset['Close']
close_new=close.shift(1)
close2=close-close_new
close3=close2.dropna()
u=close.loc['2012-01-04',tick]
v=close.loc['2020-06-22',tick]
c=((v-u)/u)*100
change.append(c)
print(change.sort())
The list.sort()
method, modifies the list in-place (and returns None
). Usually it’s less convenient than sorted()
- but if you don’t need the original list, it’s slightly more efficient. Anyway, you can use sorted
:
print(sorted(change))
or numpy.sort
:
print(np.sort(change))