Python Forum

Full Version: Pulling & Reading Date from UDF that Compare it to Live Data
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello Everyone!
Would you help me solve the following problem i have:
I am trying to write a user defined function that would load, read date from a csv file, itereate through the column where row of values being examined are located, check those values against current value (price = live.get_live_price("AAPL"))and then take an action (in this case to print it out) if the comparison meet certain condition (row value < price or row == price). when i run the script i do not get any error message and yet there is no output at all.
Thank you
#import all necessary modules
import csv
from yahoo_fin import stock_info as live
import pandas as pd
from datetime import date
import datetime


def readfile(filepath):
    #get Apple's latest quote price
    price = live.get_live_price("AAPL")

    with open(r'C:\Users\...\Desktop\AAPLCSV', 'r') as file:
        reader = csv.reader(file)
        for index, row in reader:
            if row[3] < price:
                return price
            elif row[3] == price:
                return row[3]
            print(price, row[3])
(Jul-19-2019, 07:50 PM)firebird Wrote: [ -> ]when i run the script i do not get any error message and yet there is no output at all.
Because you don't call the function(readfile) at all.
There are both ValueError and logical error in your code Wink

Some points:
Can not use this without enumerate()
# for index, row in reader: 
for index, row in enumerate(reader):
price is float then need to compare with float,when read a csv you always get string out.
>>> from yahoo_fin import stock_info as live
>>> 
>>> price = live.get_live_price("AAPL")
>>> price
202.58999633789062
>>> type(price)
<class 'numpy.float64'>
When do like this with eg float,it will just return(out) as soon as True.
Then this do not make sense as don't know if 1 or 10 value it return price of.
if float(row[3]) < price:
    return price
Remove function and start testing small scale with hint given.
Hi snippsat,
Thank you for having taken the time to review and reply and made some valuable suggestion for assisting me.
Approaching to solve it 'small scale', the reworked code gets me the following output (below). Pardon my ignorance, when it comes to calling the function, i then have to create another function, don't i?
Output:
Apple's closing price today is 202.58999633789062
Values in row[3] from AAPLcsv file
177.9499969482422
176.22999572753906
175.60000610351562
175.44000244140625
184.27999877929688
183.0800018310547
186.50999450683594
191.80999755859375
194.86000061035156
193.9499969482422
194.6999969482422
191.5500030517578
192.89999389648438
196.0500030517578
199.67999267578125
200.3699951171875
198.8000030517578
198.5399932861328
198.42999267578125
197.77000427246094
200.2899932861328
198.67999267578125
Reworked code:
#import all necessary modules
import csv
from yahoo_fin import stock_info as live
import pandas as pd
from datetime import date
import datetime


#get Apple's latest quote price
price = live.get_live_price("AAPL")
with open(r'C:\Users\...\Desktop\AAPLcsv.csv', 'r') as file:
    reader = csv.reader(file)
    next(reader, None)#skip the header
    print("Apple's closing price today is", price)
    print('Values in row[3] from AAPLcsv file')
    for index, row in enumerate(reader):
        if float(row[3]) < price:
            print(row[3])
Hello, I'm still in need of some help with this code snippet. I revised my earlier code and now managing to call my function 'readfile' successfully. However, i'm stuck with this error message which generated in the part of 'if __name__ == "__main__":'.
I can't seem to pass the header of column in index 3 (row[3])- which is a string. The error i get:
Error:
Traceback (most recent call last): File "C:\Users\...\Desktop\funcTest1.py", line 22, in <module> if float(row[3]) < price: ValueError: could not convert string to float: '.'
This is my new, reworked code:
#import all necessary modules
import csv
from yahoo_fin import stock_info as live
import pandas as pd
from datetime import date
import datetime
 
 
def readfile(filepath):
 
    with open(r'C:\Users\...\Desktop\AAPLcsv.csv', 'r') as file:
        reader = csv.reader(file)
        next(reader, None)#skip header
        for index, row in enumerate(reader):
            return row
            
if __name__ == "__main__":
    #get Apple's latest quote price
    path = r'C:\Users\...\Desktop\AAPLcsv.csv'
    price = live.get_live_price("AAPL")
    for index, row in enumerate(readfile(path)):
        if float(row[3]) < price:
            print(row[3])
This will just iterate over all rows,and return only last row.
def readfile(filepath):
  
    with open(r'C:\Users\...\Desktop\AAPLcsv.csv', 'r') as file:
        reader = csv.reader(file)
        next(reader, None)#skip header
        for index, row in enumerate(reader):
            return row
Have to collect all row in list before return.
def readfile(filepath=''):
    apple_stock = []
    with open('apple.csv', 'r') as file:
        reader = csv.reader(file)
        next(reader, None)#skip header
        for index, row in enumerate(reader):
            apple_stock.append(row)
    return apple_stock
To do a test made apple.csv:
Output:
header 2,Name,a,1 1,John,b,204.4444 2,Eric,c,200.2899932861328 3,Brad,d,177.9499969482422
Added count and show live price.
#import all necessary modules
import csv
from yahoo_fin import stock_info as live
import pandas as pd
from datetime import date
import datetime

def readfile(filepath=''):
    apple_stock = []
    with open('apple.csv', 'r') as file:
        reader = csv.reader(file)
        next(reader, None)#skip header
        for index, row in enumerate(reader):
            apple_stock.append(row)
    return apple_stock

if __name__ == "__main__":
    #get Apple's latest quote price
    path = r'apple.csv'
    price = live.get_live_price("AAPL")
    count = 0
    for index, row in enumerate(readfile(path)):
        if float(row[3]) < price:
            print(row[3])
            count += 1
    print('-' * 10)
    print(f'Live price now is: {price} count below from {path} is: {count}')

Output:
1 200.2899932861328 177.9499969482422 ---------- Live price now is: 202.58999633789062 count below from apple.csv is: 3