0 ratings0% found this document useful (0 votes) 25 views6 pagesPython '
cash python test analysis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
3115124, 5:39 PM
Welcome to Colab!
(New) Try the Gemini API
+ Generate a Gemini API key
‘+ Talk to Gemini with the Speech-to-Text API
‘+ Gemini API: Quickstart with Python
+ Gemini API code sample
‘+ Compare Gemini with ChatGPT
+ More notebooks
Welcome To Colaboratory - Colaboratory
If youre already familiar with Colab, check out this video to learn about interactive tables, the executed code history view,
and the command palette,
hi
Nareerror
-ipython-inut-1-sscaszase3e4> in | Thi
Naretrror
Traceback (most recent call last)
BO
ane "hi' is not defined
Next steps: Explain error
Ipip install yi
Requirement
Requirement
Requirement
Requirement
Requirement
Requirement
Requirement
Requirement
Requirement
Requirement
Requirement
Requirement
Requirement
Requirement
Requirenent
Requirenent
Requirenent
Requirement
Requirement
Requirement
already
already
already
already
already
already
alreasy
alreasy
already
already
alreacy
already
alreacy
alreacy
alreacy
alrescy
alrescy
already
already
already
satisfied
satisfied:
satisfied
satisfied
satisfied:
satisfied
sfied
sfied
satisfied:
satisfied
satisfied
satisfied
sfied:
satisfied:
: yfinance in /usr/local/lib/python3.10/dist-packages (0.2.37)
satisfied:
pandas>=1.3. in /usr/local/1ib/python3.10/dist-packages (from yfinance) (2
hhunpy>=1.16.5 In /usr/local/1ib/python3.10/dist-packages (from yfinance) (2
requests>-2.31 in /usr/lecal/1ib/python3.10/dist-packages (from yfinance) (2.
satisfied:
satisfied:
pultitasking>=0.0.7 in /usr/local/Lib/python3.10/dist-packages (from yFinance
Lxm>e4.9.1 in /use/local/1ib/python3.1/dist-packages (from yfinance) (4.9.4
appdirs>=1.4.4 in /usr/local/1ib/python3.10/dist-packages (from yfinance) (1
pytz>=2022.5 in /usr/local/1ib/python3.10/dist-packages (From yfinance) (2023
frozendict>=2.3.4 in /usr/local/Lib/python3.10/dist-packages (Fro= yfinance)
peowee>=3.16.2 in /usr/local/Lib/python3.10/dist-packages (from yfinance) (3
beautifulsoup4=4.11.1 in /usr/local/1ib/python3. 10/¢ist-packages (from yfina
hem151ib>=1.1 In /usr/local/1ib/python3.10/éist-packages (from yfinance) (1.
soupsieve>t.2 in /usr/local/1i6/python3.10/éist-packages (from beautiful soupa
sb0=1.9 in /usr/local/lib/python3.18/dist-packages (From heml5]ib>=1.1->yFi
webencodings in /usr/local/1i6/python3.10/¢ist-packages (from htm151ib>=1.1->
python-dateutil>=2.8.1 in /usr/local/1ib/python3.10/¢ist-packages (from pands
charset-normalizercé,>=2 in /usr/local/1ib/python3.10/dist-packages (From rec
idnacd,>=2.5 in /usr/local/1ib/python3.10/¢ist-packages (From requests>=2.31
urlLib3<3, >=1.21.1 in /usr/local/Lib/python3.1@/dist-packages (Fron requests
certifir=2017.4.17 in /usr/local/Lib/python3. 1e/dist-packages (Fron requests:
‘wae notes: activate dependencies/oackages
ntps:ifcola. research google.comiscrolTo=cDdVxkZ0-ryxBprintMode=true 1683115124, 5:39PM Welcome To Colaboratory - Colaboratory
import pandas_datareader.data as web
import yFinance as yf
Fron datetine import datetine
yf-pdr_override()
import pandas as pa
import natplotlib.pyplot as plt
Fron natplotlib import style
import: numpy’as np
What is Colab?
Colab, or *Colaboratory’, allows you to write and execute Python in your browser, with
‘+ Zero configuration required
+ Access to GPUs free of charge
+ Easy sharing
Whether you're a student, a data scientist or an Al researcher, Colab can make your work easier. Watch Introduction to
Golab to learn more, or just get started below!
wae User Anputs.
startdate = datetine(2022,1,1)
fatetime(2023,10,31)
tickers = ['GILLETTE.NS", "APARINDS.NS' , "COAL
nusber_of portfolios = 25008
isk_free = 0.070597
enddate =
(DTA.NS", “APOLLOTYRE.NS' , ‘NH.NS"]
188 Create an enpty table space for Filling the data
returns = pd.dataFrane()
¥# Create a looping function that
8 (2) Downloads the stock price data for all the tickers defined above
88 (2) compute the percentage change (returns)
for ticker in thekers:
data = web.get_data_yahoo(ticker, start = startdate, end = enddate)
data = pd.DataFrace(data)
data[ticker] = data[ ‘Adj Close’]-pct_change()
Af returns.enpty:
returns = datal(ticker)]
else:
returns = returns.join(data[[ticker]], how = ‘outer’)
[sererseseseeseeneeeneggurrestereeneeesenereeees] 2 of 1 completed
[setersonesecsueneneseqggexeeseesuevenesenereoees] 2 of 1 completed
[ttetssaseceseseneseqggeyteseeesereseseeeesaes] 1 of 1 completed
[ettetsesssecesessneseqggeyreseststssneseeseaseas] 1 of 1 completed
[nteeteenssecensseseneqgguyresscestvesenenseeoees] 1 of 1 completed
#8 drop the missing value rows
returns = returns. dropna()
ntps:ifcola. research google.comitscrolTo=cDdVxkZ0-nyx8printMode=true 2163115124, 5:39PM Welcome To Colaboratory - Colaboratory
GILLETTE.NS APARINOS.NS COALINDIA.NS APOLLOTYRE.NS MNS
Date o
2022-01-04 0.004408 0.000785 0.074810 0.021277 -0,008193
2022-01-05 0.008153 0.011448 0.004575 0.008422 0.028629
2022-01-06 0.003103 0.024418 0.006187 0.004396 -0.026312
2022-01-07 0.000075 o.008140 0.14872 0.019694 0.016496
2022-01-10 0.000905 0.000384 0.02893 0.002146 0.012781
Next steps: Generate code with returns € View recommended plots
Y Generate Using dataframe: returns suogest a plot Q | Close
Generate is available fora limited time for unsubscribed users. Upgrade to Colab Pro x
#8 Create some variabls spaces (to be computed)
portfolio_returns = []
portfolio_risks = (]
sharpe_ratios = []
portfolio weights = []
‘8 conpute the variables required for building the portfolio
for portfolio in range(nurber_of portfolios
weights = np.randos.randos_sanple(len(tickers)) ## Generating randos portfolio weights
weights = np.round((weights / np.sum(weights)),3) ## rounding off the randon weights upto 3 decinal poi
portfolio_weights.apsenc(weights) iit add the weights in the "portfolioweights” space created earlier
annualised_return = np.sun(returns.mean() weights)*252 #88 computing the annualised portfolio return
portfolio_retumns.append(annualised_return) ### add the ann returns in the “portfolig_retumns” space crez
covariance matrix = returns.cov()*252 ## build the covariance matrix
portfolio_stdev = np.sqrt(np.dot (weights. np-cot (covariance matrix, weights))) ## computing the portfolio
portfolio_risks.append(portfoli_stdev) ##it add the portfolio stdev in the “portfolio risks” space createc
sharpe_ratio = (annualised_return - risk free) / portfolio_stdev ### compute the sharpe ratio
sharpe_ratios.append(sharpe_ratio) iif add the sharpe ratio in the “sharpe_ratios” space created earlier
portfolio returns = np.array(portfolie_returns) ### arrange all the portfolio returns in ene coluan
portfoliorisks = np.array(portfolio risks) #88 arrange all the portfolio risk in one colun
sharpe_ratios = np.array(sharpe_ratios) Wf arrange all the sharpe ratios in one colusn
portfolio_metrics = [portfolio_retuens, portfolio_risks, sharpe_ratios, portfolio.weights] s## create a new va
portfolio df = pd.Datafrane(portfolio_netrics).T ‘i convert the metrics data into a datafrane
portfolio df.colunns = [*Return’,"Risk*, ‘Sharpe’, ‘Weights'] ### renaming the columns in the matrics datafrane
print(portfolioéf) ## output
Return Risk Sharpe Weights
° 0.60985 0.252447 2.136109 [0.025, 0.313, 0.015, 8.446, 0.202]
1 0.300256 0.180822 1.270084 [0.198, 2.015, 0.023, 0.355, 2.41]
2 0.220573 0.153834 0.974923 [0.583, 0.011, 8.065, 0.058, 0.283]
3 0.540138 0.206104 2.278177 [0.053, 0.148, 0.454, 8.26, 0.085]
4 0.529568 0.19572 2.345035 [8.151, 8.192, 8.297, 0.277, 8.084]
24995 0.408673 0.175639 1.921419 [0.243, 0.107, 6.163, 0.385, 8.126]
24996 0.552796 @.213081 2.262989 (8,223, @.256, 0.182, 6.328, 0.61]
24997 0.653715 @.254662 2.289774 [8.178, 0.374, 0.113, 8.317, 8.018]
24998 0.615219 0.22758 2.393161 [2.136, 0.333, 6.158, 2.628, 0.345]
24999 0.61355 0.227217 2.390018 [@.172, 0.313, @.193, 2.267, 0.955]
[25000 rows x 4 coluens]
snax_sharpe = portfolie_df.iloc[portfolio_4f[ ’Sharpe’ J astype( Float) idxmax() ]
nax_sharpe = portfolio_dF.iloc[portfolio_éf[ Sharpe" ].astype( float) .iéxmax() ]
nriat('Hiehect Sharne: Part falin:*)
ntps:ifcola. research google.comitscrolTo=cDdVxkZ0-ryx8printMode=true 363115124, 5:39 PM Welcome To Colaboratory - Colaboratory
print(max_sharpe)
print(tickers)
print("")
Highest Sharpe Portfolio:
Return 704151
Risk 2.246479
Sharpe 2.57a414
Weights (0.005, @.332, 0.441, 0.074, @.148)
Nave: 11769, dtype: object
['GILLETTE.NS", 'APARINOS.NS", “COALINDIA.NS', “APOLLOTYRE.NS', 'NH.NS"]
v Getting started
‘The document you are reading is nota static web page, but an interactive environment called a Colab notebook that lets
you write and execute code,
For example, here is a code cell with a short Python script that computes a value, stores it in a variable, and prints the
result:
seconds_in_a_day = 24 * 68 * 60
seconds_in_a day
6800
To execute the code in the above cell, select it with a click and then either press the play button to the left of the code, or
use the keyboard shortcut "Command/Ctrl+Enter’, To edit the code, just click the cell and start editing,
Variables that you define in one cell can later be used in other cells:
seconds_in +
seconds_in_s
week = 7 * seconds_in,
day
604800
Colab notebooks allow you to combine executable code and rich text in a single document, along with i
ages, HTML,
LaTeX and more. When you create your own Colab notebooks, they are stored in your Google Drive account. You can
easily share your Colab notebooks with co-workers or friends, allowing them to comment on your notebooks or even edit
them. To learn more, see Overview of Colab. To create a new Colab notebook you can use the File menu above, or use the
following link create a new Colab notebook.
Colab notebooks are Jupyter notebooks that are hosted by Colab, To learn more about the Jupyter project, see
jupytercors,
v Data science
With Colab you can harness the full power of popular Python libraries to analyze and visualize data. The code cell below
Uses numpy to generate some random data, and uses matplotlb to visualize it. To edit the code, just click the cell and
start editing
ntpsifcolab.research.google.comitscrolTo=cDdVxkZ0-nyxSprintMode=true 483115124, 5:39PM Welcome Ta Colaboratory -Colaboratory
import numpy as np
import TPython.display as display
fron matplotlib import pyplot as plt
import io
import base64
ys = 286 + np.randon.randn(160)
x= [x for x in range(len(ys)))
Fig = plt-figure(Figsize=(4, 3), facecolor='w')
plt.plot(x, ys, '=")
plt.fill_between(x, ys, 195, where=(ys > 195), facecolor='g', alpha-0.6)
plt.title("Sarple Visualization", fontsize=13)
data = io.Bytesto()
pit. savefig(data)
nage = F'data:image/png;base64, (base6a. bsencode (data. getvalue()) .decode()}"
alt = "Sample Visualization"
display ci splay (display .Markdown(F™"* |[{a1t}] ({image))"*"))
plt.close(ig)
‘Sample Visualization
202
201
200
199
198
197
196
195,
You can import your own data into Colab notebooks from your Google Drive account, including from spreadsheets, as well
as from Github and many other sources, To learn more about importing data, and how Colab can be used for data
‘science, see the links below under Working with Data,
v Machine learning
With Colab you can import an image dataset, train an image classifier on it, and evaluate the model, al in just a few lines
of code. Colab notebooks execute code on Google's cloud servers, meaning you can leverage the power of Google.
hardware, including GPUs and TPUs, regardless of the power of your machine. All you need is a browser.
Colab is used extensively in the machine learning community with applications including:
+ Getting started with TensorFlow
Developing and training neural networks
Experimenting with TPUs
Disseminating Al research
+ Creating tutorials:
‘To see sample Colab notebooks that demonstrate machine learning applications, see the machine learning examples
below.
ntpsifcolab.research.google.comitscrolTo=cDdVxkZ0-nyxSprintMode=true 5163115124, 5:39PM Welcome To Colaboratory - Colaboratory
v More Resources
Working with Notebooks in Colab
+ Overview of Colaboratory
© Guide to Markdown
“Importing libraries and installing dependencies
‘Saving and loading notebooks in GitHub
“Interactive forms
“Interactive widgets
Working with Data
+ Loading data: Drive, Sheets, and Google Cloud Storage.
+ Charts: visualizing data
Getting started with BigQuery
Machine Learning Crash Course
‘These are a few of the notebooks from Google's online Machine Learning course. See the full course website for more.
+ Intro to Pandas DataFrame.
+ Linear regression with tf.keras using synthetic data
Using Accelerated Hardware
+ TensorFlow with GPUs
Featured examples
+ NeMo Voice sw
computer generated one,
p: Use Nvidia's NeMo conversational Al Toolkit to swap a voice in an audio fragment with a
‘+ Retraining an image Classifier: Build a Keras model on top of a pre-trained image classifier to distinguish flowers,
+ Text Classification: Classify IMDB movie reviews as either positive or negative.
‘+ Style Transfer: Use deep learning to transfer style between images.
‘+ Multilingual Universal Sentence Encoder Q&A: Use a machine learning model to answer questions from the SQUAD
dataset
‘+ Video Interpolation: Predict what happened in a video between the first and the last frame.
Could not connect tothe reCAPTCHA service. Please check your internet connection and reload to get a reCAPTCHA challenge,
ntpsifcolab.research.google.comitscrolTo=cDdVxkZ0-nyxSprintMode=true 86 |