Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

yFinance - Eli Policape Stock Performance Data for Microsoft and SPY ETF

128 views
License: GPL3
ubuntu2204
Kernel: Python 3 (system-wide)
import yfinance as yf
import quantstats as qs
import sys sys.prefix
'C:\\ProgramData\\Anaconda3\\envs\\yfinance'

QuantStats functions

[f for f in dir(qs.reports) if f[0] != '_']
['basic', 'full', 'html', 'iDisplay', 'iHTML', 'metrics', 'plots', 'relativedelta']
[f for f in dir(qs.plots) if f[0] != '_']
['daily_returns', 'distribution', 'drawdown', 'drawdowns_periods', 'earnings', 'histogram', 'log_returns', 'monthly_heatmap', 'monthly_returns', 'plotly', 'returns', 'rolling_beta', 'rolling_sharpe', 'rolling_sortino', 'rolling_volatility', 'snapshot', 'to_plotly', 'warnings', 'yearly_returns']

QuantStats is comprised of 3 main modules:

quantstats.stats - for calculating various performance metrics, like Sharpe ratio, Win rate, Volatility, etc. quantstats.plots - for visualizing performance, drawdowns, rolling statistics, monthly returns, etc. quantstats.reports - for generating metrics reports, batch plotting, and creating tear sheets that can be saved as an HTML file.

Creating a report

You can create 7 different report tearsheets:

