Skip to content

Instantly share code, notes, and snippets.

@bundyfx
Created April 1, 2019 18:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bundyfx/a474649fe399496f2c881d0c6b91c351 to your computer and use it in GitHub Desktop.
Save bundyfx/a474649fe399496f2c881d0c6b91c351 to your computer and use it in GitHub Desktop.
import requests
import re
import pandas as pd
import csv
from random import choice
from bs4 import BeautifulSoup
from datetime import datetime
from time import mktime
class Stock():
def __init__(self, stock, interval, begin_date, end_date):
self.stock = stock
self.interval = interval
self.url = 'https://finance.yahoo.com/quote/{0}/history'.format(stock)
self.begin_date = self._convert_to_unix(begin_date)
self.end_date = self._convert_to_unix(end_date)
self._request()
def _convert_to_unix(self, date):
return int(mktime(datetime.strptime(date, '%d-%m-%Y').timetuple()))
def _load(self, data):
[self.crumb] = re.findall('"CrumbStore":{"crumb":"(.+?)"}', str(
BeautifulSoup(data.text, 'lxml')
))
self.cookies = data.cookies
self.csv_url = 'https://query1.finance.yahoo.com/v7/finance/download/{0}?period1={1}&period2={2}&interval={3}&events=history&crumb={4}'.format(
self.stock, self.begin_date, self.end_date, self.interval, self.crumb
)
def _request(self):
req = requests.get(self.url)
self._load(
req
)
def get(self):
_csv = requests.get(self.csv_url, cookies=self.cookies, verify=False)
decoded_content = _csv.content.decode('utf-8')
cr = csv.reader(decoded_content.splitlines(), delimiter=',')
for row in list(cr):
print(row)
def main():
amzn = Stock('AMZN', '1d', "03-03-2019", "03-04-2019")
omg_my_shares_are_up = amzn.get()
print(omg_my_shares_are_up)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment