markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Generate Samples
#@title Generate 4 samples from the prior. temperature = 0.5 #@param {type:"slider", min:0.1, max:1.5, step:0.1} mel_2_samples = mel_2bar.sample(n=4, length=32, temperature=temperature) for ns in mel_2_samples: play(ns) #@title Optionally download samples. for i, ns in enumerate(mel_2_samples): download(ns, 'mel_2b...
_____no_output_____
Apache-2.0
colab/MusicVAE.ipynb
hwangsog/magenta
Generate Interpolations
#@title Option 1: Use example MIDI files for interpolation endpoints. input_mel_midi_data = [ tf.gfile.Open(fn).read() for fn in sorted(tf.gfile.Glob('/content/midi/mel_2bar*.mid'))] #@title Option 2: Upload your own MIDI files to use for interpolation endpoints instead of those provided. input_mel_midi_data = ...
_____no_output_____
Apache-2.0
colab/MusicVAE.ipynb
hwangsog/magenta
16-bar Melody ModelsThe pre-trained hierarchical model consists of a 2-layer stacked bidirectional LSTM encoder with 2048 nodes in each direction for each layer, a 16-step 2-layer LSTM "conductor" decoder with 1024 nodes in each layer, a 2-layer LSTM core decoder with 1024 nodes in each layer, and a Z with 512 dimensi...
#@title Load the pre-trained models. mel_16bar_models = {} hierdec_mel_16bar_config = configs.CONFIG_MAP['hierdec-mel_16bar'] mel_16bar_models['hierdec_mel_16bar'] = TrainedModel(hierdec_mel_16bar_config, batch_size=4, checkpoint_dir_or_path='/content/checkpoints/mel_16bar_hierdec.ckpt') flat_mel_16bar_config = config...
_____no_output_____
Apache-2.0
colab/MusicVAE.ipynb
hwangsog/magenta
Generate Samples
#@title Generate 4 samples from the selected model prior. mel_sample_model = "hierdec_mel_16bar" #@param ["hierdec_mel_16bar", "baseline_flat_mel_16bar"] temperature = 0.5 #@param {type:"slider", min:0.1, max:1.5, step:0.1} mel_16_samples = mel_16bar_models[mel_sample_model].sample(n=4, length=256, temperature=temperat...
_____no_output_____
Apache-2.0
colab/MusicVAE.ipynb
hwangsog/magenta
Generate Means
#@title Option 1: Use example MIDI files for interpolation endpoints. input_mel_16_midi_data = [ tf.gfile.Open(fn).read() for fn in sorted(tf.gfile.Glob('/content/midi/mel_16bar*.mid'))] #@title Option 2: upload your own MIDI files to use for interpolation endpoints instead of those provided. input_mel_16_midi_...
_____no_output_____
Apache-2.0
colab/MusicVAE.ipynb
hwangsog/magenta
16-bar "Trio" Models (lead, bass, drums)We present two pre-trained models for 16-bar trios: a hierarchical model and a flat (baseline) model.The pre-trained hierarchical model consists of a 2-layer stacked bidirectional LSTM encoder with 2048 nodes in each direction for each layer, a 16-step 2-layer LSTM "conductor" de...
#@title Load the pre-trained models. trio_models = {} hierdec_trio_16bar_config = configs.CONFIG_MAP['hierdec-trio_16bar'] trio_models['hierdec_trio_16bar'] = TrainedModel(hierdec_trio_16bar_config, batch_size=4, checkpoint_dir_or_path='/content/checkpoints/trio_16bar_hierdec.ckpt') flat_trio_16bar_config = configs.CO...
_____no_output_____
Apache-2.0
colab/MusicVAE.ipynb
hwangsog/magenta
Generate Samples
#@title Generate 4 samples from the selected model prior. trio_sample_model = "hierdec_trio_16bar" #@param ["hierdec_trio_16bar", "baseline_flat_trio_16bar"] temperature = 0.5 #@param {type:"slider", min:0.1, max:1.5, step:0.1} trio_16_samples = trio_models[trio_sample_model].sample(n=4, length=256, temperature=temper...
_____no_output_____
Apache-2.0
colab/MusicVAE.ipynb
hwangsog/magenta
Generate Means
#@title Option 1: Use example MIDI files for interpolation endpoints. input_trio_midi_data = [ tf.gfile.Open(fn).read() for fn in sorted(tf.gfile.Glob('/content/midi/trio_16bar*.mid'))] #@title Option 2: Upload your own MIDI files to use for interpolation endpoints instead of those provided. input_trio_midi_dat...
_____no_output_____
Apache-2.0
colab/MusicVAE.ipynb
hwangsog/magenta
Project 3: Smart Beta Portfolio and Portfolio Optimization OverviewSmart beta has a broad meaning, but we can say in practice that when we use the universe of stocks from an index, and then apply some weighting scheme other than market cap weighting, it can be considered a type of smart beta fund. A Smart Beta portfo...
import sys !{sys.executable} -m pip install -r requirements.txt
Requirement already satisfied: colour==0.1.5 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 1)) Collecting cvxpy==1.0.3 (from -r requirements.txt (line 2)) Downloading https://files.pythonhosted.org/packages/a1/59/2613468ffbbe3a818934d06b81b9f4877fe054afbf4f99d2f43f398a0b34/cvxpy-1.0.3.tar....
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
Load Packages
import pandas as pd import numpy as np import helper import project_helper import project_tests
_____no_output_____
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
Market Data Load DataFor this universe of stocks, we'll be selecting large dollar volume stocks. We're using this universe, since it is highly liquid.
df = pd.read_csv('../../data/project_3/eod-quotemedia.csv') percent_top_dollar = 0.2 high_volume_symbols = project_helper.large_dollar_volume_stocks(df, 'adj_close', 'adj_volume', percent_top_dollar) df = df[df['ticker'].isin(high_volume_symbols)] close = df.reset_index().pivot(index='date', columns='ticker', values=...
_____no_output_____
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
View DataTo see what one of these 2-d matrices looks like, let's take a look at the closing prices matrix.
project_helper.print_dataframe(close)
_____no_output_____
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
Part 1: Smart Beta PortfolioIn Part 1 of this project, you'll build a portfolio using dividend yield to choose the portfolio weights. A portfolio such as this could be incorporated into a smart beta ETF. You'll compare this portfolio to a market cap weighted index to see how well it performs. Note that in practice, y...
def generate_dollar_volume_weights(close, volume): """ Generate dollar volume weights. Parameters ---------- close : DataFrame Close price for each ticker and date volume : str Volume for each ticker and date Returns ------- dollar_volume_weights : DataFrame ...
Tests Passed
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
View DataLet's generate the index weights using `generate_dollar_volume_weights` and view them using a heatmap.
index_weights = generate_dollar_volume_weights(close, volume) project_helper.plot_weights(index_weights, 'Index Weights')
_____no_output_____
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
Portfolio WeightsNow that we have the index weights, let's choose the portfolio weights based on dividend. You would normally calculate the weights based on trailing dividend yield, but we'll simplify this by just calculating the total dividend yield over time.Implement `calculate_dividend_weights` to return the weigh...
def calculate_dividend_weights(dividends): """ Calculate dividend weights. Parameters ---------- dividends : DataFrame Dividend for each stock and date Returns ------- dividend_weights : DataFrame Weights for each stock and date """ #TODO: Implement function ...
Tests Passed
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
View DataJust like the index weights, let's generate the ETF weights and view them using a heatmap.
etf_weights = calculate_dividend_weights(dividends) project_helper.plot_weights(etf_weights, 'ETF Weights')
_____no_output_____
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
ReturnsImplement `generate_returns` to generate returns data for all the stocks and dates from price data. You might notice we're implementing returns and not log returns. Since we're not dealing with volatility, we don't have to use log returns.
def generate_returns(prices): """ Generate returns for ticker and date. Parameters ---------- prices : DataFrame Price for each ticker and date Returns ------- returns : Dataframe The returns for each ticker and date """ #TODO: Implement function return ((p...
Tests Passed
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
View DataLet's generate the closing returns using `generate_returns` and view them using a heatmap.
returns = generate_returns(close) project_helper.plot_returns(returns, 'Close Returns')
_____no_output_____
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
Weighted ReturnsWith the returns of each stock computed, we can use it to compute the returns for an index or ETF. Implement `generate_weighted_returns` to create weighted returns using the returns and weights.
def generate_weighted_returns(returns, weights): """ Generate weighted returns. Parameters ---------- returns : DataFrame Returns for each ticker and date weights : DataFrame Weights for each ticker and date Returns ------- weighted_returns : DataFrame Weigh...
Tests Passed
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
View DataLet's generate the ETF and index returns using `generate_weighted_returns` and view them using a heatmap.
index_weighted_returns = generate_weighted_returns(returns, index_weights) etf_weighted_returns = generate_weighted_returns(returns, etf_weights) project_helper.plot_returns(index_weighted_returns, 'Index Returns') project_helper.plot_returns(etf_weighted_returns, 'ETF Returns')
_____no_output_____
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
Cumulative ReturnsTo compare performance between the ETF and Index, we're going to calculate the tracking error. Before we do that, we first need to calculate the index and ETF comulative returns. Implement `calculate_cumulative_returns` to calculate the cumulative returns over time given the returns.
def calculate_cumulative_returns(returns): """ Calculate cumulative returns. Parameters ---------- returns : DataFrame Returns for each ticker and date Returns ------- cumulative_returns : Pandas Series Cumulative returns for each date """ #TODO: Implement funct...
Tests Passed
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
View DataLet's generate the ETF and index cumulative returns using `calculate_cumulative_returns` and compare the two.
index_weighted_cumulative_returns = calculate_cumulative_returns(index_weighted_returns) etf_weighted_cumulative_returns = calculate_cumulative_returns(etf_weighted_returns) project_helper.plot_benchmark_returns(index_weighted_cumulative_returns, etf_weighted_cumulative_returns, 'Smart Beta ETF vs Index')
_____no_output_____
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
Tracking ErrorIn order to check the performance of the smart beta portfolio, we can calculate the annualized tracking error against the index. Implement `tracking_error` to return the tracking error between the ETF and benchmark.For reference, we'll be using the following annualized tracking error function:$$ TE = \sq...
def tracking_error(benchmark_returns_by_date, etf_returns_by_date): """ Calculate the tracking error. Parameters ---------- benchmark_returns_by_date : Pandas Series The benchmark returns for each date etf_returns_by_date : Pandas Series The ETF returns for each date Return...
Tests Passed
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
View DataLet's generate the tracking error using `tracking_error`.
smart_beta_tracking_error = tracking_error(np.sum(index_weighted_returns, 1), np.sum(etf_weighted_returns, 1)) print('Smart Beta Tracking Error: {}'.format(smart_beta_tracking_error))
Smart Beta Tracking Error: 0.09940101796032481
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
Part 2: Portfolio OptimizationNow, let's create a second portfolio. We'll still reuse the market cap weighted index, but this will be independent of the dividend-weighted portfolio that we created in part 1.We want to both minimize the portfolio variance and also want to closely track a market cap weighted index. In...
def get_covariance_returns(returns): """ Calculate covariance matrices. Parameters ---------- returns : DataFrame Returns for each ticker and date Returns ------- returns_covariance : 2 dimensional Ndarray The covariance of the returns """ #TODO: Implement func...
Tests Passed
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
View DataLet's look at the covariance generated from `get_covariance_returns`.
covariance_returns = get_covariance_returns(returns) covariance_returns = pd.DataFrame(covariance_returns, returns.columns, returns.columns) covariance_returns_correlation = np.linalg.inv(np.diag(np.sqrt(np.diag(covariance_returns)))) covariance_returns_correlation = pd.DataFrame( covariance_returns_correlation.do...
_____no_output_____
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
portfolio varianceWe can write the portfolio variance $\sigma^2_p = \mathbf{x^T} \mathbf{P} \mathbf{x}$Recall that the $\mathbf{x^T} \mathbf{P} \mathbf{x}$ is called the quadratic form.We can use the cvxpy function `quad_form(x,P)` to get the quadratic form. Distance from index weightsWe want portfolio weights that tr...
import cvxpy as cvx def get_optimal_weights(covariance_returns, index_weights, scale=2.0): """ Find the optimal weights. Parameters ---------- covariance_returns : 2 dimensional Ndarray The covariance of the returns index_weights : Pandas Series Index weights for all tickers at...
Tests Passed
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
Optimized PortfolioUsing the `get_optimal_weights` function, let's generate the optimal ETF weights without rebalanceing. We can do this by feeding in the covariance of the entire history of data. We also need to feed in a set of index weights. We'll go with the average weights of the index over time.
raw_optimal_single_rebalance_etf_weights = get_optimal_weights(covariance_returns.values, index_weights.iloc[-1]) optimal_single_rebalance_etf_weights = pd.DataFrame( np.tile(raw_optimal_single_rebalance_etf_weights, (len(returns.index), 1)), returns.index, returns.columns)
_____no_output_____
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
With our ETF weights built, let's compare it to the index. Run the next cell to calculate the ETF returns and compare it to the index returns.
optim_etf_returns = generate_weighted_returns(returns, optimal_single_rebalance_etf_weights) optim_etf_cumulative_returns = calculate_cumulative_returns(optim_etf_returns) project_helper.plot_benchmark_returns(index_weighted_cumulative_returns, optim_etf_cumulative_returns, 'Optimized ETF vs Index') optim_etf_tracking...
_____no_output_____
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
Rebalance Portfolio Over TimeThe single optimized ETF portfolio used the same weights for the entire history. This might not be the optimal weights for the entire period. Let's rebalance the portfolio over the same period instead of using the same weights. Implement `rebalance_portfolio` to rebalance a portfolio.Rebla...
def rebalance_portfolio(returns, index_weights, shift_size, chunk_size): """ Get weights for each rebalancing of the portfolio. Parameters ---------- returns : DataFrame Returns for each ticker and date index_weights : DataFrame Index weight for each ticker and date shift_si...
Tests Passed
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
Run the following cell to rebalance the portfolio using `rebalance_portfolio`.
chunk_size = 250 shift_size = 5 all_rebalance_weights = rebalance_portfolio(returns, index_weights, shift_size, chunk_size)
_____no_output_____
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
Portfolio TurnoverWith the portfolio rebalanced, we need to use a metric to measure the cost of rebalancing the portfolio. Implement `get_portfolio_turnover` to calculate the annual portfolio turnover. We'll be using the formulas used in the classroom:$ AnnualizedTurnover =\frac{SumTotalTurnover}{NumberOfRebalanceEven...
def get_portfolio_turnover(all_rebalance_weights, shift_size, rebalance_count, n_trading_days_in_year=252): """ Calculage portfolio turnover. Parameters ---------- all_rebalance_weights : list of Ndarrays The ETF weights for each point they are rebalanced shift_size : int The nu...
Tests Passed
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
Run the following cell to get the portfolio turnover from `get_portfolio turnover`.
print(get_portfolio_turnover(all_rebalance_weights, shift_size, len(all_rebalance_weights) - 1))
16.72683266050277
MIT
project-03/project_3_starter.ipynb
rafaelmartinsbuck/ai-for-trading
Model Construction
# Model_3, use only the very last hidden layer from Roberta. from torch import nn from transformers import RobertaConfig, RobertaModel class OurRobertaCOPA(torch.nn.Module): def __init__(self): super(OurRobertaCOPA, self).__init__() # self.configuration = RobertaConfig() # self.tokenizer = ...
_____no_output_____
MIT
copa_roberta_more_data.ipynb
LiGhtime/NLPProject
Training
# Initialization tokenizer = RobertaTokenizer.from_pretrained('roberta-base') # model = OurRobertaCOPA() model = RobertaForMultipleChoice.from_pretrained('roberta-base') model.to(device) ce = nn.CrossEntropyLoss() softmax = nn.Softmax(dim=0) optimizer = torch.optim.Adam(model.parameters(), lr=1e-2) scheduler = torch.op...
_____no_output_____
MIT
copa_roberta_more_data.ipynb
LiGhtime/NLPProject
Testing
test_model = torch.load('RoBERTa.pth') test_model.eval() num_correct_pred = 0 with torch.no_grad(): for i in range(0, test_raw_data.shape[0]): prompt = test_raw_data.iloc[i]['asks-for'] + ". " + test_raw_data.iloc[i]['p'] choice0 = test_raw_data.iloc[i]['a1'] choice1 = test_raw_data.iloc[i]...
_____no_output_____
MIT
copa_roberta_more_data.ipynb
LiGhtime/NLPProject
Python Stock Trading Quick Start with Alpaca by Billy Hau The purpose of this tutorial is to provide a quick start guide to trade stock with python. We will use the Alpaca trading platform since it is free and support paper trading. We will go over the fundamental operations, such as connecting to an account, check ac...
! pip install pandas ! pip install numpy ! pip install matplotlib import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates import time ! pip install alpaca-trade-api
Requirement already satisfied: alpaca-trade-api in c:\users\billw\anaconda3\lib\site-packages (1.2.1) Requirement already satisfied: urllib3<2,>1.24 in c:\users\billw\anaconda3\lib\site-packages (from alpaca-trade-api) (1.25.11) Requirement already satisfied: numpy in c:\users\billw\anaconda3\lib\site-packages (from al...
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
3) Enter API Credentials from https://app.alpaca.markets/paper/dashboard/overview
ALPACA_ENDPOINT = 'https://paper-api.alpaca.markets' ALPACA_API = 'API Key ID' # Replace with API Key ID from Alpaca Paper Account ALPACA_API_SECRET = 'Secret Key' # Replace with Secret Key from Alpaca Paper Account
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
4) Import Alpaca API and Connect to Account
import alpaca_trade_api alpaca = alpaca_trade_api.REST(ALPACA_API, ALPACA_API_SECRET, ALPACA_ENDPOINT)
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
1) Access Account Information
account = alpaca.get_account() print(account)
Account({ 'account_blocked': False, 'account_number': 'PA2QIYXZJEXP', 'buying_power': '111133.208', 'cash': '20090.75', 'created_at': '2020-12-17T08:28:12.995558Z', 'currency': 'USD', 'daytrade_count': 0, 'daytrading_buying_power': '111133.208', 'equity': '31366.31', 'id': 'a921481...
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
Account Number
account.account_number
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
Account Cash
account.cash
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
Account Portfolio Value
account.portfolio_value
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
Account Stock Holdings / Positions
position = alpaca.list_positions() position
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
2) Get Stock Exchange Status
clock = alpaca.get_clock() clock
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
Current Time
clock.timestamp
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
Is the Market Currently Open?
clock.is_open
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
3) Get Stock Information
trade = alpaca.get_latest_trade('NIO') trade
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
Last Trade Price
trade.p
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
Last Trade Size
trade.s
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
Last Trade Time
trade.t
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
Historic DataHistoric Data is stored in Barsets and can be reported in timeframe of 1Min / 5Min / 15Min / 1D.- c: close- h: high- l: low- o: open- t: timestamp- v: volume
historic_data = alpaca.get_barset('NIO', timeframe='1D', limit=20) historic_data NIO_DATA = historic_data.df NIO_DATA NIO_DATA['NIO','close'].plot(figsize=(16,5), title='NIO Closing Price') fig, ax = plt.subplots(figsize=(16,5)) l1 = ax.plot(NIO_DATA['NIO', 'close'], 'g-', label='Close') ax.set_xlabel('Date') ax.set_y...
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
Historic Data for Multiple Stock
portfolio_list = ['SPY', 'VNQ', 'BND', 'GLD'] portfolio_data = alpaca.get_barset(portfolio_list, '1D', limit=100).df portfolio_data fig = plt.figure(figsize=(16,5)) for i in range(len(portfolio_list)): percentage_return = (portfolio_data[portfolio_list[i],'close'] - portfolio_data[portfolio_list[i],'close'][0]) / ...
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
4) Placing Stock Order Placing a Buy Order at Market Price
order0 = alpaca.submit_order('FB', qty=25, side='buy', type='market') order0
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
Placing a Buy Order at Limit Price
order1 = alpaca.submit_order('NIO', qty=10, side='buy', type='limit', limit_price=28) order1
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
Placing a Sell Order at Market Price
order2 = alpaca.submit_order('FB', qty=10, side='sell', type='market') order2
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
Shorting a StockConfigure Account to Allow / Disallow Shorting Stockhttps://app.alpaca.markets/paper/dashboard/config
alpaca.submit_order('GE', qty=100, side='sell', type='market')
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
List All Current Orders
order = alpaca.list_orders() order
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
Cancel an Order
alpaca.cancel_order(order[0].id) alpaca.list_orders()
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
Cancel All Orders
alpaca.cancel_all_orders() alpaca.list_orders()
_____no_output_____
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
Check Specific Order Status
alpaca.get_order(order0.id) print(order0.symbol + '\t' + order0.side + '\t' + order0.qty + '\t' + order0.type + '\t' + alpaca.get_order(order0.id).status) print(order1.symbol + '\t' + order1.side + '\t' + order1.qty + '\t' + order1.type + '\t' +alpaca.get_order(order1.id).status) print(order2.symbol + '\t' + order2.sid...
FB sell 10 limit filled
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
[PROJECT] Simple Paper Stock Trading BotThis is a simple trading bot project to practice everything we learned here. THIS IS ONLY MEANT FOR A PRACTICE, DO NOT USE FOR LIVE TRADING! AS ALWAYS, USE AT YOUR OWN RISK! In future tutorials, we will build a back-testing program to test our strategies. But right now, we just ...
stock = 'GME' data = alpaca.get_barset(stock, timeframe='1Min', limit=100).df avg = data[stock,'close'].rolling(30).mean() avg2 = data[stock,'close'].rolling(15).mean() diff2 = avg2.diff() fig, ax = plt.subplots(figsize=(16,10)) ax.plot(avg, 'b-', label = 'Moving Average 30Min') ax.plot(avg2, 'm-', label = 'Moving Ave...
[05/17/21 15:11:01] Market is Open... Executing Trading Bot Sequence! - [GME] Retrieving Market Data ... - [GME] Performing Stock Price Analysis ... --- [GME] Price: 176.29 MA15: 177.31 DIFF15: -0.02 MA30: 175.76 MA_Diff: 0.89 - [GME] Performing Technical Analysis ... --- Pass Through - [GME] cu...
MIT
1 - Python Stock Trading Quick Start with Alpaca.ipynb
Billwaa/python-algorithmic-stock-trading-
Homework: Basic Artificial Neural Networks
%matplotlib inline from time import time, sleep import numpy as np import matplotlib.pyplot as plt from IPython import display
_____no_output_____
MIT
homework_3_custom_framework/homework_main.ipynb
Vinogradov-Mikhail/Spbu_ML_hw_19
Framework Implement everything in `Modules.ipynb`. Read all the comments thoughtfully to ease the pain. Please try not to change the prototypes.Do not forget, that each module should return **AND** store `output` and `gradInput`.The typical assumption is that `module.backward` is always executed after `module.forward`...
# (re-)load layers %run homework_modules.ipynb
_____no_output_____
MIT
homework_3_custom_framework/homework_main.ipynb
Vinogradov-Mikhail/Spbu_ML_hw_19
Optimizer is implemented for you.
def sgd_momentum(x, dx, config, state): """ This is a very ugly implementation of sgd with momentum just to show an example how to store old grad in state. config: - momentum - learning_rate state: - old_grad """ # x and dx h...
_____no_output_____
MIT
homework_3_custom_framework/homework_main.ipynb
Vinogradov-Mikhail/Spbu_ML_hw_19
Build NN
net = Sequential() net.add(Linear(features, 300)) net.add(ReLU()) net.add(Linear(300, 10)) net.add(SoftMax()) criterion = MSECriterion() print(net)
Linear 784 -> 300 ReLU Linear 300 -> 10 SoftMax
MIT
homework_3_custom_framework/homework_main.ipynb
Vinogradov-Mikhail/Spbu_ML_hw_19
Train Basic training loop. Examine it.
loss_history = [] for i in range(n_epoch): for x_batch, y_batch in get_batches((x_train, y_train_onehot), batch_size): net.zeroGradParameters() # Forward predictions = net.forward(x_batch) loss = criterion.forward(predictions, y_batch) # Backward ...
_____no_output_____
MIT
homework_3_custom_framework/homework_main.ipynb
Vinogradov-Mikhail/Spbu_ML_hw_19
Build NN with dropout
net = Sequential() net.add(Linear(features, 300)) net.add(ReLU()) net.add(Dropout(0.7)) net.add(Linear(300, 10)) net.add(SoftMax()) criterion = MSECriterion() print(net) loss_history = [] for i in range(n_epoch): for x_batch, y_batch in get_batches((x_train, y_train_onehot), batch_size): net.zer...
_____no_output_____
MIT
homework_3_custom_framework/homework_main.ipynb
Vinogradov-Mikhail/Spbu_ML_hw_19
Mixture Model in PyMC3Original NB by Abe Flaxman, modified by Thomas Wiecki
import pymc3 as pm, theano.tensor as tt # simulate data from a known mixture distribution np.random.seed(12345) # set random seed for reproducibility k = 3 ndata = 500 spread = 5 centers = np.array([-spread, 0, spread]) # simulate data from mixture distribution v = np.random.randint(0, k, ndata) data = centers[v] + n...
[-----------------100%-----------------] 10000 of 10000 complete in 93.9 sec
Apache-2.0
pymc3/examples/gaussian_mixture_model.ipynb
dhiapet/PyMC3
Full trace
pm.plots.traceplot(tr, ['p', 'sd', 'means']);
_____no_output_____
Apache-2.0
pymc3/examples/gaussian_mixture_model.ipynb
dhiapet/PyMC3
After convergence
# take a look at traceplot for some model parameters # (with some burn-in and thinning) pm.plots.traceplot(tr[5000::5], ['p', 'sd', 'means']); # I prefer autocorrelation plots for serious confirmation of MCMC convergence pm.autocorrplot(tr[5000::5], ['sd'])
_____no_output_____
Apache-2.0
pymc3/examples/gaussian_mixture_model.ipynb
dhiapet/PyMC3
Sampling of cluster for individual data point
i=0 plt.plot(tr['category'][5000::5, i], drawstyle='steps-mid') plt.axis(ymin=-.1, ymax=2.1) def cluster_posterior(i=0): print('true cluster:', v[i]) print(' data value:', np.round(data[i],2)) plt.hist(tr['category'][5000::5,i], bins=[-.5,.5,1.5,2.5,], rwidth=.9) plt.axis(xmin=-.5, xmax=2.5) plt.xt...
true cluster: 2 data value: 3.29
Apache-2.0
pymc3/examples/gaussian_mixture_model.ipynb
dhiapet/PyMC3
Number of subarrays having product less than KGiven an Array of positive numbers, calculate the number of possible contiguous subarrays having product lesser than a given number K.Examples :Input : arr[] = [1, 2, 3, 4] K = 10Output : 7The subarrays are {1}, {2}, {3}, {4}{1, 2}, {1, 2, 3} and {2, 3}Input : arr[...
# Number of subarrays having product less than K # Python3 program to count subarrays # having product less than k. def countsubarray(array, n, k): count = 0 for i in range(0, n): # Counter for single element if array[i] <= k: count += 1 mul = array[i] for j in range(i + 1, n): # Mul...
7
MIT
sorting.ipynb
rakeshnavsoft/django-docker-s3
a = [5, 3, 2] k = 16 counter = 0 Window: [5] Product: 5 5 counter += 1+ (0-0) counter = 1 Window: [5,3] Product: 15 15 counter += 1 + (1-0) counter = 3 Window: [5,3,2] Product: 30 30 > 16 --> Adjust the left border New Window: [3,2] New Product: 6 6 counter += 1 + (2-1) counter = 5 Answer: 5
# Python3 program to count # subarrays having product # less than k. def countSubArrayProductLessThanK(a,k): n = len(a) p = 1 res = 0 start = 0 end = 0 while(end < n): # Move right bound by 1 # step. Update the product. p *= a[end] # Move left bound so guarantee # that p is again less tha...
24
MIT
sorting.ipynb
rakeshnavsoft/django-docker-s3
timestep> run one timestep of model
#export def solution(InitCond,ParamStruct,ClockStruct,weather_step,Outputs): """ Function to perform AquaCrop-OS solution for a single time step *Arguments:*\n `InitCond` : `InitCondClass` : containing current model paramaters `ClockStruct` : `ClockStructClass` : model time paramate...
Converted 00_core.ipynb. Converted 01_initialize.ipynb. Converted 02_timestep.ipynb. Converted 03_solution.ipynb. Converted 04_classes.ipynb. Converted 05_comparison.ipynb. Converted index.ipynb.
Apache-2.0
nbs/02_timestep.ipynb
qiz5/nbdev_qq_test
Self-Driving Car Engineer Nanodegree Project: **Finding Lane Lines on the Road** ***In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a se...
#importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import math import numpy as np import cv2 %matplotlib inline
_____no_output_____
MIT
P1.ipynb
ddonco/CarND-Finding-Lane-Lines
Read in an Image
#reading in an image image = mpimg.imread('test_images/solidWhiteRight.jpg') #printing out some stats and plotting print('This image is:', type(image), 'with dimensions:', image.shape) plt.figure(figsize=(10,6)) plt.imshow(image) # if you wanted to show a single color channel image called 'gray', for example, call as...
This image is: <class 'numpy.ndarray'> with dimensions: (540, 960, 3)
MIT
P1.ipynb
ddonco/CarND-Finding-Lane-Lines
Ideas for Lane Detection Pipeline **Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are:**`cv2.inRange()` for color selection `cv2.fillPoly()` for regions selection `cv2.line()` to draw lines on an image given endpoints `cv2.addWeighted()` to coadd / overlay two i...
import math def grayscale(img): """Applies the Grayscale transform This will return an image with only one color channel but NOTE: to see the returned image as grayscale (assuming your grayscaled image is called 'gray') you should call plt.imshow(gray, cmap='gray')""" return cv2.cvtColor(img, c...
_____no_output_____
MIT
P1.ipynb
ddonco/CarND-Finding-Lane-Lines
Test ImagesBuild your pipeline to work on the images in the directory "test_images" **You should make sure your pipeline works well on these images before you try the videos.**
import os os.listdir("test_images/")
_____no_output_____
MIT
P1.ipynb
ddonco/CarND-Finding-Lane-Lines
Build a Lane Finding Pipeline Build the pipeline and run your solution on all test_images. Make copies into the `test_images_output` directory, and you can use the images in your writeup report.Try tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters.
# Read in and grayscale the image image = mpimg.imread('test_images/solidWhiteRight.jpg') gray = grayscale(image) # Define a kernel size and apply Gaussian smoothing kernel_size = 5 blur_gray = gaussian_blur(gray, kernel_size) # Define our parameters for Canny and apply low_threshold = 55 high_threshold = 175 edges =...
540 960
MIT
P1.ipynb
ddonco/CarND-Finding-Lane-Lines
Test on VideosYou know what's cooler than drawing lanes over images? Drawing lanes over video!We can test our solution on two provided videos:`solidWhiteRight.mp4``solidYellowLeft.mp4`**Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel...
# Import everything needed to edit/save/watch video clips from moviepy.editor import VideoFileClip from IPython.display import HTML def process_image(image): # NOTE: The output you return should be a color image (3 channel) for processing video below # TODO: put your pipeline here, # you should return the f...
_____no_output_____
MIT
P1.ipynb
ddonco/CarND-Finding-Lane-Lines
Let's try the one with the solid white lane on the right first ...
white_output = 'test_videos_output/solidWhiteRight.mp4' ## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video ## To do so add .subclip(start_second,end_second) to the end of the line below ## Where start_second and end_second are integer values representing the start and...
[MoviePy] >>>> Building video test_videos_output/solidWhiteRight.mp4 [MoviePy] Writing video test_videos_output/solidWhiteRight.mp4
MIT
P1.ipynb
ddonco/CarND-Finding-Lane-Lines
Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice.
HTML(""" <video width="960" height="540" controls> <source src="{0}"> </video> """.format(white_output))
_____no_output_____
MIT
P1.ipynb
ddonco/CarND-Finding-Lane-Lines
Improve the draw_lines() function**At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about de...
yellow_output = 'test_videos_output/solidYellowLeft.mp4' ## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video ## To do so add .subclip(start_second,end_second) to the end of the line below ## Where start_second and end_second are integer values representing the start an...
_____no_output_____
MIT
P1.ipynb
ddonco/CarND-Finding-Lane-Lines
Writeup and SubmissionIf you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a [link](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_templat...
challenge_output = 'test_videos_output/challenge.mp4' ## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video ## To do so add .subclip(start_second,end_second) to the end of the line below ## Where start_second and end_second are integer values representing the start and e...
_____no_output_____
MIT
P1.ipynb
ddonco/CarND-Finding-Lane-Lines
ML2CPP Preparing the dataset
from sklearn import datasets import numpy as np import pandas as pd boston = datasets.load_boston() def populate_table(tablename, feature_names): X = boston.data y = boston.target N = X.shape[0] y = y.reshape(N,1) k = np.arange(N).reshape(N, 1) k_X_y = np.concatenate((k, X, y) , axis=1) ...
_____no_output_____
BSD-3-Clause
doc/FeatureSelection/ml2cpp_SelectKBest_boston.ipynb
antoinecarme/ml2cpp
Training a Model
# train any scikit model on the iris dataset from sklearn.feature_selection import SelectKBest, chi2 clf = SelectKBest(chi2, k=5) clf.fit(df[metadata['features']].values, df[metadata['targets']].values)
_____no_output_____
BSD-3-Clause
doc/FeatureSelection/ml2cpp_SelectKBest_boston.ipynb
antoinecarme/ml2cpp
Deploying the Model
def generate_cpp_for_model(model): import pickle, json, requests, base64 b64_data = base64.b64encode(pickle.dumps(model)).decode('utf-8') # send the model th the web service json_data={"Name":"model_cpp_sample", "PickleData":b64_data , "SQLDialect":"CPP", ...
count 506.0 mean 0.0 std 0.0 min 0.0 25% 0.0 50% 0.0 75% 0.0 max 0.0 dtype: float64 count 5.060000e+02 mean -3.471161e-17 std 6.703551e-16 min -1.421085e-14 25% 0.000000e+00 50% 0.000000e+00 75% 0.000000e+00 max 1.776357e-15 dtype: fl...
BSD-3-Clause
doc/FeatureSelection/ml2cpp_SelectKBest_boston.ipynb
antoinecarme/ml2cpp
Neural style transfer in PyTorchThis tutorial implements the "slow" neural style transfer based on the VGG19 model.It closely follows the official neural style tutorial you can find [here](http://pytorch.org/tutorials/advanced/neural_style_tutorial.html).__Note:__ if you didn't sit through the explanation of neural st...
import numpy as np import matplotlib.pyplot as plt %matplotlib inline from matplotlib.pyplot import imread from skimage.transform import resize, rotate import torch, torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable # desired size of the output image imsize = 512 # REDUCE THIS TO 1...
torch 1.10.0+cu111 Using GPU.
MIT
week10_interpretability/bonus_style_transfer/style_transfer_pytorch.ipynb
silviageiser/Practical_DL
Draw input images
!mkdir -p images !wget https://github.com/yandexdataschool/Practical_DL/raw/fall21/week10_interpretability/bonus_style_transfer/images/wave.jpg -O images/wave.jpg style_img = image_loader("images/wave.jpg").type(dtype) !wget http://cdn.cnn.com/cnnnext/dam/assets/170809210024-trump-nk.jpg -O images/my_img.jpg content_i...
_____no_output_____
MIT
week10_interpretability/bonus_style_transfer/style_transfer_pytorch.ipynb
silviageiser/Practical_DL
Define Style Transfer LossesAs shown in the lecture, we define two loss functions: content and style losses.Content loss is simply a pointwise mean squared error of high-level features while style loss is the error between gram matrices of intermediate feature layers.To obtain the feature representations we use a pre-...
import torchvision.models as models cnn = models.vgg19(pretrained=True).features # move it to the GPU if possible: if use_cuda: cnn = cnn.cuda() class ContentLoss(nn.Module): def __init__(self, target, weight): super(ContentLoss, self).__init__() # we 'detach' the target content from the tree...
_____no_output_____
MIT
week10_interpretability/bonus_style_transfer/style_transfer_pytorch.ipynb
silviageiser/Practical_DL
Style transfer pipelineWe can now define a unified "model" that computes all the losses on the image triplet (content image, style image, optimized image) so that we could optimize them with backprop (over image pixels).
content_weight=1 # coefficient for content loss style_weight=1000 # coefficient for style loss content_layers=('conv_4',) # use these layers for content loss style_layers=('conv_1', 'conv_2', 'conv_3', 'conv_4', 'conv_5') # use these layers for style loss content_losses = [] style_losses = [] mo...
_____no_output_____
MIT
week10_interpretability/bonus_style_transfer/style_transfer_pytorch.ipynb
silviageiser/Practical_DL
OptimizationWe can now optimize both style and content loss over input image.
input_image = Variable(content_img.clone().data, requires_grad=True) optimizer = torch.optim.Adam([input_image], lr=0.1) num_steps = 300 for i in range(num_steps): # correct the values of updated input image input_image.data.clamp_(0, 1) model(input_image) style_score = 0 content_score = 0 for...
_____no_output_____
MIT
week10_interpretability/bonus_style_transfer/style_transfer_pytorch.ipynb
silviageiser/Practical_DL
Final image
plt.figure(figsize=[10,10]) imshow(input_image.data) plt.show()
_____no_output_____
MIT
week10_interpretability/bonus_style_transfer/style_transfer_pytorch.ipynb
silviageiser/Practical_DL
Implementing a 1D convnetIn Keras, you would use a 1D convnet via the `Conv1D` layer, which has a very similar interface to `Conv2D`. It **takes as input 3D tensors with shape (samples, time, features) and also returns similarly-shaped 3D tensors**. The convolution window is a 1D window on the temporal axis, axis 1 in...
from tensorflow.keras.datasets import imdb from tensorflow.keras.preprocessing import sequence max_features = 10000 # number of words to consider as features max_len = 500 # cut texts after this number of words (among top max_features most common words) print('Loading data...') (x_train, y_train), (x_test, y_test) ...
Loading data... 25000 train sequences 25000 test sequences Pad sequences (samples x time) x_train shape: (25000, 500) x_test shape: (25000, 500)
MIT
notebooks/chapter_06/05 - Sequence processing with convnets.ipynb
lucone83/deep-learning-with-python
**1D convnets are structured in the same way as their 2D counter-parts**: they consist of a stack of `Conv1D` and `MaxPooling1D layers`, eventually ending in either a global pooling layer or a `Flatten` layer, turning the 3D outputs into 2D outputs, allowing to add one or more Dense layers to the model, for classificat...
from tensorflow.keras.models import Sequential from tensorflow.keras import layers from tensorflow.keras.optimizers import RMSprop model = Sequential() model.add(layers.Embedding(max_features, 128, input_length=max_len)) model.add(layers.Conv1D(32, 7, activation='relu')) model.add(layers.MaxPooling1D(5)) model.add(lay...
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= embedding (Embedding) (None, 500, 128) 1280000 ____________________________________...
MIT
notebooks/chapter_06/05 - Sequence processing with convnets.ipynb
lucone83/deep-learning-with-python
Here are our training and validation results: validation accuracy is slightly lower than that of the LSTM example we used two sections ago, but runtime is faster, both on CPU and GPU (albeit the exact speedup will vary greatly depending on your exact configuration). At that point, we could re-train this model for the r...
import matplotlib.pyplot as plt acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(len(acc)) plt.plot(epochs, acc, 'bo', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training...
_____no_output_____
MIT
notebooks/chapter_06/05 - Sequence processing with convnets.ipynb
lucone83/deep-learning-with-python
Combining CNNs and RNNs to process long sequencesBecause 1D convnets process input patches independently, **they are not sensitive to the order of the timesteps** (beyond a local scale, the size of the convolution windows), unlike RNNs. Of course, in order to be able to recognize longer-term patterns, one could stack ...
import numpy as np import os # Import data data_dir = './datasets/jena' fname = os.path.join(data_dir, 'jena_climate_2009_2016.csv') f = open(fname) data = f.read() f.close() lines = data.split('\n') header = lines[0].split(',') lines = lines[1:] print(header) print() print(len(lines)) # Preprocessing float_data ...
_____no_output_____
MIT
notebooks/chapter_06/05 - Sequence processing with convnets.ipynb
lucone83/deep-learning-with-python
The validation MAE stays in the low 0.40s: **we cannot even beat our common-sense baseline using the small convnet**. Again, this is because **our convnet looks for patterns anywhere in the input timeseries, and has no knowledge of the temporal position of a pattern it sees** (e.g. towards the beginning, towards the en...
# This was previously set to 6 (one point per hour). Now 3 (one point per 30 min). step = 3 lookback = 720 # Unchanged delay = 144 # Unchanged train_gen = generator( float_data, lookback=lookback, delay=delay, min_index=0, max_index=200000, shuffle=True, step=step ) val_gen = generator( ...
_____no_output_____
MIT
notebooks/chapter_06/05 - Sequence processing with convnets.ipynb
lucone83/deep-learning-with-python
This is our new model, **starting with two `Conv1D` layers and following-up with a `GRU` layer**:
model = Sequential() model.add(layers.Conv1D(32, 5, activation='relu',input_shape=(None, float_data.shape[-1]))) model.add(layers.MaxPooling1D(3)) model.add(layers.Conv1D(32, 5, activation='relu')) model.add(layers.GRU(32, dropout=0.1, recurrent_dropout=0.5)) model.add(layers.Dense(1)) model.summary() model.compile(o...
_____no_output_____
MIT
notebooks/chapter_06/05 - Sequence processing with convnets.ipynb
lucone83/deep-learning-with-python