pandas yahoo finance real time data - python

Is it possible to get real time stock data with pandas from yahoo finance?
For historical data i would do the following:
import pandas.io.data as web
aapl = web.get_data_yahoo('AAPL')
Is there a way to get the latest aapl price?

EDIT:
Yahoo has ended their free finance API so this answer is no longer relevant. Below is my answer for pre-2019 purposes.
Archival:
There's plenty of libraries available for this. Pandas doesn't explicitly do this though.
Most simply, I would suggest you just use a web library to download yahoo data. I like using requests, but you could also use urllib. You can coerce the response into a data frame after you get it.
import requests
requests.get("http://download.finance.yahoo.com/d/quotes.csv?s=AAPL&e=.csv&f=nsl1op").text
The nsl1op format var is from the docs:
I will use here the tags of name(n), symbol(s), the latest value(l1), open(o) and the close value of the last trading day(p)
Your response data should look something like
u'"Apple Inc.","AAPL",114.63,113.50,115.07\r\n'
You can just split up the string using the csv library and throw it into a data frame from there

To answer your question about using Pandas specifically, you can pull stock data from yahoo using pandas like so:
from pandas.io.data import DataReader
from datetime import datetime
aapl = DataReader('AAPL', 'yahoo', datetime(2015,7,1), datetime(2015,7,1))
print(aapl['Adj Close'][0])
This code results in:
126.599998
The other keys you can use are Open, Close, High, Low, and Volume.
Keep in mind that the returned dataset is an array. You need to enumerate said array to get the data, either by specifying your index, or with a for loop.

You can use below code to get all info from yahoo finace api:
import pandas as pd
from pandas_datareader import data as wb
aapl=wb.DataReader('AAPL',start='2015-1-1',data_source='yahoo')
print(aapl)

Related

Convert NOAA JSON value to data frame in python

From NOAA API, I can get Boston hourly weather forecast information via JSON file. Here is the link: https://api.weather.gov/gridpoints/BOX/70,76
(This JSON file is too long to present comprehensively here, please kindly click the link to see it)
I want to convert some of the weather variables into data frame to proceed further calculation.
The expected format is as below for temperature. I will use the same format to get precipitation, snowfall, humidity, etc.
expected dataframe format
Now I cannot figure out how to convert it to the dataframe I want. Please kindly help....
For now, here is the best I can do, but still cannot extract validTime and values from Temperature
import requests
import pandas as pd
response = requests.get("https://api.weather.gov/gridpoints/BOX/70,76")
# create new variable forecast
forecast=response.json()
df1 = pd.DataFrame.from_records(forecast['properties']).reset_index()
df2=df1.loc[ :1 , ['temperature','quantitativePrecipitation', 'snowfallAmount', 'relativeHumidity', 'windGust', 'windSpeed', 'visibility']]
df2
current output

Is there a way to work around python to pull multiple tickers / symbols from binance and extract necessary information from them?

I would like to pull multiple tickers from Binance and have managed to do so and write them into a CSV file. However, I am having an issue pulling specific information from the columns to have the OHLCV data only and then work on wrapping ta-lib around this data.
For eg. I would like to keep the OHLCV data from each row for XRPBTC, NEOBTC which are in columns, and write them into a new file or just wrap ta-lib around the same data. It works fine for just one ticker but I'm having some troubles extracting this for multiple tickers.
I am given to understand that these are in the format of lists, can I split them to keep only OHLCV data and from each row and from each column and write them into a new file - is there an easier way of splitting a list?
screenshot of the data
Link to relevant binance documentation Klines candlestick data
import pandas as pd
import numpy as np
import csv
import talib as ta
from binance.client import Client
candlesticks = ['XRPBTC','NEOBTC'] # unable to split for each row in multiple columns
data = pd.DataFrame()
for candlestick in candlesticks:
data[candlestick] = client.get_historical_klines(candlestick, Client.KLINE_INTERVAL_15MINUTE, "1 Jul, 2021")
data.to_csv("XRPNEO15M.csv")
print(data)

Scanning Finviz Stocks

Hello here is a screener tool for Finviz but my stock_list result returns object of type Screener I am trying to put that into a data frame but I am having issues as the data is one long string divided by pipes. I tried to use str but method does not exists in the screener class. I am new to python this looks easy but I just dont know the proper syntax here can anyone help. Thank you!
import pandas as pd
import nest_asyncio
from finviz.screener import Screener
import csv
import sys
from datetime import datetime
nest_asyncio.apply()
filters = ['idx_sp500'] # Shows companies in NASDAQ which are in the S&P500
stock_list = Screener(filters=filters, order='price')
You could output the data to a csv file and read the file using pandas:
stock_list = Screener(filters=filters, order='price')
stock_list.to_csv(filename="stocks.csv")
df = pd.read_csv("stocks.csv")

Slicing a spreadsheet in Python terminal

So I'm making a program that asks a server a data and it send back. The problem is when I ask for some data it answer:
And I need just the value from the column "Close" . I can't figure out how to do it.
Code:
import yfinance as yf
import time
stock = yf.Ticker("MSFT")
data = stock.history(period="1")
oferta= stock.info["bid"]
print(data)
yfinance uses the pandas library to return data. You are receiving a pandas' DataFrame object in data, so to select only the "Close" column you can do this:
print(data["Close"].iloc[0])

Python 2.7 csv download from URL

I'm trying to do some basic analsys on ether historical prices for a school project. My problem is quite a simple one I think. I made a function that download the data from the URL, but the format is wrong. I got a dataframe thats size is (0,~14k). So I download the data, but I'm not sure how should I format it into a form that I can use.
I see 2 possibilities, I format the dataframe after download, which I will try to do. Or I download it in the correct format first, which would be the better and more elegant solution.
My problem that I don't know how to do the 2. and I may not succeed on the 1. thats why I make this post.
def get_stock_price_csv_from_poloniex():
import requests
from pandas import DataFrame
from io import StringIO
url = 'https://poloniex.com/public?command=returnChartData&currencyPair=USDT_ETH&start=1435699200&end=9999999999&period=14400'
csv = requests.get(url)
if csv.ok:
return DataFrame.from_csv(StringIO(csv.text), sep=',')
else:
return None
The source data is not CSV, it's json. Luckily pandas provides facilities for working with it as well.
import requests
from pandas.io.json import json_normalize
url = 'https://poloniex.com/public?command=returnChartData&currencyPair=USDT_ETH&start=1435699200&end=9999999999&period=14400'
resp = requests.get(url)
data_frame = json_normalize(resp.json())

Categories

Resources