1
\$\begingroup\$

I know that this code would look a lot better if I made it so that checking the current prices against the open prices were in a function. This would avoid rewriting it for every stock I want to check. But I'm not sure how to get started on doing that properly. Do any of you have some tips to get me started?

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."))
\$\endgroup\$
  • \$\begingroup\$ Non-technical note: I'm unfamiliar with the Yahoo Finance library, but bear in mind that stock movements should not be calculated based on the open price for a day. Last price would be preferable, so that it changes as you check through the day. For example, a stock I own shares in plummeted 3% yesterday morning, but finished the day positive. Your script - if run in the afternoon - would have still have told me it was "down for the day". \$\endgroup\$ – mirichan Sep 22 '15 at 22:51
  • \$\begingroup\$ oh jeez, great catch @scarl3tt! thank you for that! \$\endgroup\$ – n1c9 Sep 22 '15 at 23:10
2
\$\begingroup\$

As you yourself noted, you need a function:

def financial_info(acronym):
    company = Share(acronym)

    company_open = float(company.get_open())
    company_current = float(company.get_price())

    if company_open > company_current:
        print(company, " is down for the day. Current price is ", company_current)
    else:
        print(company, " is up for the day! Current price is ", company_current)

    # ...

I just wrote a part of it, you sure are able to finish it :)

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.