qs.reports.metrics(mode='basic|full", ...) - shows basic/full metrics qs.reports.plots(mode='basic|full", ...) - shows basic/full plots qs.reports.basic(...) - shows basic metrics and plots qs.reports.full(...) - shows full metrics and plots qs.reports.html(...) - generates a complete report as html
msft = yf.Ticker("MSFT") print(msft)
yfinance.Ticker object <MSFT>
#msft.info
msft.history(period="1mo")
msft.actions
msft.dividends
Series([], Name: Dividends, dtype: int64)
# extend pandas functionality with metrics, etc. qs.extend_pandas() # fetch the daily returns for a stock msft_stock = qs.utils.download_returns('msft') # show sharpe ratio qs.stats.sharpe(msft_stock) # or using extend_pandas() :) msft_stock.sharpe() print(msft_stock)
Date 1986-03-13 00:00:00-05:00 NaN 1986-03-14 00:00:00-05:00 0.035712 1986-03-17 00:00:00-05:00 0.017250 1986-03-18 00:00:00-05:00 -0.025431 1986-03-19 00:00:00-05:00 -0.017391 ... 2023-10-11 00:00:00-04:00 0.012272 2023-10-12 00:00:00-04:00 -0.003790 2023-10-13 00:00:00-04:00 -0.010358 2023-10-16 00:00:00-04:00 0.014982 2023-10-17 00:00:00-04:00 0.000872 Name: Close, Length: 9476, dtype: float64
qs.plots.daily_returns(msft_stock)
Image in a Jupyter notebook
qs.plots.yearly_returns(msft_stock)
Image in a Jupyter notebook
qs.plots.snapshot(msft_stock, title = 'Microsoft')
Image in a Jupyter notebook
If your legacy code is using pandas_datareader and you want to keep the code changes to minimum, you can simply call the override method and keep your code as it was:
qs.reports.plots(msft_stock, mode = "full")
Image in a Jupyter notebookImage in a Jupyter notebookImage in a Jupyter notebookImage in a Jupyter notebookImage in a Jupyter notebookImage in a Jupyter notebookImage in a Jupyter notebookImage in a Jupyter notebookImage in a Jupyter notebookImage in a Jupyter notebook
C:\ProgramData\Anaconda3\envs\yfinance\lib\site-packages\quantstats\stats.py:968: FutureWarning: In a future version of pandas all arguments of DataFrame.pivot will be keyword-only. returns = returns.pivot('Year', 'Month', 'Returns').fillna(0)
Image in a Jupyter notebookImage in a Jupyter notebook
from pandas_datareader import data as pdr import yfinance as yf yf.pdr_override() #<== This is the override method data = pdr.get_data_yahoo("SPY", start = "20")
from pandas_datareader import data as pdr data = pdr.get_data_yahoo("SPY") data
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In [17], line 2 1 from pandas_datareader import data as pdr ----> 2 data = pdr.get_data_yahoo("SPY") 3 data
File C:NaN, in get_data_yahoo(*args, **kwargs) 79 def get_data_yahoo(*args, **kwargs): ---> 80 return YahooDailyReader(*args, **kwargs).read()
File C:NaN, in _DailyBaseReader.read(self) 251 # If a single symbol, (e.g., 'GOOG') 252 if isinstance(self.symbols, (string_types, int)): --> 253 df = self._read_one_data(self.url, params=self._get_params(self.symbols)) 254 # Or multiple symbols, (e.g., ['GOOG', 'AAPL', 'MSFT']) 255 elif isinstance(self.symbols, DataFrame):
File C:NaN, in YahooDailyReader._read_one_data(self, url, params) 151 try: 152 j = json.loads(re.search(ptrn, resp.text, re.DOTALL).group(1)) --> 153 data = j["context"]["dispatcher"]["stores"]["HistoricalPriceStore"] 154 except KeyError: 155 msg = "No data fetched for symbol {} using {}"
TypeError: string indices must be integers
spy = yf.Ticker("SPY") print(spy)
yfinance.Ticker object <SPY>
#spy.info

# Data period parameters 1d, 5d, 1mo, 3mo, 6mo, 1y,2y,5y,10y.ytd,max spy.history(period = "1mo" )
# extend pandas functionality with metrics, etc. qs.extend_pandas() # fetch the daily returns for a stock spy_stock = qs.utils.download_returns('SPY') # show sharpe ratio qs.stats.sharpe(spy_stock) # or using extend_pandas() :) spy_stock.sharpe() print(spy_stock)
Date 1993-01-29 00:00:00-05:00 NaN 1993-02-01 00:00:00-05:00 0.007113 1993-02-02 00:00:00-05:00 0.002119 1993-02-03 00:00:00-05:00 0.010570 1993-02-04 00:00:00-05:00 0.004185 ... 2023-10-10 00:00:00-04:00 0.005205 2023-10-11 00:00:00-04:00 0.004096 2023-10-12 00:00:00-04:00 -0.006096 2023-10-13 00:00:00-04:00 -0.004981 2023-10-16 00:00:00-04:00 0.010521 Name: Close, Length: 7734, dtype: float64
qs.stats.conditional_value_at_risk(spy_stock)
-0.02894721345003485
qs.plots.daily_returns(spy_stock)
Image in a Jupyter notebook
qs.plots.yearly_returns(spy_stock)
Image in a Jupyter notebook
qs.plots.snapshot(spy_stock, title = 'S&P 500 ETF')
Image in a Jupyter notebook
qs.reports.plots(spy_stock, mode = "full")
Image in a Jupyter notebookImage in a Jupyter notebookImage in a Jupyter notebookImage in a Jupyter notebookImage in a Jupyter notebookImage in a Jupyter notebookImage in a Jupyter notebookImage in a Jupyter notebookImage in a Jupyter notebookImage in a Jupyter notebook
C:\ProgramData\Anaconda3\envs\yfinance\lib\site-packages\quantstats\stats.py:968: FutureWarning: In a future version of pandas all arguments of DataFrame.pivot will be keyword-only. returns = returns.pivot('Year', 'Month', 'Returns').fillna(0)
Image in a Jupyter notebookImage in a Jupyter notebook
qs.stats.compare(spy_stock,msft_stock)
qs.stats.win_loss_ratio(spy_stock)
0.944087854833915
qs.stats.win_loss_ratio(msft_stock)
1.0925793813066438