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:

Python
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:

Python
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:

  1. Apple Inc. (AAPL)
  2. Amazon.com Inc. (AMZN)
  3. Microsoft Corporation (MSFT)
  4. Facebook Inc. (FB)
  5. Alphabet Inc. (GOOGL)
  6. JPMorgan Chase & Co. (JPM)
  7. Johnson & Johnson (JNJ)
  8. Berkshire Hathaway Inc. (BRK.A)
  9. Procter & Gamble Co. (PG)
  10. 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.

    Python
    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.

    Python
    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.

    Python
    pip install pandas
    
    Python
    pip install openpyxl
    

    Con esas 2 librerias instaladas podras descargar la informacion en un archivo de Excel (xlsx)

    Python
    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.

    Categorías: finanzasPython

    13 comentarios

    sladana milojev 1000 dollar · 12 de febrero de 2023 a las 17:41

    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?

    proxy german · 13 de febrero de 2023 a las 19:21

    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.

    เว็บแทงบอล · 14 de febrero de 2023 a las 17:23

    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.

    slot deposit dana 10000 tanpa potongan · 16 de febrero de 2023 a las 14:13

    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.

    fiserv iso program · 20 de febrero de 2023 a las 05:39

    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.

    whatiscoparenting21098.dm-blog.com · 20 de febrero de 2023 a las 12:03

    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!

    AFPlus · 22 de febrero de 2023 a las 22:33

    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!

    Buy Golden Teacher Capsules · 23 de febrero de 2023 a las 00:48

    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?

    judi slot online · 24 de febrero de 2023 a las 16:14

    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.

    먹튀검증 · 26 de febrero de 2023 a las 22:10

    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!

      Ego Cañari Torres · 28 de febrero de 2023 a las 05:28

      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

    Jewel Killiney · 27 de febrero de 2023 a las 22:09

    Because the admin of this web site is working, no hesitation very rapidly it will
    be famous, due to its feature contents.

    https://www.google.com.bh · 7 de junio de 2023 a las 18:11

    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?

    Deja una respuesta

    Marcador de posición del avatar

    Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *