0

I am coding a project for school (A-Level) and need to be able to download stock data and chart it. I am able to chart the data using matplotlib. However I am only allowed to use a certain number of libraries.

I need to get the data without importing a library,but was unable to do it. I've tried downloading from https://query1.finance.yahoo.com/v7/finance/download/ticker, but the crumb value keeps changing so I keep getting errors from wrong cookie.

How can i fix this? Or is there an easier site for the data?

My code:

import requests

r = requests.get("query1.finance.yahoo.com/v7/finance/download/…)

file = open(r"MSFT.csv", 'w')

file.write(r.text) file.close()
ZF007
  • 3,708
  • 8
  • 29
  • 48
  • I can't currently test anything but you might want to look here https://stackoverflow.com/questions/44030983/yahoo-finance-url-not-working – CumminUp07 Dec 23 '19 at 16:25

2 Answers2

0

Download the data from https://datahub.io or else you can subscribe for real time data feed from third party vendors of different exchanges.

0

You stated: 'I am only allowed to use a certain number of libraries.' What does that mean? You should be able to use any libraries you need to use, right. Run the script below. It will download stock data from Yahoo and plot the time series.

import pandas as pd  
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import scipy.optimize as sco
import datetime as dt
import math
from datetime import datetime, timedelta
from pandas_datareader import data as wb
from sklearn.cluster import KMeans
np.random.seed(777)


start = '2019-4-30'
end = '2019-10-31'
# N = 90
# start = datetime.now() - timedelta(days=N)
# end = dt.datetime.today()



tickers = ['MMM',
'ABT',
'ABBV',
'ABMD',
'AAPL',
'XEL',
'XRX',
'XLNX',
'XYL',
'YUM',
'ZBH',
'ZION',
'ZTS'] 

thelen = len(tickers)

price_data = []
for ticker in tickers:
    prices = wb.DataReader(ticker, start = start, end = end, data_source='yahoo')[['Adj Close']]
    price_data.append(prices.assign(ticker=ticker)[['ticker', 'Adj Close']])

df = pd.concat(price_data)
df.dtypes
df.head()
df.shape

pd.set_option('display.max_columns', 500)

df = df.reset_index()
df = df.set_index('Date')
table = df.pivot(columns='ticker')
# By specifying col[1] in below list comprehension
# You can select the stock names under multi-level column
table.columns = [col[1] for col in table.columns]
table.head()

plt.figure(figsize=(14, 7))
for c in table.columns.values:
    plt.plot(table.index, table[c], lw=3, alpha=0.8,label=c)
plt.legend(loc='upper left', fontsize=12)
plt.ylabel('price in $')

enter image description here

ASH
  • 20,759
  • 19
  • 87
  • 200