I am attempting to download stock option data via the library yfinance for a list of stock tickers represented by the variable: "tickers" for options with an expiration date represented by: "exp_date".
Frankly, I don't even know if my loop/append is correct as I am new to coding, but I am getting the error message:
"AttributeError: 'str' object has no attribute 'option_chain'".
I only get the error message if I try to do this loop for all stock tickers. If I manually input a single ticker and manually input the expiration date instead of using the "exp_date" variable, it works perfectly.
import yfinance as yf
import pandas as pd
import datetime
# Get Friday of current week for expiration date
current_time = datetime.datetime.now()
exp_date = (current_time.date() - datetime.timedelta(days=current_time.weekday()) + datetime.timedelta(days=4))
# Get options data and put in dataframe
opt_df = pd.DataFrame()
for ticker in tickers:
opt = ticker.option_chain(exp_date)
opt_df.pd.Dataframe.append(opt)
ticker is the ticker symbol, not the ticker information returned by yfinance.
for symbol in tickers:
ticker = yf.Ticker(symbol)
opt = ticker.option_chain(exp_date)
opt_df.pd.Dataframe.append(opt)
Related
I'm trying to get a quarter end date based on today's date, but I wanted to strip the time first. If I do that, the below code throws me an error on the last line AttributeError: 'datetime.datetime' object has no attribute 'to_period'
import pandas as pd
import datetime
today_datetime = datetime.date.today().strftime('%Y-%m-%d')
today_date = datetime.datetime.strptime(today_datetime, '%Y-%m-%d')
df['Qend'] = today_date.to_period("Q").end_time
Could you advise me, how to improve it to get the Quarter end of today's date without time, please?
Considering #Ezer-k comment, below is code, which insert quarter end date based on current date with stripped time.
today_datetime = pd.Timestamp.now()
# get month end stripped time
df['Qend'] = today_datetime.to_period('M').end_time
df['Qend'] = df['Qend'].dt.strftime('%Y-%m-%d')
I'm sure there might be better way also, but just to return with correct answer.
I grab data with yfinance package. I convert it into a panda dataframe.
However, I am unable to save the dataframe to excel file.
ValueError: Excel does not support datetimes with timezones. Please
ensure that datetimes are timezone unaware before writing to Excel.
This is how the dataframe looks like. It should be 8 columns. Spyder says it has 7 columns.
Below is my codes:
import yfinance as yf
import pandas as pd
stock = yf.Ticker("BABA")
# get stock info
stock.info
# get historical market data
hist = stock.history(start="2021-03-25",end="2021-05-20",interval="15m")
hist = pd.DataFrame(hist)
# pd.to_datetime(hist['Datetime'])
# hist['Datetime'].dt.tz_localize(None)
hist.to_excel(excel_writer= "D:/data/python projects/stock_BABA2.xlsx")
You can remove the time zone information of DatetimeIndex using DatetimeIndex.tz_localize() , as follows:
hist.index = hist.index.tz_localize(None)
You can convert time zones using tz_convert(), in your situation it should work with:
hist.index = hist.index.tz_convert(None)
import yfinance as yf
from datetime import datetime, timedelta
from pandas import DataFrame
startDate = datetime.now ()- timedelta(100)
endday = datetime.now()-timedelta(-1)
stockNo = xxx # xxx1, xxx2, ...stock code
start = startDate, end = endday
stock = yf.Ticker(stockNo)
stock_df = pd.DataFrame(stock.history(start = startDate, end = endday ))
yfinance responses as follow, how can i save this information as list or dataframe
xxx1: No data found, symbol may be delisted
xxx2: No data found, symbol may be delisted
This is a really late answer, but considering there are none yet:
import yfinance as yf
import pandas as pd
ticker = "ENTER_YOUR_TICKER_HERE"
yahootickerdata = yf.Ticker(f"{ticker}")
# this is already a dataframe so no need to read it in as one
# but this depends on what you're requesting from yfinance
earnings = yahootickerdata.earnings
# save to CSV
earnings.to_csv(f"data/{ticker}-yahoo-earnings.csv")
# and next time you can just load the CSV
df = pd.read_csv(f"data/{ticker}-yahoo-earnings.csv")
I have searched for this topic and I found some packages that are useful. All what I am trying to get is the last price of any specific ticker such as "MSFT"
Here's a code that I found and it is good
import pandas_datareader as pdr
from datetime import datetime
ibm = pdr.get_data_yahoo(symbols='MSFT', start=datetime(2021, 3, 1), end=datetime(2021, 3, 12))
print(ibm['Adj Close'])
This works for range of dates. How can I get the last price only without hard-coding the start date or end date?
Just use tail keyword.
from datetime import datetime, date
ibm = pdr.get_data_yahoo(symbols='MSFT', start = date.today(), end = date.today())
print(ibm['Adj Close'].tail(1))
I'm using Metatrader5 module for python and this is my code
'''
#python
from datetime import datetime
import MetaTrader5 as mt5
# display data on the MetaTrader 5 package
print("MetaTrader5 package author: ", mt5.__author__)
print("MetaTrader5 package version: ", mt5.__version__)
# import the 'pandas' module for displaying data obtained in the tabular form
import pandas as pd
pd.set_option('display.max_columns', 500) # number of columns to be displayed
pd.set_option('display.width', 1500) # max table width to display
# import pytz module for working with time zone
import pytz
# establish connection to MetaTrader 5 terminal
if not mt5.initialize():
print("initialize() failed")
mt5.shutdown()
# set time zone to UTC
timezone = pytz.timezone("Etc/UTC")
# create 'datetime' object in UTC time zone to avoid the implementation of a local time zone offset
utc_from = datetime(2020, 1, 10, tzinfo=timezone)
# get 10 EURUSD H4 bars starting from 01.10.2020 in UTC time zone
rates = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_H4, utc_from, 10)
# shut down connection to the MetaTrader 5 terminal
mt5.shutdown()
# display each element of obtained data in a new line
print("Display obtained data 'as is'")
for rate in rates:
print(rate)
# create DataFrame out of the obtained data
rates_frame = pd.DataFrame(rates)
# convert time in seconds into the datetime format
rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s')
# display data
print("\nDisplay dataframe with data")
print(rates_frame)
'''
My question is s there any easy way to calculate stock indicators like RSI and MFI and other indicators using this module?
No. Its possible if using other modules though.
Here is a method using another that could achieve it:
https://www.mql5.com/en/articles/5691
Alternatively, you can pull the data from MT5 and throw it in TA-lib for analysis. TA-lib consumes the data and provides values for the indicators outside MT5.
Check out TA-lib: https://mrjbq7.github.io/ta-lib/
Since your data will be in a pandas df, I would check out pandas-ta, https://pypi.org/project/pandas-ta, all technical indicators. Also, thats a lot of code to pull your data, this is what I use;
import MetaTrader5 as mt
import pandas as pd
from datetime import datetime
mt.initialize()
df = pd.DataFrame( mt.copy_rates_range( '#MNQ', #micro nasd100
mt.TIMEFRAME_D1,
datetime( 2022, 1, 1 ),
datetime.now() ) )
# manipulate as you please
mt.shutdown()
and i didnt like the GMT+2 timezone used by metatrader at first but Ive found its easier to get used to it as the date change is timed to the daily futures market open at 5pm central, which in GMT+2 is day+1 00:00.