Thursday, May 16, 2019

extract data from stocks and graph it

# import libraries
import requests
import time
import http
from bs4 import BeautifulSoup
from datetime import date
import matplotlib.pyplot as plt

import json

jours = []
prix = []



def duplicate_quote ( x= str):
   
   
    """If it founf=ds onw quote it duplicates it
   
   
    >>>duplicate_quote ("{'Thu Jan 24 04:28:23 2019': 52.64}" )
    >>>('{"Thu Jan 24 04:28:23 2019": 52.64}' )
    """
    if "'" in x:
       j = x.replace("'", '"')
    return j

#2 lineas codigo debajo vrean file primero
f1 = open('us_cad.txt', 'a')
f1.close

f1 = open('us_cad.txt', 'r')
texto = f1.read()
#texto
#"{'Thu Jan 24 04:28:23 2019': 52.64}"

#code below reverses the code and find the '{' tehn we  get the last dicitonary we substract 1 to include last character becasue of slincing
if texto != '':
    new_dic = texto [-(texto[::-1].find('{')) - 1 :  ]
    duplicate_quote(new_dic)
    dic = json.loads(duplicate_quote(new_dic))
    f1.close()
else:
    dic = {}
    precio = []
    f1.close()
#time.ctime()
#'Thu Jan 24 03:51:29 2019'


today = date.today()
today

days = []


quote_page = 'http://30rates.com/usd-cad-forecast-canadian-dollar-to-us-dollar-forecast-tomorrow-week-month'

# query the website and return the html to the variable ‘page’
page = requests.get(quote_page)
soup = BeautifulSoup(page.content, 'html.parser')


# Take out the <div> of name and get its value
name_box = soup.find('strong')

name = name_box.text
print(name)

precio = []
precio.append(float(name))

days = []
days.append(today.strftime("%d/%m/%y"))

dias = []
dias.append(time.ctime())

#plt.plot(dias, precio)

#plt.plot([1,2,3], [3,4,5])



for i in range(len(dias)):
    dic[dias[i]] = precio[i]

with open('us_cad.txt', 'w') as f:
    f.write(str(dic))
f.close


for i in dic:
    jours.append(i)
    prix.append(dic[i])
plt.plot(jours, prix)





           

No comments:

Post a Comment