如何处理yahoofinance报价阅读器的打印输出?

2024-09-28 18:53:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在设计一个工具来帮助我管理股票投资组合中的风险。我有一些代码可以从雅虎财经收集4只股票,2倍多头和2倍空头的当前价格数据。这是使用雅虎金融工具。在

我可以收集数据,但我不知道如何将价格除以对方以返回价差的价值(stockA/stockB作为一种相对价值交易)

#always helpful to show the version:
(env) LaurencsonsiMac:~ admin$ python
Python 2.7.10 (default, Oct 23 2015, 18:05:06) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin



from yahoo_finance import Share
>>> L1 = Share('YHOO')
>>> L2 = Share('GOOG')
>>> S1 = Share('AAPL')
>>> S2 = Share('MSFT')
>>> print L1.get_price()
50.55
>>> print S1.get_price()
154.45

小小的胜利!我可以卖这个价钱:)但是 我不知道如何将这个输出作为一个对象来操作,并将Long1定义为“print L1.get_price()返回的任何内容” 最终的输出将是这样一个表,其中的价差值是一个单独的(非常重要!)小数点后两到三位。在

^{pr2}$

我试图将Long1和Short1定义为L1.get_price()打印的数字:

>>> Long1 = "L1.get_price()"
>>> Short1 = "S2.get_price()"

希望我能从这两个人身上得到一个数字:

>>> Long1/Short1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'str'

所以我试着把这些数字转换成一个浮点数(因为它可能有用,为什么不行),但我显然误解了一些事情:

>>> float(Long1)/float(Short1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: L1.get_price()

或者,我确实使用pandas模块使用这段代码获得了一个输出:(为此感谢Brad Solomon:)

import pandas_datareader.data as web

def get_quotes(symbols, type='dict'):
    quotes = web.get_quote_yahoo(symbols)['last']
    if type == 'dict':
        quotes = quotes.to_dict() # otherwise, Series
    return quotes

quotes = get_quotes(symbols=['RAD', 'MSFT']); quotes
Out[16]: {'MSFT': 70.409999999999997, 'RAD': 3.46}

但是如何实现MSFT/RAD,让python“读取字符串”?在

我真的很困,有人能告诉我怎样才能把我的报价变成我能用的实物吗? 谢谢您!!在


Tags: tol1sharegettype数字floatprice
2条回答

Long1Short1的变量赋值是错误的:不是调用方法,而是用函数名指定字符串文本。尝试将其更改为:

>>> Long1 = L1.get_price()
>>> Short1 = S2.get_price()

将值放在引号中就是告诉Python它是一个字符串数据类型。你用它来划分,那将失败。即使在使用float函数时,因为该值实际上是一个字符串,而不是表达式的值,您可能希望它会导致函数调用在引号内失败。 不需要使用引号,直接函数调用就可以做到这一点。在

>>> Long1 = L1.get_price()

>>> Short1 = S2.get_price()

相关问题 更多 >