To retrieve stock data in Python, you can use various libraries and APIs that provide access to financial data. One popular library is
yfinance, which allows you to fetch historical stock data from Yahoo Finance. Here’s an example:
import yfinance as yf # Define the stock ticker symbol ticker_symbol = 'AAPL' # Example: Apple Inc. # Fetch stock data stock_data = yf.download(ticker_symbol, start='2022-01-01', end='2022-12-31') # Print the fetched stock data print(stock_data)
In the above code:
- First, you import the
- You define the stock ticker symbol of the company you want to retrieve data for. In the example, we use the ticker symbol
'AAPL', which represents Apple Inc.
yf.download()function is used to fetch the historical stock data. You pass the ticker symbol as the first argument and provide the start and end dates as strings using the
- The fetched stock data is stored in the
- Finally, you print the retrieved stock data to the console.
Make sure to adjust the
end dates according to the desired time range for fetching stock data. Additionally, you can customize the parameters of
yf.download() to retrieve specific columns or data intervals.
yfinance is just one of many options available for retrieving stock data in Python. Other popular libraries and APIs include
pandas_datareader, Alpha Vantage, and Intrinio, among others. The choice of library or API depends on your specific requirements and the