我知道,如果我这样做的话,这段代码看起来会好很多,以便在一个函数中检查当前价格与开盘价,这样我就不必为我想检查的每只股票重新编写它,但我不知道如何开始正确地做到这一点。你们中有人有一些建议可以帮助我入门吗?
from yahoo_finance import Share
apple = Share('AAPL')
appleopen = float(apple.get_open())
applecurrent = float(apple.get_price())
if appleopen > applecurrent:
print(("Apple is down for the day. Current price is"), applecurrent)
else:
print(("Apple is up for the day! Current price is "), applecurrent)
applechange = (applecurrent - appleopen)
if applechange > 0:
print(('The price moved'),abs(applechange),("to the upside today."))
else:
print(('The priced moved'),abs(applechange),("to the downside today."))
print('-----------------------')
nflx = Share('NFLX')
nflxopen = float(nflx.get_open())
nflxcurrent = float(nflx.get_price())
if nflxopen > nflxcurrent:
print(("Netflix is down for the day. Current price is"), nflxcurrent)
else:
print(("Netflix is up for the day! Current price is "), nflxcurrent)
nflxchange = (nflxcurrent - nflxopen)
if nflxchange > 0:
print(('The price moved'),abs(nflxchange),("to the upside today."))
else:
print(('The priced moved'),abs(nflxchange),("to the downside today."))
最佳答案
试试这个:
from yahoo_finance import Share
Store = {
'AAPL': 'Apple',
'NFLX': 'Netflix'
}
for code in Store:
name, shr = Store[code], Share(code)
sopen = float( shr.get_open() )
scurr = float( shr.get_price() )
schange = scurr - sopen
movement = 'down' if schange < 0 else 'up'
print( format("{} is {} for the day. Current price is {}"), name, movement, scurr) )
print( format('The price moved {} to the {}side today.',abs(schange), movement) )
print('-----------------------')
关于python - 我怎样才能使这段代码更加Pythonic——具体来说,将一些东西合并到一个函数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32723600/