yfinance python es una librería en Python que permite descargar información financiera, incluyendo precios históricos y datos actuales, desde la plataforma Yahoo Finance. Esta librería se utiliza comúnmente para análisis financiero y estudios de mercado, y es una herramienta popular entre los programadores y analistas de datos.
yfinance python
Para usar yfinance con Python, primero debes instalar la biblioteca yfinance. Puedes hacerlo usando el siguiente comando en la terminal o en el Anaconda prompt:
pip install yfinance
Una vez instalada la biblioteca, puedes importar tu código en Python y empezar a utilizarla. Si necesitas un ejemplo de código para descargar información de una acción de una compañía en particular sigue este ejemplo:
import yfinance as yf
# Obtener información de una acción específica
ticker = "AAPL" #es el ticket de Apple
df = yf.download(ticker)
print(df.head())
Lista de algunos de los tickers más utilizados en finanzas:
- Apple Inc. (AAPL)
- Amazon.com Inc. (AMZN)
- Microsoft Corporation (MSFT)
- Facebook Inc. (FB)
- Alphabet Inc. (GOOGL)
- JPMorgan Chase & Co. (JPM)
- Johnson & Johnson (JNJ)
- Berkshire Hathaway Inc. (BRK.A)
- Procter & Gamble Co. (PG)
- Exxon Mobil Corporation (XOM)
Agregando un parametro de fechas, fecha de inicio y fecha final, para consultar en ese rango y utlizando el ticker de tu preferencia.
import yfinance as yf
ticker = "AAPL"
start_date = "2022-01-01"
end_date = "2022-12-31"
df = yf.download(ticker, start=start_date, end=end_date)
permite agregar diversos parámetros al momento de obtener información sobre un ticker en particular, algunos de ellos incluyen:
- start: fecha de inicio desde donde se obtendrá la información
- end: fecha final hasta donde se obtendrá la información
- interval: intervalo de tiempo para la frecuencia de los datos (1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo)
- actions: permite obtener acciones de un ticker en lugar de información histórica
- threads: número de hilos para hacer la descarga de información más rápida
- proxy: dirección de un proxy a través del cual se obtendrá la información.
Estos son algunos de los parámetros más comunes, pero hay más disponibles en la documentación de
yfinance
Ejemplo con Amazon con intervalos de un día, desde hace 6 meses hasta el día de hoy.
import yfinance as yf
import datetime
# Obtener fecha actual y fecha hace 6 meses
now = datetime.datetime.now()
six_months_ago = now - datetime.timedelta(days=180)
# Descargar datos históricos de Amazon con un intervalo de un día
ticker = "AMZN"
df = yf.download(ticker, start=six_months_ago, end=now, interval="1d")
print(df.head())
Este es el resultado que se muestra en consola.
Open High Low Close Adj Close Volume
Date
2022-08-16 143.910004 146.570007 142.000000 144.779999 144.779999 59102900
2022-08-17 142.690002 143.380005 140.779999 142.100006 142.100006 48149800
2022-08-18 141.320007 142.770004 140.380005 142.300003 142.300003 37458700
2022-08-19 140.470001 141.110001 137.910004 138.229996 138.229996 47792800
2022-08-22 135.720001 136.320007 132.850006 133.220001 133.220001 50461500
Descargar la información en un Excel y agregar mas ticker. Necesitas instalar 2 librerías extras, que no son muy complejas.
Este fragmento de código va en el terminal.
pip install pandas
pip install openpyxl
Con esas 2 librerias instaladas podras descargar la informacion en un archivo de Excel (xlsx)
import yfinance as yf
import pandas as pd
tickers = ['AAPL', 'MSFT', 'AMZN', 'GOOG']
df = yf.download(tickers, start="2020-01-01", end="2022-01-01")
df.to_excel('tickers_data_audra.xlsx', index=True)
Esto guardará el DataFrame df
como un archivo Excel llamado «tickers_data_audra.xlsx» en el mismo directorio donde está el código.
Pruebas realizadas en Visual Studio Code.
15 comentarios
I was wondering if you ever thought of changing the structure of your website?
Its very well written; I love what youve got to say.
But maybe you could a little more in the way of
content so people could connect with it better. Youve got an awful lot of text for only
having one or two pictures. Maybe you could space it out better?
My family all the time say that I am wasting my time here at web, but
I know I am getting know-how all the time by reading such
pleasant articles or reviews.
Everyone loves what you guys are usually up too.
This type of clever work and coverage! Keep up the good works guys I’ve
added you guys to blogroll.
Hmm it appears like your blog ate my first comment (it was super long) so I
guess I’ll just sum it up what I submitted and say, I’m thoroughly enjoying your blog.
I as well am an aspiring blog blogger but I’m still new to
everything. Do you have any helpful hints for beginner blog writers?
I’d definitely appreciate it.
When some one searches for his essential thing, so he/she needs to be
available that in detail, thus that thing is maintained over here.
It’s a pity you don’t have a donate button! I’d certainly donate to this outstanding blog!
I guess for now i’ll settle for bookmarking and adding your RSS feed to my Google account.
I look forward to brand new updates and will talk about this blog with my Facebook group.
Talk soon!
Hello there, I found your web site via Google whilst looking for a
related topic, your site came up, it appears great. I’ve bookmarked
it in my google bookmarks.
Hello there, just became aware of your weblog thru Google, and located that
it’s really informative. I’m going to watch out for brussels.
I will appreciate in the event you proceed this in future.
Lots of other folks shall be benefited from your writing.
Cheers!
excellent points altogether, you just gained a emblem new reader.
What might you suggest about your publish that you simply made a few days in the past?
Any sure?
Hi there friends, how is all, and what you want to say regarding
this paragraph, in my view its in fact amazing in favor of me.
I seriously love your website.. Pleasant colors & theme.
Did you develop this site yourself? Please reply back as I’m hoping to create
my own personal website and want to find out where you got this from or exactly what the theme is named.
Thanks!
the theme is called hestia, well, it has some modifications at the code level that we are still polishing to maintain speed and performance as a whole
Because the admin of this web site is working, no hesitation very rapidly it will
be famous, due to its feature contents.
Howdy, i read your blog occasionally and i own a similar
one and i was just wondering if you get a lot of spam comments?
If so how do you stop it, any plugin or anything you can suggest?
I get so much lately it’s driving me insane so any support is very much appreciated.
write to us at contactenos@audra.company
Thank you for the auspicious writeup. It in reality used to be a entertainment account it.
Look advanced to more added agreeable from you! By the
way, how can we keep up a correspondence?