I have this code that works when manually entering a start date and an end date:
import datetime as dt
from datetime import date
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader as web
today = date.today()
style.use("ggplot")
start = dt.datetime(2020,1,1)
end = today
df = web.get_data_yahoo("TSLA", start, end)
df["Adj Close"].plot()
plt.xlabel("Date")
plt.ylabel("Price $")
plt.title("TSLA Stock Price ", )
plt.show()
It works when plotting the graph, but I want the start and end date to show up on the title as well. Is there anyway that I can import the "start" and "end" variables after "TSLA Stock Price "?
I think you can just use an f string in the plt.title().
plt.title(f"TSLA Stock Price {start.strftime('%x')} to {end.strftime('%x')}")
This code results in the title being formated like mm/dd/yy to mm/dd/yy
Related
My problem is when I plot the users joining by day the advance year appear, it should not have year 2023. I tried to search it into my csv file and there is no row holding the value of 2023.
data = pd.read_csv('users-current.csv')
#transform datetime to date
data['dateCreated'] = pd.to_datetime(data['created_on']).dt.date
#date Count Registered
dataCreated = data.groupby('dateCreated').size()
#dataCreatedArray = np.array([dataCreated], dtype = object)
dataCreated.head(50)
dataCreated.plot().invert_xaxis()
plt.title('Users Joining in a Day',pad=20, fontdict={'fontsize':24})
plt.show()
the output:
column in my csv used below:
This is because the range of x is automatically generated. Instead, you can explicitly limit a range of x using plt.xlim(), as follows:
import pandas as pd
import matplotlib.pyplot as plt
import datetime
data = pd.read_csv('users-current.csv')
#transform datetime to date
data['dateCreated'] = pd.to_datetime(data['created_on']).dt.date
#date Count Registered
dataCreated = data.groupby('dateCreated').size()
#dataCreatedArray = np.array([dataCreated], dtype = object)
dataCreated.head(50)
dataCreated.plot().invert_xaxis()
# import datetime, and use this code to set a period as you want.
plt.xlim([datetime.date(2021, 1, 1), datetime.date(2022, 12, 31)])
plt.title('Users Joining in a Day', pad=20, fontdict={'fontsize':24})
plt.show()
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 am using the following code to generate data series :-
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import calendar
from datetime import datetime
from itertools import cycle, islice
month_input = "Jan"
year_input = 2018
month_start= str(month_input)
year_start = int(year_input)
start = pd.to_datetime(f'{month_start}{year_start}', format='%b%Y')
end = pd.to_datetime(f'{month_input}{year_start + 1}', format='%b%Y') - pd.Timedelta('1d') # Generating Date Range for an Year
daily_series_cal = pd.DataFrame({'Date': pd.date_range(start, end)})
When I am trying to do:
print(daily_series_cal["Date"][0])
It is giving as output as :-
2018-01-01 00:00:00
How can I change the format of whole column to 01/01/2018 ie mm/dd/yyyy?
It is possible by DatetimeIndex.strftime, but lost datetimes and get strings:
daily_series_cal = pd.DataFrame({'Date': pd.date_range(start, end).strftime('%m/%d/%Y')})
I try to write a small "program" that gets the stock prices from Quandl.
The user should be able to enter a startring date (yyyymmdd) and the the program should then get the data from that date and forward to current date.
import datetime as dt
import pandas_datareader as web
ticker = 'TSLA'
# Time variables for current and starting date as integers
current_year = int(dt.datetime.now().strftime("%Y"))
current_month = int(dt.datetime.now().strftime("%m"))
current_day = int(dt.datetime.now().strftime("%d"))
start_date = str(input("Starting date (yyyymmdd): "))
start_year = int(start_date[:4])
start_month = int(start_date[5:6])
start_day = int(start_date[7:8])
# Defines the total period
start = dt.datetime(start_year, start_month, start_day) # Starting date, yyyy mm dd
end = dt.datetime(current_year, current_month, current_day) # End date, yyyy mm dd
# Gets the data from start to end date for the stock definded as 'Ticker'
df = web.get_data_quandl(ticker, start, end)
print(start)
print(end)
print(df)
My problem is that I cannot seem to get any data newer than 2018-03-27.
The WIKI database is indeed no longer updated or supported starting from March 27, 2018. The closest alternative on Quandl is EOD, which is a value-priced end-of-day US stock price data feed.