# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # Cryptocurrency Market Analysis
# *Based off my stock market analysis of tech giants, located [here](https://github.com/melvfernandez/data_science_portfolio/blob/master/Stock%20Market%20Analysis%20for%20Tech%20Stocks.ipynb).*
#
# ***
#
# In this project, we will analyze data from Yahoo Finance of three popular cryptocurrencies to date.
#
# We will use Pandas to extract and analyze the information, visualize it, and analyze risks based on it's performance history.
#
# Here are questions we will try to answer:
# -  What was the change of price over time?
# -  What was the daily return on average of a stock?
# -  What was the moving average of various stock?
# -  What is the correlation between daily returns of different stock?
# -  How much value do we put at risk by investing in a stock?
# -  How can we attempt to predict future stock behavior?

# +
#python data analysis imports
import pandas as pd
from pandas import Series, DataFrame
import numpy as np

#visualization imports
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('whitegrid')
# %matplotlib inline

#grab data imports
import pandas_datareader.data as pdr
from datetime import datetime
# -

#We are going to analyze the top cryptocurrencies.
cc_list = ['BTC-USD','ETH-USD','LTC-USD']

# +
#Setting the end date to today
end = datetime.today()

#Start date set to one year back
start = datetime(end.year-1,end.month,end.day)
# -

#using yahoo finance to grab cryptocurrency data
BTC = pdr.DataReader('BTC-USD','yahoo',start,end)
ETH = pdr.DataReader('ETH-USD','yahoo',start,end)
LTC = pdr.DataReader('LTC-USD','yahoo',start,end)

#STATISTICS FOR BTC'S STOCK
BTC.describe()

BTC.head()

#INFORMATION ABOUT BTC DATAFRAME
BTC.info()

# ***

# ## What is the change in stock's price over time?

#Using pandas we canplot the stocks adjusted closing price
BTC['Adj Close'].plot(legend = True, figsize=(12,5))

# Within the year, we can see the value of BTC almost reach up to 20K.

#Using pandas once more to plot the total volume being traded over time
BTC['Volume'].plot(legend=True,figsize=(12,5))

# ***

# ## What was the moving average of the stocks?

# +
#using pandas we will create moving averages for 10, 20 and 50 day periods of time

ma_days = [10,20,50]

for ma in ma_days:
    column_name = "MA %s days" %(str(ma))
    BTC[column_name] = BTC['Adj Close'].rolling(window=ma,center=False).mean()
# -

BTC.tail()

BTC[['Adj Close','MA 10 days','MA 20 days','MA 50 days']].plot(legend=True,figsize=(12,5))

# Genereally some casual dips in the past month but overall an upward trend.

# ***

# ## What was the daily return average of a stock?

# +
#In order calculate daily return we can use the percentage change of the adjusted closing price

BTC['Daily Return'] = BTC['Adj Close'].pct_change()

BTC['Daily Return'].tail()
# -

#Let us now plot the daily return
BTC['Daily Return'].plot(marker='.',legend=True,figsize=(12,5))

# Positive daily returns seem to be more frequent than negative returns.

# ## What was the correlation between daily returns of different stocks?

# +
#Let's read the 'Adj Close' column from all the cryptocurrencies giants

close_df = pdr.DataReader(cc_list,'yahoo',start,end)['Adj Close']
# -

close_df.tail()

#Let's explore the returns again using the percentage change from the adj close.
returns_df = close_df.pct_change()
returns_df.plot(marker='.',legend=True,figsize=(12,5))

# This plot is difficult to understand, let's use a jointplot instead.

returns_df.tail()

#We can now try to find the correlation between Bitcoin and Ethreum
sns.jointplot('BTC-USD','ETH-USD',returns_df,kind='scatter')

# There seems to be a minor positive correlation between the two, the pearsonr correlation coefficient value of 0.4 agrees with that statement.

# Let's use a pairplot to visualize all the tech giants in one view.

sns.pairplot(returns_df.dropna(),diag_kind='kde')

# Quick and easy way to view correlations but let's use a correlation plot to see the actual numbers.

# +
corr = returns_df.dropna().corr()

sns.heatmap(corr,
            xticklabels=corr.columns,
            yticklabels=corr.columns, 
            annot=True,
            cmap='Blues')

#the darker the shade the higher the correlation
# -

rets = returns_df.dropna()

# +
plt.figure(figsize=(8,5))

plt.scatter(rets.mean(),rets.std(),s=25)

plt.xlabel('Expected Return')
plt.ylabel('Risk')

#For adding annotatios in the scatterplot
for label,x,y in zip(rets.columns,rets.mean(),rets.std()):
    plt.annotate(
        label,
        xy=(x,y),xytext=(-120,20),
        textcoords = 'offset points', 
        ha = 'right', 
        va = 'bottom',
        arrowprops = dict(arrowstyle='->'))
# -

# As of January 12, the current trend for cryptocurrencies seem to output a negative return. We want a crypto with high return and low risk.

rets.head()

qt = rets['BTC-USD'].quantile(0.05)

qt_pct = abs(rets['BTC-USD'].quantile(0.05))*100
print(qt_pct)

print("The 0.05 empirical quantile of daily returns is at {0:.2f}. This means that with 95% confidence, the worst daily loss will not exceed {0:.2f}% (of the investment).".format(qt,qt_pct))

# ## How can we predict future behavior?

days = 365
dt = 1/365
mu = rets.mean()['BTC-USD']
sigma = rets.std()['BTC-USD']


#Function takes in stock price, number of days to run, mean and standard deviation values
def stock_monte_carlo(start_price,days,mu,sigma):
    
    price = np.zeros(days)
    price[0] = start_price
    
    shock = np.zeros(days)
    drift = np.zeros(days)
    
    for x in range(1,days):
        
        #Shock and drift formulas taken from the Monte Carlo formula
        shock[x] = np.random.normal(loc=mu*dt,scale=sigma*np.sqrt(dt))
        
        drift[x] = mu * dt
        
        #New price = Old price + Old price*(shock+drift)
        price[x] = price[x-1] + (price[x-1] * (drift[x]+shock[x]))
        
    return price



BTC.tail()

# +
start_price = 13841.190 #Taken from above

for run in range(100):
    plt.plot(stock_monte_carlo(start_price,days,mu,sigma))

plt.xlabel('Days')
plt.ylabel('Price')
plt.title('Monte Carlo Analysis for BTC')

# +
runs = 10000

simulations = np.zeros(runs)

for run in range(runs):
    simulations[run] = stock_monte_carlo(start_price,days,mu,sigma)[days-1]

# +
q = np.percentile(simulations,1)

plt.hist(simulations,bins=200)

plt.figtext(0.6,0.8,s="Start price: $%.2f" %start_price)

plt.figtext(0.6,0.7,"Mean final price: $%.2f" % simulations.mean())

plt.figtext(0.6,0.6,"VaR(0.99): $%.2f" % (start_price -q,))

plt.figtext(0.15,0.6, "q(0.99): $%.2f" % q)

plt.axvline(x=q, linewidth=4, color='r')

plt.title(u"Final price distribution for BTC after %s days" %days, weight='bold')
# -

# Seems like BTC's overall price is going down. After 10,000 runs the starting price is at $13,840 and it goes down to $13680.

StarcoderdataJupyterScriptsDedupFiltered