☆☆ 新着記事 ☆☆

2020年6月19日金曜日

Finance APIを色々試してみる。

1. Alpha Vintage
2. Financial Modeling Prep API
3. yfinnance (Main使用)
一度は閉鎖されたYahoo FinanceのAPIを、なんとか使おうというPython ライブラリ



1. Alpha Vintage
・無料の場合、制限あり
・Index(DJIA等)やETFの値が取得できない



2. Financial Modeling Prep API 
https://financialmodelingprep.com/developer/docs/
・Market Movers Gainers, Loosers取得のエンドポイントあり。
・API 自体は使いやすい。
・CAPサイズ等でフィルターできないので、小規模な会社の株が表示されやすい。

[['Ascena Retail Group Inc.', 'ASNA', '$1.29', '(+119.76%)'],
 ['Array BioPharma Inc.', 'ARRY', '$46.57', '(+61.25%)'],
 ['Pensare Acquisition Corp. Warrant', 'WRLSW', '$0.18', '(+56.39%)'],
 ['Natuzzi S.p.A.', 'NTZ', '$1.77', '(+54.59%)'],
 ['Global Eagle Entertainment Inc.', 'ENT', '$3.23', '(+53.81%)'],
 ['Hamilton Beach Brands Holding Company Class A', 'HBB', '$14.58', '(+40.87%)'],
 ['CYREN Ltd.', 'CYRN', '$1.79', '(+34.59%)'],
 ['WISeKey International Holding AG', 'WKEY', '$9.50', '(+34.18%)'],
 ['Nebula Acquisition Corporation Warrant', 'NEBUW', '$2.45', '(+33.15%)'],
 ['Ocugen, Inc.', 'OCGN', '$0.38', '(+32.85%)']]

知らんがな、こんな会社、という会社が出てくる。
2. yfinnance
(特徴)
・無制限アクセス
・Index(DJIA等)やETFの値も取得できる


(参考)
https://aroussi.com/post/python-yahoo-finance
https://towardsdatascience.com/a-comprehensive-guide-to-downloading-stock-prices-in-python-2cd93ff821d4

(取得したデータへのアクセスはこちら)

Python Object -- Excelで管理する典型的表形式


(実際にやってみる)
pip install yfinance
でインストールしてね。



import yfinance as yf

msft =
yf.Ticker("MSFT")
print(msft)
"""
returns
<yfinance.Ticker object at 0x1a1715e898>
"""

# get stock info
msft.info //使えない pip install lxmlが必要


# get historical market data
msft.history(period="max")
"""
returns:
              Open    High    Low    Close      Volume  Dividends  Splits
Date
1986-03-13    0.06    0.07    0.06    0.07  1031788800        0.0     0.0
1986-03-14    0.07    0.07    0.07    0.07   308160000        0.0     0.0
...
2019-04-15  120.94  121.58  120.57  121.05    15792600        0.0     0.0
2019-04-16  121.64  121.65  120.10  120.77    14059700        0.0     0.0
"""

# show actions (dividends, splits)
msft.actions
"""
returns:
            Dividends  Splits
Date
1987-09-21       0.00     2.0
1990-04-16       0.00     2.0
...
2018-11-14       0.46     0.0
2019-02-20       0.46     0.0
"""

# show dividends
msft.dividends
"""
returns:
Date
2003-02-19    0.08
2003-10-15    0.16
...
2018-11-14    0.46
2019-02-20    0.46
"""

