Skip to content

Instantly share code, notes, and snippets.

@Vido
Created July 4, 2023 15:23
Show Gist options
  • Save Vido/bd8ee82d4837a67e7b6b5ee30be0b7e3 to your computer and use it in GitHub Desktop.
Save Vido/bd8ee82d4837a67e7b6b5ee30be0b7e3 to your computer and use it in GitHub Desktop.
Modelo de Markowitz com dados da Binance
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy.optimize as sco
from quotes import tickers
df = pd.read_pickle("quotes.pkl")
logrets = np.log(df / df.shift(1))
rmean = logrets.mean() * 365
cov = logrets.cov() * 365
def statistics(weights):
RE = np.sum(rmean * weights)
DP = np.sqrt(np.dot(weights.T, np.dot(cov, weights)))
return DP, RE
n = len(tickers)
cons = ({'type': 'eq', 'fun': lambda x: np.sum(x)-1})
bnds = tuple((0, 1) for x in range(n))
chute = [0.4, 0.4, 0.0, 0.2, 0.0, 0.0, 0.0, 0.0]
def funcao_objetivo(weights):
DP, RE = statistics(weights)
return DP/RE # Invertido (minimize)
opts = sco.minimize(funcao_objetivo, chute, method='SLSQP', bounds=bnds, constraints=cons)
plt.pie(opts.x.round(2), explode=n*[1/n], labels=tickers)
plt.legend(tickers, loc='best')
plt.show()
ponderacao = n * [1/n]
plt.pie(ponderacao, explode=n*[1/n], labels=tickers)
plt.legend(tickers, loc='best')
plt.show()
DP1, RE1 = statistics(opts.x)
DP2, RE2 = statistics(np.array(ponderacao))
import os
from datetime import datetime
import pandas as pd
from decouple import config
from binance.client import Client
import matplotlib.pyplot as plt
def download_hquotes_binance(binance_tickers):
client = Client(config('BINANCE_APIKEY'), config('BINANCE_SECRETKEY'))
df_buffer = pd.DataFrame()
for idx, ticker in enumerate(binance_tickers):
klines = client.get_historical_klines(
ticker, Client.KLINE_INTERVAL_1DAY, "26 Jun, 2022")
ts_list, q_list = [], []
for k in klines:
ts_list.append(datetime.fromtimestamp(int(k[0])/1000))
q_list.append(float(k[4]))
df_buffer[ticker] = pd.Series(data=q_list, index=ts_list)
return df_buffer
tickers = [ 'BTCUSDT',
'ETHUSDT',
'BNBUSDT',
'XRPUSDT',
'ADAUSDT',
'DOGEUSDT',
'SOLUSDT',
'DOTUSDT',
#'LTCUSDT',
]
if __name__ == '__main__':
df = download_hquotes_binance(tickers)
df.to_pickle("quotes.pkl")
(df / df.iloc[0]).plot()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment