yfinace-python

yfinance python

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.

Tabla de Contenido

Contenido Adicional

text
Javascript
Ego Cañari Torres

Estructuras de Datos y Funciones con Javascript

¡Bienvenidos al fascinante mundo de las estructuras de datos y funciones en Javascript! Si eres un desarrollador web en ciernes o simplemente alguien curioso por aprender más sobre este lenguaje de programación, estás en el lugar correcto. ¿Qué son las

Leer más »
CIEN AÑOS DE SOLEDAD
Literatura
audra

CIEN AÑOS DE SOLEDAD

autor de cien años de soledad Gabriel García Márquez Gabriel García Márquez, también conocido como «Gabo», fue un escritor y periodista colombiano. Es considerado uno de los autores más importantes del siglo XX y es conocido por su estilo literario

Leer más »
text
Desarrollo web
audra

DOM y Eventos con JavaScript

El fascinante mundo del DOM y los eventos en JavaScript Si eres un desarrollador web, es muy probable que hayas escuchado hablar del DOM y los eventos en JavaScript. Pero, ¿qué son realmente y por qué son tan importantes en

Leer más »
text
Desarrollo web
Ego Cañari Torres

Fundamentos básicos de Javascript

En este artículo, vamos a sumergirnos en los fundamentos básicos de Javascript. Si eres nuevo en la programación o simplemente quieres refrescar tus conocimientos, estás en el lugar correcto. ¿Qué es Javascript? Javascript es un lenguaje de programación que se

Leer más »
Tipos de variables
Programacion
Ego Cañari Torres

Tipos de variables

JavaScript tiene los siguientes tipos de variables: Ejemplo: Java tiene los siguientes tipos de variables: Ejemplo: Además, en Java existen los arreglos y los objetos, los cuales pueden almacenar múltiples valores y tienen características específicas. Ejemplo: En C#, los tipos

Leer más »
programación en Python con líneas de código y sintaxis destacada
Programacion
Ego Cañari Torres

Python

que es python python online Python es un lenguaje de programación de alto nivel, interpretado, dinámico y multiplataforma. Fue creado por Guido van Rossum en 1991 y es ampliamente utilizado por su sintaxis clara y legible, así como por su

Leer más »

15 respuestas a “yfinance python”

  1. 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?

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

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

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

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

  6. 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!

  7. AFPlus dice:

    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!

  8. 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?

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

  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!

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

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

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

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