# show splits
msft.splits
"""
returns:
Date
1987-09-21    2.0
1990-04-16    2.0
...
1999-03-29    2.0
2003-02-18    2.0


msft = yf.Ticker("MSFT")
で取得できるものは、yfinance.Ticker object <MSFT>

print(dir(msft))で確認すると、
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_balancesheet', '_base_url', '_calendar', '_cashflow', '_download_options', '_earnings', '_expirations', '_financials', '_fundamentals', '_get_fundamentals', '_history', '_info', '_institutional_holders', '_isin', '_major_holders', '_options2df', '_recommendations', '_scrape_url', '_sustainability', 'actions', 'balance_sheet', 'balancesheet', 'calendar', 'cashflow', 'divi
dends', 'earnings', 'financials', 'get_actions', 'get_balance_sheet', get_balancesheet', 'get_calendar', 'get_cashflow', 'get_dividends', 'get_earnings', 'get_financials', 'get_info', 'get_institutional_holders', 'get_isin', 'get_major_holders', 'get_recommendations', 'get_splits', 'get_sustainability', 'history', 'info', 'institutional_holders', 'isin', 'major_holders', 'option_chain', 'options', 'quarterly_balance_sheet', 'quarterly_balancesheet', 'quarterly_cashflow', 'qu
arterly_earnings', 'quarterly_financials', 'recommendations', 'splits', 'sustainability', 'ticker']

print(dir(msft.info))
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '
__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

print(Ticker.info)
{'zip': '98052', 'sector': 'Technology', 'fullTimeEmployees': 144000, 'longBusinessSummary': 'Microsoft Corporation deve
lops, licenses, and supports software, services, devices, and solutions worldwide. Its Productivity and Business Process
es segment offers Office, Exchange, SharePoint, Microsoft Teams, Office 365 Security and Compliance, and Skype for Busin
ess, as well as related Client Access Licenses (CAL); Skype, Outlook.com, and OneDrive; LinkedIn that includes Talent an
d marketing solutions, and subscriptions; and Dynamics 365, a set of cloud-based and on-premises business solutions for
small and medium businesses, large organizations, and divisions of enterprises. Its Intelligent Cloud segment licenses S
QL and Windows Servers, Visual Studio, System Center, and related CALs; GitHub that provides a collaboration platform an..... 続く


https://www.youtube.com/watch?v=UPmf-eijhXI&list=PLaYT64KWZAEOOf3FnrYZKrm0GW7--go_a&index=3
info = sorted([[k,v] for k,v in msft.info.items()])
for k,v in info:
    print(f'{k}:{v}')

52WeekChange:0.44700778
SandP52WeekChange:0.015086055
address1:One Microsoft Way
algorithm:None
annualHoldingsTurnover:None
annualReportExpenseRatio:None
ask:0
askSize:1800
averageDailyVolume10Day:37895183
averageVolume:39978820
averageVolume10days:37895183

.history()のオプションの使い方

◆periodで指定
data=DJIA.history(
    period="1d",
   interval='5m'
    )
print(data)
                             Open    High     Low   Close  Volume  Dividends  Stock Splits
Datetime
2020-06-18 09:30:00-04:00  284.97  285.45  284.69  285.19  290160          0             0
2020-06-18 09:35:00-04:00  285.08  285.75  284.55  285.56  117414          0             0
2020-06-18 09:40:00-04:00  285.54  285.92  285.38  285.91   76632          0             0



data=DJIA.history(
    start="2020-06-11",
    end='2020-06-19' #ここで指定した日は含まない。
    ) #intervalも指定できる

Date
2020-06-10  27251.89  27355.22  26938.05  26989.99  6570840000          0
2020-06-11  26282.51  26294.08  25082.72  25128.17  7018890000          0
2020-06-12  25659.42  25965.55  25078.41  25605.54  5832250000          0
2020-06-15  25270.39  25891.58  24843.18  25763.16  5740660000          0
2020-06-16  26326.68  26611.03  25811.70  26289.98  5829240000          0
2020-06-17  26330.52  26400.07  26068.41  26119.61  4549390000          0
2020-06-18  26016.45  26154.20  25848.53  26080.10  4429030000          0


====簡単なグラフ
y_axis =[]
for y in data['Close']:
    y_axis.append(y)

x_axis =[]
fmt='%m/%d- %H:%M'
for x in data['Close'].keys():
    date = datetime.datetime.strftime(x,'%m/%d- %H:%M')
    x_axis.append(date)

fig = plt.figure(figsize=(7, 4))
ax = fig.add_subplot(1, 1, 1, fc='#191970')


plt.style.use=('seaborn-dark')
plt.plot(x_axis, y_axis, color='#98fb98')

#間隔の日数を指定
ticks = 12
plt.xticks(range(0, len(x_axis), ticks), x_axis[::ticks])


# 次の2行は軸ラベルを回転させるために使用
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, fontsize=5)

plt.tick_params( labelsize=7)
plt.title(ticker_name)
plt.xlabel('Date')
plt.ylabel('USD')
plt.grid(True)

plt.show()
plt.savefig('price.png')

◇.infoについて


◇msft.actions
            Dividends  Stock Splits
Date
2018-09-24      0.330           0.0
2018-12-24      0.421           0.0
2019-03-18      0.324           0.0
2019-06-24      0.416           0.0
2019-09-23      0.384           0.0
2019-12-23      0.458           0.0
2020-03-23      0.363           0.0
2020-06-22      0.424           0.0

0 件のコメント:

コメントを投稿