0

What I am trying to do is to get this line of code to work by putting a price from Yahoo Finance for a stock into a spreadsheet. I have asked quite a few people and I have researched the issue but I haven't gotten it to work.

This is the trouble line of code:

ws.cell(1,i+1).value = str.replace(price','price')

I get errors likes, "replace' requires a 'str' object but received a 'list' or 'int' object has no attributes everytime I modify it. Thanks for the help in advance.

from openpyxl import Workbook

import urllib
import re

from openpyxl.cell import get_column_letter

wb = Workbook()

dest_filename = r'empty_book.xlsx'

ws = wb.create_sheet()

ws.title = 'Stocks'
symbolslist = ["aapl","spy","goog","nflx"] 

i=0
while i<len(symbolslist):
    #counts each object as 1 in the list
    url = "http://finance.yahoo.com/q?s="+symbolslist[i]+"&q1=1"
    htmlfile = urllib.urlopen(url)
    htmltext = htmlfile.read()
    regex = '<span id="yfs_l84_'+symbolslist[i]+'">(.+?)</span>'
    pattern = re.compile(regex)
    price = re.findall(pattern,htmltext)
    print "The price of", symbolslist[i], " is ", price 
    ws.cell(1,i+1).value = str.replace(price','price')
    i+=1


wb.save(filename = dest_filename)

Importing the CSV module is better than using Excel for data analysis because it is open source friendly.

2 Answers 2

2

I don't even think you need the EXCEL API to do this, you are merely work offline, so write the finance stock price using CSV format, and then open the csv file using EXCEL. like this (psudo code, not exact one ):

with( f=open( "a.csv" ) ):
    f.writeline( ",".join(l) );
Sign up to request clarification or add additional context in comments.

1 Comment

That's an interesting idea...but where do I put that code? I want the Excel file for manipulating the data later.
0
  1. re.findall return a list object, you may want to get the first object of the list.

  2. you can only use str.replace from an string object, such asprice.replace('a', 'b')

  3. should use ws.cell('F5') instead of ws.cell(1,1) to access one cell.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.