Python:同时使用相同的函数运行多个变量。 Python新手

时间:2016-03-29 21:11:54

标签: python function finance yahoo-finance google-finance

过去几天我一直在使用python,并开始研究一个项目。目前正试图弄清楚如何使用多个变量执行相同的功能(在这种情况下,股票代码)。优选地,一个输入()用逗号或其他东西分隔。尽管如此,我还是遇到了这个问题。任何人都能指出我下一步的方向吗? (同时使用多个变量运行相同的函数。)

这是我的代码:

#Google + Yahoo Finance Stock Lookup
from googlefinance import getQuotes
from yahoo_finance import Share
import googlefinance
import datetime, time
import os
from datetime import datetime


tDate = datetime.now().strftime('%Y-%m-%d')
print (tDate)
tDateConv = str(tDate)

try:
    os.chdir('/Users/Jakes_Macbook/Desktop/Python/Stocks')
except Exception:
    print('Default Path does not exsist, make sure your directory is   right.')
    pass

run = True
while run == True:
    print('You are currently storing the file in ')
    print(os.getcwd())
    print('type "yes" to continue')
confirm = input()
if confirm == 'yes':
    print ('ok\n')
    try:
        os.makedirs(tDateConv)
    except Exception:
        pass
    os.chdir(tDateConv)
    print('File will be saved to:')
    print(os.getcwd())
    break
else:
    print('Where do you want to store the file?')
    changeDir = input()
    os.chdir(changeDir)


print('What Stock or Stocks would you like to look up?')
stockSymbol = input()

def runStocks():

    print (" ")
    print ("Stock Symbol: " + stockSymbol)
    stockSymbolYhoo = Share(stockSymbol)

    stockFile = open(str(stockSymbol)+'.txt', 'a')

    dicStored = googlefinance.getQuotes(stockSymbol)[0]
    numStoredPrice = float(dicStored['LastTradePrice'])
    print('Stock Open: ' + stockSymbolYhoo.get_open())
    print ("Stored Price: " + str(numStoredPrice))
    stockFile.write(str("\n" + "Stock Symbol: " + stockSymbol + "\n"))
    stockFile.write(str("\n" + "Open Price: " + stockSymbolYhoo.get_open() + "\n"))
    stockFile.write(str("Stored Price: " + str(numStoredPrice)+'\n'))


    runs = 0
while runs < 5:
    stor = googlefinance.getQuotes(stockSymbol)[0]
    price = stor['LastTradePrice']
    print(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')) + " | " + price)
    stockFile.write(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')) + " | Price " + price + ' \n')

    numPrice = float(price)

    if numPrice < numStoredPrice*float(.995):
        print ("buy")

    time.sleep(5)
    runs = runs + 1

stockFile.close()

runStocks()

我的目标是让每个输入的股票代码在今天的文件夹中创建自己的文件。一旦我得到多个功能,我很确定我能弄清楚如何做到这一点。提前谢谢。

另外,如果您有任何重要建议或最佳做法,请与我们联系。这就像我第二天使用python一样。再次感谢。

1 个答案:

答案 0 :(得分:0)

将它们传递给函数:

# Note the definition was updated to be able to pass in a stockSymbol
def runStocks(stockSymbol):

    print (" ")
    print ("Stock Symbol: " + stockSymbol)
    stockSymbolYhoo = Share(stockSymbol)

    stockFile = open(str(stockSymbol)+'.txt', 'a')

    dicStored = googlefinance.getQuotes(stockSymbol)[0]
    numStoredPrice = float(dicStored['LastTradePrice'])
    print('Stock Open: ' + stockSymbolYhoo.get_open())
    print ("Stored Price: " + str(numStoredPrice))
    stockFile.write(str("\n" + "Stock Symbol: " + stockSymbol + "\n"))
    stockFile.write(str("\n" + "Open Price: " + stockSymbolYhoo.get_open() + "\n"))
    stockFile.write(str("Stored Price: " + str(numStoredPrice)+'\n'))

stockSymbols = input("Enter stock symbols separated by commas").split(",")

for stockSymbol in stockSymbols:
    runStocks(stockSymbol) # Call your function in a loop