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 |
|---|---|---|---|---|---|
Clean Data | #remove unwanted columns
df_cleaned = df.drop(['DGUID','UOM_ID','SCALAR_ID','VECTOR', 'COORDINATE', 'STATUS','SYMBOL','TERMINATED', 'DECIMALS'],axis=1)
#remove unwanted rows
df_cleaned = df_cleaned[df_cleaned['GEO'].isin(['Canada','British Columbia'])]
df_cleaned = df_cleaned[df_cleaned['UOM'].isin(['Dollars'])]
#remov... | _____no_output_____ | MIT | notebooks/analysis1.ipynb | data301-2021-winter1/group05-project |
Process/Wrangle Data | df_cleaned = df_cleaned.rename(columns = {'REF_DATE':'Year', 'GEO': 'Location', 'SCALAR_FACTOR': 'Scalar factor', 'VALUE':'Value' })
df_cleaned | _____no_output_____ | MIT | notebooks/analysis1.ipynb | data301-2021-winter1/group05-project |
Task 3: Method Chain Step 1 | df = (
pd.read_csv("../data/raw/tourism.csv")
.drop(columns=['DGUID','UOM_ID','SCALAR_ID','VECTOR', 'COORDINATE', 'STATUS','SYMBOL','TERMINATED', 'DECIMALS'],axis=1)
.dropna()
.query("GEO != ['Nunavut', 'Northwest Territories','Yukon','Newfoundland and Labrador','Prince Edward Island','Nova Scotia','New... | _____no_output_____ | MIT | notebooks/analysis1.ipynb | data301-2021-winter1/group05-project |
Step 2 | def load_and_process(url_or_path_to_csv_file):
# Method Chain 1
df = (
pd.read_csv(url_or_path_to_csv_file)
.drop(columns=['DGUID','UOM_ID','SCALAR_ID','VECTOR', 'COORDINATE', 'STATUS','SYMBOL','TERMINATED', 'DECIMALS'],axis=1)
.dropna()
.query("GEO != ['Nunavut', 'Northwest Terr... | _____no_output_____ | MIT | notebooks/analysis1.ipynb | data301-2021-winter1/group05-project |
Step 3 | import project_functions1
df = project_functions1.load_and_process("../data/raw/tourism.csv")
df
df_cleaned.to_csv('emily_cleaned_data.csv') | _____no_output_____ | MIT | notebooks/analysis1.ipynb | data301-2021-winter1/group05-project |
Task 4: Conduct your analysis Research Question 1: Which categories within tourism BC makes the most money in In the table below, we can see which categories have the highest total demand in BC. We can compare these numbers with the total demands in Canada to see what percentage of these catagories is from BC. | dfBC = df[df['Location'].isin(['British Columbia'])]
dfBC = dfBC[dfBC['Indicators'].isin(['Total demand'])]
dfBC = dfBC[['Year','Products','Value']]
dfBC = dfBC.sort_values(by=["Value"], ascending=[False]).groupby("Value")
dfBC.head(10)
### I don't know why head isn't working properly
dfCan = df[df['Location'].isin(['B... | _____no_output_____ | MIT | notebooks/analysis1.ipynb | data301-2021-winter1/group05-project |
The top 3 catagories of higest demand in BC are Total Tourism Expenditures, Total Tourism Products and Total Transportion. These catagories remain top 3 in 2017 as well. We can see some growth from 2014 to 2017 in these catagories within BC as well as Canada. We can use this data in these catagories to find out what p... | sns.barplot(data=new_df, x='Indicator', y='Dollars (in millions)', hue='Location and Year')
plt.title('Total Tourism Expenditures per Indicator for 2014 and 2017')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0)
new_Can = pd.DataFrame([['2014','Total Demand', 84580.6],
['2... | _____no_output_____ | MIT | notebooks/analysis1.ipynb | data301-2021-winter1/group05-project |
Example for Minicircuits Switch Boxes controlled via USB | from qcodes.instrument_drivers.Minicircuits.USB_SPDT import USB_SPDT | _____no_output_____ | MIT | docs/examples/driver_examples/Qcodes example with Minicircuits Switch boxes (USB-XSPDT).ipynb | jsaez8/Qcodes |
change the serial number to the serial number on the sticker on the back of the device, or leave it blank if there is only one switch box connectedThe driver_path should specify the url of the dll for controlling the instrument. You can find it here:https://ww2.minicircuits.com/softwaredownload/rfswitchcontroller.htmlD... | dev = USB_SPDT('test',
serial_number='11703020018',
driver_path= r'C:\Users\a-dovoge\Qcodes\qcodes\instrument_drivers\Minicircuits\mcl_RF_Switch_Controller64') | Connected to: Mini-Circuits RC-4SPDT-A18 (serial:11703020018, firmware:20) in 0.19s
| MIT | docs/examples/driver_examples/Qcodes example with Minicircuits Switch boxes (USB-XSPDT).ipynb | jsaez8/Qcodes |
setting value to line one or two | dev.a(1) | _____no_output_____ | MIT | docs/examples/driver_examples/Qcodes example with Minicircuits Switch boxes (USB-XSPDT).ipynb | jsaez8/Qcodes |
reading value | dev.b() | _____no_output_____ | MIT | docs/examples/driver_examples/Qcodes example with Minicircuits Switch boxes (USB-XSPDT).ipynb | jsaez8/Qcodes |
setting all switches to line 2 | dev.all(2) | _____no_output_____ | MIT | docs/examples/driver_examples/Qcodes example with Minicircuits Switch boxes (USB-XSPDT).ipynb | jsaez8/Qcodes |
官方DEMO- Message Type :https://developers.line.me/en/docs/messaging-api/message-types/ Doc : https://github.com/line/line-bot-sdk-python/blob/master/linebot/models/send_messages.py | CHANNEL_ACCESS_TOKEN = "YOUR CHANNEL TOKEN"
# user ID - Get by reply message object.
to = "YOUR USER ID"
from linebot.models import TextSendMessage | _____no_output_____ | MIT | .ipynb_checkpoints/push_tutorial-checkpoint.ipynb | darkfirzenmax/Line_chatbot_tutorial |
TextSendMessage | line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)
try:
line_bot_api.push_message(to, TextSendMessage(text='台科大電腦研習社'))
except LineBotApiError as e:
# error handle
raise e | _____no_output_____ | MIT | .ipynb_checkpoints/push_tutorial-checkpoint.ipynb | darkfirzenmax/Line_chatbot_tutorial |
Output  | from linebot.models import ImageSendMessage, VideoSendMessage, LocationSendMessage, StickerSendMessage | _____no_output_____ | MIT | .ipynb_checkpoints/push_tutorial-checkpoint.ipynb | darkfirzenmax/Line_chatbot_tutorial |
ImageSendMessage 連結需要使用https 物件中的輸入 original_content_url 以及 preview_image_url都要寫才不會報錯。輸入的網址要是一個圖片,應該說只能是一個圖片,不然不會報錯但是傳過去是灰色不能用的圖他圖片的功能都有點問題,我都要丟到imgur圖床才能鏈結。。。直接丟進github 用raw也不能讀 | line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)
image_url = "https://i.imgur.com/eTldj2E.png?1"
try:
line_bot_api.push_message(to, ImageSendMessage(original_content_url=image_url, preview_image_url=image_url))
except LineBotApiError as e:
# error handle
raise e | _____no_output_____ | MIT | .ipynb_checkpoints/push_tutorial-checkpoint.ipynb | darkfirzenmax/Line_chatbot_tutorial |
Output  | from linebot.models import LocationSendMessage | _____no_output_____ | MIT | .ipynb_checkpoints/push_tutorial-checkpoint.ipynb | darkfirzenmax/Line_chatbot_tutorial |
LocationSendMessage | line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)
title = "國立臺灣科技大學"
address = "106台北市大安區基隆路四段43號"
latitude = 25.0136906
longitude = 121.5406792
try:
line_bot_api.push_message(to, LocationSendMessage(title=title,
address=address,
... | _____no_output_____ | MIT | .ipynb_checkpoints/push_tutorial-checkpoint.ipynb | darkfirzenmax/Line_chatbot_tutorial |
Output  | from linebot.models import StickerSendMessage | _____no_output_____ | MIT | .ipynb_checkpoints/push_tutorial-checkpoint.ipynb | darkfirzenmax/Line_chatbot_tutorial |
StickerSendMessage 照下面這段話的意思是說,只能用預設的!!!Message object which contains the sticker data sent from the source.For a list of basic LINE stickers and sticker IDs, see sticker list.stick list:https://developers.line.me/media/messaging-api/messages/sticker_list.pdf | line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)
package_id = "1"
sticker_id = "1"
# package_id = "1181660"
# sticker_id = "7389429"
try:
line_bot_api.push_message(to, StickerSendMessage(package_id=package_id, sticker_id=sticker_id))
except LineBotApiError as e:
# error handle
raise e
| _____no_output_____ | MIT | .ipynb_checkpoints/push_tutorial-checkpoint.ipynb | darkfirzenmax/Line_chatbot_tutorial |
Output  ImagemapSendMessage | from linebot.models import ImagemapSendMessage, BaseSize, URIImagemapAction, MessageImagemapAction, ImagemapArea | _____no_output_____ | MIT | .ipynb_checkpoints/push_tutorial-checkpoint.ipynb | darkfirzenmax/Line_chatbot_tutorial |
這邊解説一下輸入一張圖片的網址https,他會顯示一張圖片,但是可以對這張圖片的點選範圍做一些操作例如對某區塊點擊會發生什麼事 舉例:輸入一張圖片(如下圖)by colors https://coolors.co/ffb8d1-e4b4c2-e7cee3-e0e1e9-ddfdfe Imagemap 讓我們可以對圖片的區塊(給定一個範圍)做操作,例如我們要使用最左邊的顏色點擊後輸出色票最右邊的顏色點擊後轉至網址他圖片的功能都有點問題,我都要丟到imgur圖床才能鏈結。。。直接丟進github 用raw也不能讀而且他不會自動縮放,會裁掉  | line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)
# image_url = "https://raw.githubusercontent.com/xiaosean/Line_tutorial/master/img/colors.png"
image_url = "https://i.imgur.com/mB9yDO0.png"
text = "#FFB8D1"
click_link_1 = "https://www.facebook.com/ntustcc"
try:
line_bot_api.push_message(to, ImagemapSendMessage(ba... | _____no_output_____ | MIT | .ipynb_checkpoints/push_tutorial-checkpoint.ipynb | darkfirzenmax/Line_chatbot_tutorial |
Output  TemplateSendMessage - ButtonsTemplate 只可在智慧手機上顯示 doc:https://github.com/line/line-bot-sdk-python/blob/master/linebot/models/template.py 這部分我建議看這個人所寫的 - 他的圖片很用心,真好看!!https://ithelp.ithome.com.tw/articles/10195640?sc=iThomeR | from linebot.models import TemplateSendMessage, ButtonsTemplate, PostbackTemplateAction, MessageTemplateAction, URITemplateAction
button_template_message =ButtonsTemplate(
thumbnail_image_url="https://i.imgur.com/eTldj2E.png?1",
title='Menu',
... | _____no_output_____ | MIT | .ipynb_checkpoints/push_tutorial-checkpoint.ipynb | darkfirzenmax/Line_chatbot_tutorial |
Output  TemplateSendMessage - CarouselTemplate 只可在智慧手機上顯示 他和前一個的差別是他可以一次傳送多個Template並且可以用旋轉的方式轉過去 1...n | from linebot.models import TemplateSendMessage, CarouselTemplate, CarouselColumn, ButtonsTemplate, PostbackTemplateAction, MessageTemplateAction, URITemplateAction
image_url_1 = "https://i.imgur.com/eTldj2E.png?1"
image_url_2 = "https://i.imgur.com/mB9yDO0.png"
click_link_1 = "https://www.facebook.com/ntustcc"
click_li... | _____no_output_____ | MIT | .ipynb_checkpoints/push_tutorial-checkpoint.ipynb | darkfirzenmax/Line_chatbot_tutorial |
Output  TemplateSendMessage - ImageCarouselTemplate 只可在智慧手機上顯示 他和前一個的差別是整個版面都是圖片和一行文字,較為簡潔,請看結果。 | from linebot.models import TemplateSendMessage, ImageCarouselTemplate, ImageCarouselColumn, PostbackTemplateAction, MessageTemplateAction, URITemplateAction
image_url_1 = "https://i.imgur.com/eTldj2E.png?1"
image_url_2 = "https://i.imgur.com/mB9yDO0.png"
carousel_template = template=ImageCarouselTemplate(
c... | _____no_output_____ | MIT | .ipynb_checkpoints/push_tutorial-checkpoint.ipynb | darkfirzenmax/Line_chatbot_tutorial |
Output  TemplateAction有個DatetimePickerTemplateAction | from linebot.models import TemplateSendMessage, ButtonsTemplate, DatetimePickerTemplateAction
button_template_message =ButtonsTemplate(
thumbnail_image_url="https://i.imgur.com/eTldj2E.png?1",
title='Menu',
text='Please select',
... | _____no_output_____ | MIT | .ipynb_checkpoints/push_tutorial-checkpoint.ipynb | darkfirzenmax/Line_chatbot_tutorial |
Output  FileMessage - 沒實作 DOC https://github.com/line/line-bot-sdk-python/blob/master/linebot/models/messages.py | from linebot.models import VideoSendMessage | _____no_output_____ | MIT | .ipynb_checkpoints/push_tutorial-checkpoint.ipynb | darkfirzenmax/Line_chatbot_tutorial |
VideoSendMessage - 我沒試成功 Failed 文件中的input有說"影片時長要 我猜拉 只要找到網址後綴是.mp4應該就可以只是我找不到這種影片 | line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)
viedo_url = ""
image_url = ""
try:
line_bot_api.push_message(to, VideoSendMessage(original_content_url=viedo_url, preview_image_url=image_url))
except LineBotApiError as e:
# error handle
raise e | _____no_output_____ | MIT | .ipynb_checkpoints/push_tutorial-checkpoint.ipynb | darkfirzenmax/Line_chatbot_tutorial |
Random ForestRandom Forest is an ensemble tree-based predictive algorithm. In this case we will be using it for regression - we want to predict a continuous number, predicted points, for each player each game. It works by training many separate decision trees, each using a subset of the training data, and outputs the ... | # add a bunch of player lag features
lag_train_df, team_lag_vars = team_lag_features(train_df, ['total_points'], ['all', 1, 2, 3, 4, 5, 10])
lag_train_df, player_lag_vars = player_lag_features(lag_train_df, ['total_points'], ['all', 1, 2, 3, 4, 5, 10]) | _____no_output_____ | MIT | notebooks/02_fpl_predict_random_forest.ipynb | aneesh2606/fpl-prediction |
Similar to the simple model, we'll set the validation period to be gameweeks 20-25 of the 2019/20 season - the model will be trained on all data prior to that period. This time however, we'll be using some additional features: the season, gameweek, player position, home/away, and both teams, as well as all the lagging ... | # set validaton point/length and categorical/continuous variables
valid_season = '2021'
valid_gw = 20
valid_len = 6
cat_vars = ['season', 'position', 'was_home', 'team', 'opponent_team']
cont_vars = ['gw']#, 'minutes']
dep_var = ['total_points'] | _____no_output_____ | MIT | notebooks/02_fpl_predict_random_forest.ipynb | aneesh2606/fpl-prediction |
Some of the features have an order (2019/20 season is after 2019 season) whereas others do not (position). We can set this in the data where appropriate using an ordered category (e.g. 1617 < 1718 < 1819 < 1920 < 2021). | # we want to set gw and season as ordered categorical variables
# need lists with ordered categories
ordered_gws = list(range(1,39))
ordered_seasons = ['1617', '1718', '1819', '1920', '2021']
# set as categories with correct order
lag_train_df['gw'] = lag_train_df['gw'].astype('category')
lag_train_df['season'] = lag... | _____no_output_____ | MIT | notebooks/02_fpl_predict_random_forest.ipynb | aneesh2606/fpl-prediction |
And now we can go ahead and create our training and validation sets using the function we defined in the last notebook. | # create dataset with adjusted post-validation lag numbers
train_valid_df, train_idx, valid_idx = create_lag_train(lag_train_df,
cat_vars, cont_vars,
player_lag_vars, team_lag_vars, dep_var,
... | _____no_output_____ | MIT | notebooks/02_fpl_predict_random_forest.ipynb | aneesh2606/fpl-prediction |
The way we calculate our lag features means that there will be null values in our dataset. This will cause an error when using random forest in scikit learn, so we will set them all to zero for now (although note that this may not be the best fill strategy). | lag_train_df[~np.isfinite(lag_train_df['total_points_pg_last_1'])]
# imp = SimpleImputer(missing_values=np.nan, strategy='mean')
# need to think about imputing NaN instead of setting to zero
# imp.fit(X_train[team_lag_vars + player_lag_vars])
train_valid_df[team_lag_vars + player_lag_vars] = train_valid_df[team_lag_var... | _____no_output_____ | MIT | notebooks/02_fpl_predict_random_forest.ipynb | aneesh2606/fpl-prediction |
The random forest regressor will only take numbers as inputs, so we need to transform our caterogical features into a format that the random forest regressor object will be able to use, numbers instead of strings in one or more columns. | # split out dependent variable
X, y = train_valid_df[cat_vars + cont_vars + team_lag_vars + player_lag_vars].copy(), train_valid_df[dep_var].copy()
# since position is categorical, it should be a string
X['position'] = X['position'].apply(str)
# need to transform season
enc = LabelEncoder()
X['season'] = enc.fit_trans... | _____no_output_____ | MIT | notebooks/02_fpl_predict_random_forest.ipynb | aneesh2606/fpl-prediction |
For example, season is now represented by a number (0 -> 2016/17, 1 -> 2017/18, etc.) in a single column, and position is represented by a 1 or 0 in multiple columns. | X_df[['season', 'position_1', 'position_2', 'position_3', 'position_4']]
X_df.columns | _____no_output_____ | MIT | notebooks/02_fpl_predict_random_forest.ipynb | aneesh2606/fpl-prediction |
Let's now split out our training (everything prior to the validation gameweek) and validation (6 gameweeks from the validation gameweek, only rows with >0 minutes) | # split out training and validation sets
X_train = X_df.loc[train_idx]
y_train = y.loc[train_idx]
X_test = X_df.loc[valid_idx]
# we only want look at rows with >0 minutes (i.e. the player played)
# test_mask = (X_test['minutes'] > 0)
# X_test = X_test[test_mask]
# y_test = y.loc[valid_idx][test_mask]
y_test = y.loc[val... | _____no_output_____ | MIT | notebooks/02_fpl_predict_random_forest.ipynb | aneesh2606/fpl-prediction |
We can now create the RandomForestRegessor with set parameters, train using the training data, and look at the error on the validation set. | # def rf(xs, y, n_estimators=40, max_samples=50_000,
# max_features=0.5, min_samples_leaf=5, **kwargs):
# return RandomForestRegressor(n_jobs=-1, n_estimators=n_estimators,
# max_samples=max_samples, max_features=max_features,
# min_samples_leaf=min_samples_leaf, oob_score=True).fit(xs, y)
de... | RMSE: 2.147401
MAE: 1.217610
| MIT | notebooks/02_fpl_predict_random_forest.ipynb | aneesh2606/fpl-prediction |
Right away this looks like it's a significant improvement on the simple model, good to see. Let's go ahead and use the same approach with validation across the whole of the 2019/20 season. | def rf_season(df, valid_season='2021'):
# empty list for scores
scores = []
valid_len = 6
for valid_gw in range(1,40-valid_len):
# create dataset with adjusted post-validation lag numbers
train_valid_df, train_idx, valid_idx = create_lag_train(df, cat_vars, cont_vars,
... | _____no_output_____ | MIT | notebooks/02_fpl_predict_random_forest.ipynb | aneesh2606/fpl-prediction |
Looking across the whole season we see about a 10% improvement versus the simple model. Also interesting is that the performance again improves as the season progresses - this makes sense, more data about each of teams and players (particularly new ones) means improved ability to predict the next 6 gameweeks.Let's add ... | model_validation_scores = pd.read_csv(path/'charts/model_validation_scores.csv', index_col=0)
model_validation_scores['random_forest'] = scores
model_validation_scores.to_csv(path/'charts/model_validation_scores.csv') | _____no_output_____ | MIT | notebooks/02_fpl_predict_random_forest.ipynb | aneesh2606/fpl-prediction |
A feature of the random forest algorithm is that we can see how often features are being used in trees. This will give us an indication of how important each feature is i.e. is it predictive of todal points scored. Simple models are usually better, so this also gives us a way of seeing if there are any features that ar... | def rf_feat_importance(m, df):
return pd.DataFrame({'cols':df.columns, 'imp':m.feature_importances_}
).sort_values('imp', ascending=False)
fi = rf_feat_importance(m, X_train)
fi[:32]
def plot_fi(fi):
return fi.plot('cols', 'imp', 'barh', figsize=(12,7), legend=False).invert_yaxis()
plot_... | _____no_output_____ | MIT | notebooks/02_fpl_predict_random_forest.ipynb | aneesh2606/fpl-prediction |
At the moment this algorithm is given minutes played in the gameweek so it's unsurprising that this is by far the most important feature - the more minutes a player plays, the more opportunity to score points. But strictly speaking we don't actually have this information prior to a gameweek (in practice it is estimated... | to_keep = fi[fi.imp>0.005].cols
len(to_keep)
len(X_train.columns)
X_train_imp = X_train[to_keep]
X_test_imp = X_test[to_keep]
m = rf(X_train_imp, y_train.values.ravel())
mae(m.predict(X_test_imp), y_test.values.ravel())
# mae(m.predict(X_train_imp), y_train.values.ravel()) | _____no_output_____ | MIT | notebooks/02_fpl_predict_random_forest.ipynb | aneesh2606/fpl-prediction |
Very similar albeit slightly higher error (less than 1% worse performance) than previously, and still a long way ahead of the simple model.Continuing our thinking about improving/simplifying the model features, we can also look to see if there are any similar features - quite often we will find that some features are s... | def cluster_columns(df, figsize=(10,6), font_size=12):
corr = np.round(sp.stats.spearmanr(df).correlation, 4)
corr_condensed = hc.distance.squareform(1-corr)
z = hc.linkage(corr_condensed, method='average')
fig = plt.figure(figsize=figsize)
hc.dendrogram(z, labels=df.columns, orientation='left', lea... | _____no_output_____ | MIT | notebooks/02_fpl_predict_random_forest.ipynb | aneesh2606/fpl-prediction |
We can see that our lagging features are somewhat similar - absolutely expected since, for example, minutes_last_5 is equal to minutes_last_4 + minutes 5 games ago. They are still different enough to be of value separately, but it does make me wonder whether separating out each historic game in some way (up to a point)... | fig,ax = plt.subplots(figsize=(12, 3))
plot_partial_dependence(m, X_test_imp, ['total_points_pg_last_all',
'total_points_team_pg_last_all_opponent',
'total_points_pg_last_1'],
grid_resolution=20, ax=ax); | _____no_output_____ | MIT | notebooks/02_fpl_predict_random_forest.ipynb | aneesh2606/fpl-prediction |
Heikin-Ashi PSAR Strategy_Roshan Mahes_ In this tutorial, we implement the so-called _Parabolic Stop and Reverse (PSAR)_ strategy. Given any stock, currency or commodity, this indicator tells us whether to buy or sell the stock at any given time. The momentum strategy is based on the open, high, low and close price fo... | %pip install pandas
%pip install yfinance
%pip install plotly | Requirement already satisfied: pandas in c:\programdata\anaconda3\lib\site-packages (1.0.5)
Requirement already satisfied: python-dateutil>=2.6.1 in c:\programdata\anaconda3\lib\site-packages (from pandas) (2.8.1)
Requirement already satisfied: pytz>=2017.2 in c:\programdata\anaconda3\lib\site-packages (from pandas) (2... | MIT | PSAR Strategy.ipynb | Roshanmahes/Quant-Finance |
Now we can import the following modules: | import os
import pandas as pd
import yfinance as yf
import plotly.graph_objects as go | _____no_output_____ | MIT | PSAR Strategy.ipynb | Roshanmahes/Quant-Finance |
This strategy works on any stock. In this notebook, we take the stock of Apple, represented by the ticker symbol AAPL. Let's download the pricing data and plot a (Japanese) candlestick chart: | symbol = 'AAPL'
df = yf.download(symbol, start='2020-01-01')
df.index = df.index.strftime('%Y-%m-%d') # format index as dates only
candles = go.Candlestick(x=df.index, open=df.Open, high=df.High, low=df.Low, close=df.Close)
# plot figure
fig = go.Figure(candles)
fig.layout.xaxis.type = 'category' # remove weekend day... | [*********************100%***********************] 1 of 1 completed
| MIT | PSAR Strategy.ipynb | Roshanmahes/Quant-Finance |
The PSAR IndicatorThe _Parabolic Stop and Reverse (PSAR) indicator,_ developed by J. Wells Wilder, is a momentum indicator used by traders to determine trend direction and potential reversals in price. It is a trend-following (lagging) indicator that uses a trailing stop and reverse method called SAR (Stop and Reverse... | def PSAR(df, alpha_start=0.01):
"""
Returns the dataframe with the given PSAR indicator for each time period.
"""
trend = 0
alpha = alpha_start
SAR = [df['Open'][0]] + [0] * (len(df) - 1)
isUpTrend = lambda x: x > 0
trendSwitch = lambda x: abs(x) == 1
# initialisation
i... | _____no_output_____ | MIT | PSAR Strategy.ipynb | Roshanmahes/Quant-Finance |
After applying the PSAR strategy on Apple's stock, we end up with the following trading decisions: | # apply PSAR
df = PSAR(df)
# extract trend switches (buying/selling advice)
buy = df.loc[df['Signal'] == 1]
sell = df.loc[df['Signal'] == -1]
# candles & psar
candles = go.Candlestick(x=df.index, open=df.Open, high=df.High, low=df.Low, close=df.Close, name='candles')
psar = go.Scatter(x=df.index, y=df['SAR'], mode='m... | _____no_output_____ | MIT | PSAR Strategy.ipynb | Roshanmahes/Quant-Finance |
We see that most of the times our indicator predicted a correct trend! Instead of using the open, high, low and close data, represented by this traditional candlestick chart, we can also apply the PSAR strategy on so-called _Heikin-Ashi charts_. Heikin-Ashi Charts_Heikin-Ashi_ means 'average bar' in Japanese. Heikin-As... | def heikin_ashi(df):
"""
Converts a dataframe according to the Heikin-Ashi.
"""
df_HA = pd.DataFrame(index=df.index, columns=['Open', 'High', 'Low', 'Close'])
df_HA['Open'][0] = df['Open'][0]
df_HA['Close'] = (df['Open'] + df['High'] + df['Low'] + df['Close']) / 4
for t in ran... | _____no_output_____ | MIT | PSAR Strategy.ipynb | Roshanmahes/Quant-Finance |
Let's convert the Apple's (Japanese) candlestick chart to a Heikin-Ashi chart: | df_HA = heikin_ashi(df)
candle = go.Candlestick(x=df_HA.index, open=df_HA['Open'], high=df_HA['High'], low=df_HA['Low'], close=df_HA['Close'])
# plot figure
fig = go.Figure(candle)
fig.layout.xaxis.type = 'category' # remove weekend days
fig.layout.xaxis.dtick = 20 # show x-axis ticker once a month
fig.layout.xaxis.ra... | _____no_output_____ | MIT | PSAR Strategy.ipynb | Roshanmahes/Quant-Finance |
As we can see, the Heikin-Ashi technique can be used to identify a trend more easily. Because the Heikin-Ashi technique smooths price information over two periods, it makes trends, price patterns, and reversal points easier to spot. Candles on a traditional candlestick chart frequently change from up to down, which can... | # apply PSAR
df = PSAR(df_HA)
# extract trend switches (buying/selling advice)
buy = df.loc[df['Signal'] == 1]
sell = df.loc[df['Signal'] == -1]
# candles & psar
candles = go.Candlestick(x=df.index, open=df.Open, high=df.High, low=df.Low, close=df.Close, name='candles')
psar = go.Scatter(x=df.index, y=df['SAR'], mode... | _____no_output_____ | MIT | PSAR Strategy.ipynb | Roshanmahes/Quant-Finance |
1. Introduction to pyLHD
pyLHD is a python implementation of the R package [LHD](https://cran.r-project.org/web/packages/LHD/index.html) by Hongzhi Wang, Qian Xiao, Abhyuday Mandal. As of now, only the algebraic construction of Latin hypercube designs (LHD) are implemented in this package. For search algorithms to co... | import pyLHD as pl | _____no_output_____ | MIT | examples/notebooks/intro_pyLHD.ipynb | toledo60/pyLHD |
Lets start by generating a random LHD with 5 rows and 3 columns | X = pl.rLHD(nrows=5,ncols=3)
X | _____no_output_____ | MIT | examples/notebooks/intro_pyLHD.ipynb | toledo60/pyLHD |
We evaluate the above design with the different optimamlity criteria described earlier:
The maximin distance criterion (Manhattan) | pl.phi_p(X,p=15,q=1) # using default parameters | _____no_output_____ | MIT | examples/notebooks/intro_pyLHD.ipynb | toledo60/pyLHD |
The maximin distance criterion (Euclidean) | pl.phi_p(X,p=10,q=2) # different p used than above | _____no_output_____ | MIT | examples/notebooks/intro_pyLHD.ipynb | toledo60/pyLHD |
The average absolute correlation | pl.AvgAbsCor(X) | _____no_output_____ | MIT | examples/notebooks/intro_pyLHD.ipynb | toledo60/pyLHD |
The maximum absolute correlation | pl.MaxAbsCor(X) | _____no_output_____ | MIT | examples/notebooks/intro_pyLHD.ipynb | toledo60/pyLHD |
The maximum projection criterion | pl.MaxProCriterion(X) | _____no_output_____ | MIT | examples/notebooks/intro_pyLHD.ipynb | toledo60/pyLHD |
We can apply Williams transformation on X defined as:
$$
W(x) = \begin{cases}
2x & 0 \leq x \leq (p-1)/2 \\
2(p-x)-1 & (p+1)/2 \leq x \leq p-1
\end{cases}
$$ | W_x = pl.williams_transform(X)
W_x | _____no_output_____ | MIT | examples/notebooks/intro_pyLHD.ipynb | toledo60/pyLHD |
Lets evaluate the new transformed design | pl.phi_p(W_x) | _____no_output_____ | MIT | examples/notebooks/intro_pyLHD.ipynb | toledo60/pyLHD |
The $\phi_p$ value of transformed $W_x$ is smaller than the original design $X$ 2. Algebraic Construction Functions
The algebraic construction methods are demonstrated in the table below | | Ye98 | Cioppa07 | Sun10 | Tang93 | Lin09 | Butler01 |
|------------|---|---|---|---|---|----|
| Run $n$ | $2^m ... | Ye98 = pl.OLHD_Ye98(m=4)
Ye98
pl.MaxAbsCor(Ye98) # column-wise correlation are 0 | _____no_output_____ | MIT | examples/notebooks/intro_pyLHD.ipynb | toledo60/pyLHD |
Cioppa and Lucas 2007 construction, the resulting design will be a $2^m+1$ by $m+ {m-1 \choose 2}$ orthogonal LHD. Note $m \geq 2$ | Cioppa07 = pl.OLHD_Cioppa07(m=3)
Cioppa07
pl.MaxAbsCor(Cioppa07) # column-wise correlation are 0 | _____no_output_____ | MIT | examples/notebooks/intro_pyLHD.ipynb | toledo60/pyLHD |
Sun et al. 2010 construction, the resulting design will be $r2^{c+1}$ by $2^c$ if type='even'. If type='odd'
the resulting design will be $r2^{c+1} + 1$ by $2^c$, where $r$ and $c$ are positive integers. | Sun10_odd = pl.OLHD_Sun10(C=2,r=2,type='odd')
Sun10_odd
Sun10_even = pl.OLHD_Sun10(C=2,r=2,type='even')
Sun10_even | _____no_output_____ | MIT | examples/notebooks/intro_pyLHD.ipynb | toledo60/pyLHD |
Line et al. 2009 construction, the resulting design will be $n^2$ by $2fp$. This is obtained by using a
$n$ by $p$ orthogonal LHD with a $n^2$ by $2f$ strength 2 and level $n$ orthogonal array.
Start by generating an orthogonal LHD | OLHD_example = pl.OLHD_Cioppa07(m=2) | _____no_output_____ | MIT | examples/notebooks/intro_pyLHD.ipynb | toledo60/pyLHD |
Next, create an orthogonal array with 25 rows, 6 columns, 5 levels, and strength 2 OA(25,6,5,2) | import numpy as np
OA_example = np.array([[2,2,2,2,2,1],[2,1,5,4,3,5],
[3,2,1,5,4,5],[1,5,4,3,2,5],
[4,1,3,5,2,3],[1,2,3,4,5,2],
[1,3,5,2,4,3],[1,1,1,1,1,1],
[4,3,2,1,5,5],[5,5,5,5,5,1],
[4,4,4,4,4,1],[... | _____no_output_____ | MIT | examples/notebooks/intro_pyLHD.ipynb | toledo60/pyLHD |
Now using Lin at al. 2009 construction, we couple OLHD and OA to obtain | Lin09 = pl.OLHD_Lin09(OLHD=OLHD_example,OA=OA_example)
Lin09 | _____no_output_____ | MIT | examples/notebooks/intro_pyLHD.ipynb | toledo60/pyLHD |
We can convert an orthogonal array into a LHD using the function OA2LHD. Consider the
earlier OA_example with 25 rows and 6 columns. | pl.OA2LHD(OA_example) | _____no_output_____ | MIT | examples/notebooks/intro_pyLHD.ipynb | toledo60/pyLHD |
Lastly, we consider Butler 2001 construction by generating a $n$ by $k$ OLHD | Butler01 = pl.OLHD_Butler01(nrows=11,ncols=5)
Butler01 | _____no_output_____ | MIT | examples/notebooks/intro_pyLHD.ipynb | toledo60/pyLHD |
Update the Human Proteome Reference File and KinPred Final DataThis notebook shows the steps to upgrade from 2019-12-12 to 2020-2-26 reference humam proteome, and update the KinPred final data with the new reference human proteome. | # IMPORTS
import pandas as pd
import os
import sys
sys.path.append('../PreprocessingPredictionData/')
import humanProteomesReference
##################
# File Location #
##################
# local (../../)
base = '../../'
#####################
# Defining File Dir #
#####################
# Human Proteome fasta file di... | _____no_output_____ | MIT | Code/UpdatingResourceData/UpdateHumanProteomeVersion.ipynb | NaegleLab/KinPred |
Download the updated (new) version of Human Proteome fasta file | # Downloads the updated Human Proteomes (canonical) from Unipro.org
# saves as fasta formate at the given dir/name + last sequence modification date.
humanProteomesReference.downloadHumanProteomes(new_HP_fasta)
# Convert the input fasta file into a dataframe
# saves as csv formate at the given dir/name + last sequence... | _____no_output_____ | MIT | Code/UpdatingResourceData/UpdateHumanProteomeVersion.ipynb | NaegleLab/KinPred |
Compare the Current (old) version and the Updated (new) version- get a list of uniportIDs from the current (old) human proteome referece file that become obsolet/secondary in the updated (new) human proteome referece file- get a list of uniportIDs from the updated (new) human proteome referece file that have different... | df_old = pd.read_csv(old_HP_csv, usecols = ['UniprotID', 'sequence'], sep = '\t')
df_new = pd.read_csv(new_HP_csv, usecols = ['UniprotID', 'sequence'], sep = '\t')
common_acc = df_old.merge(df_new, on=['UniprotID'])
common_seq = df_old.merge(df_new, on=['UniprotID' , 'sequence'])
old_id = df_old[(~df_old.UniprotID.is... | Outdated Protein UniprotIDs:
UniprotID
1103 Q9UGB4
16384 Q5JT78
Protein UniprotIDs with Sequence Modifacation:
UniprotID
1873 Q96LP2
8355 Q6DHV5
10813 Q9UN66
11600 P19013
17838 P0C617
19253 Q8N4F4
19605 O75123
20283 A6QL64
| MIT | Code/UpdatingResourceData/UpdateHumanProteomeVersion.ipynb | NaegleLab/KinPred |
- download the fasta file of the Protein UniprotIDs with Sequence Modifacation | humanProteomesReference.downloadFasta (new_seq, seq_mod_fasta) | _____no_output_____ | MIT | Code/UpdatingResourceData/UpdateHumanProteomeVersion.ipynb | NaegleLab/KinPred |
Re-run predictions of the Protein UniprotIDs with Sequence Modifacation in each predictorPlease see the `Get Results` section in [FormattingPhosphoPICK.ipynb](https://github.com/NaegleLab/KinPred/blob/master/Code/PreprocessingPredictionData/FormattingPhosphoPICK.ipynb), [FormattingGPS.ipynb](https://github.com/NaegleL... | # IMPORTS
sys.path.append('../PreprocessingPredictionData/')
import gps_convert, phosphoPick_convert, networKin_convert
#####################
# Defining File Dir #
#####################
# Resource Files
SubstrateMap = base + 'Data/Map/globalSubstrateMap.csv' # add all unique substrate in HPRD to th... | _____no_output_____ | MIT | Code/UpdatingResourceData/UpdateHumanProteomeVersion.ipynb | NaegleLab/KinPred |
**Remove outdated data** of the above outdated Protein UniprotIDs and Protein UniprotIDs with Sequence Modifacation from each prediction data of each predictor | # append old_id and new_seq together
rm_id = pd.concat([old_id, new_seq]).reset_index(drop = True)
rm_id
def rmOutdated (predictor_old, predictor_new, rm_id_df):
for chunk in pd.read_csv(predictor_old, chunksize = 1000000):
chunk = chunk[~chunk.substrate_acc.isin(rm_id_df.UniprotID)]
if not os.path... | _____no_output_____ | MIT | Code/UpdatingResourceData/UpdateHumanProteomeVersion.ipynb | NaegleLab/KinPred |
- **GPS** | rmOutdated(gps_old, gps_new, rm_id) | _____no_output_____ | MIT | Code/UpdatingResourceData/UpdateHumanProteomeVersion.ipynb | NaegleLab/KinPred |
- **PhosphoPICK** | rmOutdated(pick_old, pick_new, rm_id) | _____no_output_____ | MIT | Code/UpdatingResourceData/UpdateHumanProteomeVersion.ipynb | NaegleLab/KinPred |
- **NetworKIN** | rmOutdated(kin_old, kin_new, rm_id) | _____no_output_____ | MIT | Code/UpdatingResourceData/UpdateHumanProteomeVersion.ipynb | NaegleLab/KinPred |
**Process the rerunned predictions** of each predictor | #get Gene Name(substrate) from the globalSubstrateMap.csv
df_unique_sub = pd.read_csv(SubstrateMap, usecols = ['Gene Name','UniprotID'])
#get Kinase Name from the globalKinaseMap.csv
df_unique_kin = pd.read_csv(KinaseMap, usecols = ['Kinase Name','UniprotID'])
def addNameCol (perdictor_df):
# add Gene Name (subst... | _____no_output_____ | MIT | Code/UpdatingResourceData/UpdateHumanProteomeVersion.ipynb | NaegleLab/KinPred |
- **GPS** | # convert substrate_acc and kinase_acc
convert_type = 'acc'
gps_convert.gps_convert_directory(gps_update_dir, gps_kinase, gps_temp_dir_acc_update, convert_type)
# map the site to the updated (new) human proteome reference
convert_type = 'site'
gps_convert.gps_convert_directory(gps_temp_dir_acc_update, new_HP_csv, gps_t... | _____no_output_____ | MIT | Code/UpdatingResourceData/UpdateHumanProteomeVersion.ipynb | NaegleLab/KinPred |
- **PhosphoPICK** | # convert substrate_acc and kinase_acc
convert_type = 'acc'
phosphoPick_convert.pick_convert_directory(pick_update_dir, 'na', pick_temp_dir_acc_update, convert_type)
# map the site to the updated (new) human proteome reference
convert_type = 'site'
phosphoPick_convert.pick_convert_directory(pick_temp_dir_acc_update, ne... | _____no_output_____ | MIT | Code/UpdatingResourceData/UpdateHumanProteomeVersion.ipynb | NaegleLab/KinPred |
- **NetworKIN** | # convert substrate_acc and kinase_acc
convert_type = 'acc'
networKin_convert.kin_convert_directory(kin_update_dir, 'na', kin_temp_dir_acc_update, convert_type)
# map the site to the updated (new) human proteome reference
convert_type = 'site'
networKin_convert.kin_convert_directory(kin_temp_dir_acc_update, new_HP_csv,... | _____no_output_____ | MIT | Code/UpdatingResourceData/UpdateHumanProteomeVersion.ipynb | NaegleLab/KinPred |
**Append the rerunned predictions** of each predictor to the prediction files and save as the updated prediction files with version date | def appendUpdates(predictor_new, update_df):
update_df = rm_unmatched_kinase_type(update_df)
update_df.to_csv(predictor_new, mode='a', index = False, header=False) | _____no_output_____ | MIT | Code/UpdatingResourceData/UpdateHumanProteomeVersion.ipynb | NaegleLab/KinPred |
- **GPS** | appendUpdates(gps_new, df_gps_update) | _____no_output_____ | MIT | Code/UpdatingResourceData/UpdateHumanProteomeVersion.ipynb | NaegleLab/KinPred |
- **PhosphoPICK** | appendUpdates(pick_new, df_pick_update) | _____no_output_____ | MIT | Code/UpdatingResourceData/UpdateHumanProteomeVersion.ipynb | NaegleLab/KinPred |
- **NetworKIN** | appendUpdates(kin_new, df_kin_update) | _____no_output_____ | MIT | Code/UpdatingResourceData/UpdateHumanProteomeVersion.ipynb | NaegleLab/KinPred |
Cross Referencing with ProteomeScout Phosphorylation Datasee [CrossReferenceWithProteomeScout.ipynb](https://github.com/NaegleLab/KinPred/blob/master/Code/CrossReferenceWithProteomeScout/CrossReferenceWithProteomeScout.ipynb) for detail | # IMPORTS
sys.path.append('../CrossReferenceWithProteomeScout/')
import XRefProteomeScout
from datetime import date
# version date
pscout_version = date.today().strftime('%Y-%m-%d')
# file location
ref_proteome = base+"Data/Raw/HumanProteome/humanProteome_"+ref_version+".fasta"
pscout_data = base+'Data/Raw/ProteomeSco... | _____no_output_____ | MIT | Code/UpdatingResourceData/UpdateHumanProteomeVersion.ipynb | NaegleLab/KinPred |
Now in log | B = np.log10(A)
sns.distplot(B)
j, h, k = np.percentile(B, [16, 50, 84])
sns.distplot(B)
plt.axvline(j, ls='--')
plt.axvline(h)
plt.axvline(k, ls='--')
print(f'The median of A is: {b:.2f}')
print(f'The median of B is: {h:.2f}, and 10^{h:.2f} is: {10**h:.2f}') | The median of A is: 10.01
The median of B is: 1.00, and 10^1.00 is: 10.01
| MIT | code/scripts/Old_Checks/logchecks.ipynb | ojhall94/malatium |
Introduction: Forecast for SEAIRQ model with stochastic parameters In this notebook, we consider the SEAIRQ model. We assume that the parameters * $\beta$ (probability of infection on contact),* $\gamma_{E}$ (rate of progression for exposed individual to class A), * $\gamma_{AA}$ (rate of progression from class A to a... | M = 1 # the SEAIRQ model we consider has no age structure
Ni = 50000*np.ones(M) # so there is only one age group
N = np.sum(Ni) # and the total population is the size of this age group
E0 = np.array([0])
A0 = np.array([1])
Ia0 = np.array([0]) # the SEAIRQ model we consider has only o... | _____no_output_____ | MIT | examples/forecast/ex03 - SEAIRQ.ipynb | hidekb/pyross |
Forecast based on deterministic model | result = model_forecast.simulate(S0, E0, A0, Ia0, Is0, Q0,
contactMatrix, Tf, Nt,
verbose=True,
Ns=Ns)
plot_trajectories(result,
plot_index = 2,
percentile=5,
)
plot_trajecto... | Finished. Time needed for evaluation: 00:00:05
| MIT | examples/forecast/ex03 - SEAIRQ.ipynb | hidekb/pyross |
Notas: - Probar configuraciones 6, 7, 8 y 9. - Comparar mejor resultado con notebook placescnn_v2.1 - Probar configuraciones desfrizando bloques convolutivos de la red | model.fit_from_generator(path=f'{dataset_path}/{dataset}',
train_generator=train_generator, validation_generator=validation_generator,
test_generator=test_generator,
evaluate_net=False, use_model_check_point=True, use_early_stop=True, weighted=... | _____no_output_____ | MIT | notebooks/PlacesCNN_v3.2.experiment_4.ipynb | ifranco14/tf_real_estate_images_classification |
longtail> API details. | #export
import os
from collections import namedtuple
from longtail.engine import BlockTracker
from longtail.commonlib import waste_some_time, lastWrapper, capture
from longtail.transplier import Transpiler
#hide
tr = Transpiler(".","test/src/basic.txt","test/transpile/basic.py")
tr.parse()
!open .
#hide
!python tes... | _____no_output_____ | Apache-2.0 | 04_webserver.ipynb | ArthurConner/midtail |
NEXUS tool: case study for the Souss-Massa basin - energy demand calculationsIn this notebook a case study for the Souss-Massa basin is covered using the `nexustool` package. The water requirements for agricultural irrigation and domestic use were previously calculated using the Water Evaluation and Planning System (... | import sys
sys.path.append("..") #this is to add the avobe folder to the package directory
import os
import nexustool
import pandas as pd
from dashboard.scripts.plotting import water_delivered_plot, unmet_demand_plot, water_supply_plot, wtd_plot, energy_demand_plot, crop_production | _____no_output_____ | MIT | Morocco model/Energy calculations.ipynb | KTH-dESA/FAO |
1. Read scenario dataAfter importing all required packages, the input GIS data is loaded into the variable `df`. Change the `data_folder`, `scenario` and `climate` variables to reflect the name and relative location of your data file. This dataset should already have the water demand for irrigation results. | data_folder = os.path.join('data', 'processed results')
scenario = 'Desalination'
climate = 'Climate Change'
input_folder = os.path.join(data_folder, scenario, climate) | _____no_output_____ | MIT | Morocco model/Energy calculations.ipynb | KTH-dESA/FAO |
2. Create nexus model To create a model simply create an instance of the `nexustool.Model()` class and store it in a variable name. The `nexustool.Model()` class requires a dataframe as input data. Several other properties and parameter values can be defined by explicitly passing values to them. To see a full list of ... | #Define the path to read the scenario input data and reads it in
file_path = os.path.join(input_folder, 'demand_data.gz')
df = pd.read_csv(file_path)
#Creates the nexus model with the input dataframe
souss_massa = nexustool.Model(df) | _____no_output_____ | MIT | Morocco model/Energy calculations.ipynb | KTH-dESA/FAO |
3. Define variable namesThe names of the properties of the model can be changed at any time. This is important for the model to know how each property is called withing your input data. To check the current property names run the `.print_properties()` method, a list with the names of each property and its current valu... | souss_massa.elevation_diff = 'elevation_diff' #for the case of GW, the elevation_diff is set to be the wtd
souss_massa.L = 'distance' #for the case of GW, the distance is set to be the wtd
souss_massa.D = 'Pipe_diameter'
#Defines the name of the variable for Peak Water Demand and Seasonal Scheme Water demand (monthly)... | _____no_output_____ | MIT | Morocco model/Energy calculations.ipynb | KTH-dESA/FAO |
4. Define pipelines diameters and average pumping hours, pumping efficiencyNow we need to define the specifications of the water network, giving pipeline / canal diameter values: | souss_massa.df['Pipe_diameter'] = 1.2
souss_massa.df.loc[souss_massa.df['type'].str.contains('GW'), 'Pipe_diameter'] = 1000
souss_massa.df.loc[souss_massa.df['type'].str.contains('DS'), 'Pipe_diameter'] = 1.2
souss_massa.df.loc[souss_massa.df['type'].str.contains('Pipeline'), 'Pipe_diameter'] = 1.2
souss_massa.pumping... | _____no_output_____ | MIT | Morocco model/Energy calculations.ipynb | KTH-dESA/FAO |
5. Peak Water Demand (PWD)The $PWD$ is definfe as the daily peak cubic meters of water pumped per second withing the month. To accomplish that, the $SSWD$ (m3/month) is divided by 30 days per month, 3600 seconds per hour and the amount of average pumping hours in a day. This provides the $PWD$ in m3/s:$$PWD\,(m^3/s) =... | #Defines the PWD. It is defined as double the seasonal demand for agricultural sites
souss_massa.df[souss_massa.pwd] = souss_massa.df[souss_massa.sswd] / 30 / souss_massa.pumping_hours_per_day / 3600 #to convert to cubic meter per second [m3/s]
souss_massa.df.loc[souss_massa.df['type']=='Agriculture', souss_massa.pwd] ... | _____no_output_____ | MIT | Morocco model/Energy calculations.ipynb | KTH-dESA/FAO |
6. Calculate pumping energy requirementsTo estimate the pumping energy requirements for conveyance, first we need to calculate the Total Dinamic Head (TDH). This, is a measure in meters that accounts for the elevation difference between two points and the pressure loss in distribution.For that, the area $A$ `.pipe_are... | souss_massa.pipe_area()
souss_massa.flow_velocity()
souss_massa.reynolds()
souss_massa.friction_factor() | _____no_output_____ | MIT | Morocco model/Energy calculations.ipynb | KTH-dESA/FAO |
Then, the TDH can be calculated by simply calling the `.get_tdh()` function.$$TDH\,(m) = f\cdot \frac{L\,(m)}{D\,(m)}\cdot \frac{V(m/s)^2}{2\cdot g\,(m/s^2)}$$Whereas the conveyance pumping energy requirements by calling the `.get_pumping_energy()` method. The equation used to calculate the Electricity Demand ($E_D$) f... | souss_massa.get_tdh()
souss_massa.get_pumping_energy()
souss_massa.df.loc[souss_massa.df.pp_e<0, souss_massa.pp_e] = 0 # ensures no negative energy values are considered
souss_massa.df.loc[souss_massa.df.pa_e<0, souss_massa.pa_e] = 0 # ensures no negative power values are considered
# We exclude energy for pumping ca... | _____no_output_____ | MIT | Morocco model/Energy calculations.ipynb | KTH-dESA/FAO |
7. Calculating desalination energy requirementsDesalination energy requirements are estimated by multipliying the monthly average desalinated water (`sswd`), by an energy intensity factor (`desal_energy_int`) based on the characteristics of the desalination plant. | #Define energy intensity for seawater desalination project
desal_energy_int = 3.31 # kWh/m3
#Create a new nexus Model with the data relevant to the desalination plant only, filtering by the key work DS (Desalination)
sm_desal = nexustool.Model(souss_massa.df.loc[souss_massa.df['type'].str.contains('DS')].copy())
#Mul... | _____no_output_____ | MIT | Morocco model/Energy calculations.ipynb | KTH-dESA/FAO |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.