How can I make the trailing sell move up with price and not go down when price reverse without using the high of the current candle in PineScript - trailing

How can I make the trailing sell move up with price and not go down when price reverse without using the high of the current candle in PineScript
//#version=4
study("Trailing Sell ", overlay=true)
//--------------------------------------------TRAILING SELL-------------------------------------------
//TRAILING SELL LINE
show_drop_labels = input(true, title="Show Labels Trailing Below")
trailing_sell_offset = input(-0.2, title="Red Trailing Sell Line % Set Above Current Price", maxval=100, step=0.1)
src = close // should trail up behind current price and not the candle(high). should trail up and stop if price reverse.
sumbars2 = 1
color_sell = color.red
per_calc = (sum(src,sumbars2)/sumbars2)*(1+(trailing_sell_offset/100))
trailing_sell_line = line.new(x1=bar_index, y1=per_calc,
x2=bar_index[13], y2=per_calc, width=1, color=color_sell)
line.set_extend(trailing_sell_line, extend.none)
line.delete(trailing_sell_line[1])
//TRAILING SELL LABEL
var line l12 = na
if show_drop_labels
label trailing_sell_label = label.new(bar_index[12] , per_calc, "Trailing Sell Line", textcolor=color.white, style=label.style_label_right, color=color_sell, size=size.tiny )
line.delete(l12[1])
label.delete(trailing_sell_label[1])

Related

using regex in python to return line and some lines are skipped

I am new to Python and programming in general. My code gets data from a pdf. Then iterates over the returned lines to pull only lines meeting a regex expression. Most lines have data in the next line that need to be added to the current line which is being iterated over. The code I wrote does this successfully except that lines that do not have data in the next line to be added, returns the current line but skips the very next line.
What can I add or change to make sure that it does not skip the line.
An example of the lines that need to be iterated over are:
#Input text
CATS THIRD PARTY PAYMENT 1,664.58 0320 2,130.05
MUTUAL/IBS /GAL /0000010318908
IB TRANSFER TO 2,000.00- 0323 130.05
578441575425 10H32 28662338
FEE-INTER ACCOUNT TRANSFER ## 5.50- 0323 124.55
8419752
IB PAYMENT FROM 9,000.00 0325 9,124.55
JENNIFER LIVINGSTONE
IB PAYMENT FROM 1,000.00 0401 10,124.55
JENNIFER LIVINGSTONE
MONTHLY MANAGEMENT FEE ## 21.00- 0331 10,103.55 (This line has no description in the following line)
CREDIT TRANSFER 9,000.00 0401 19,103.55 (This line gets skipped)
ABSA BANK rent
IB TRANSFER TO 19,000.00- 0403 103.55
578441575425 11H45 286623383
bpdf = 'test pdf.pdf'
with pdfplumber.open(bpdf) as pdf:
page = pdf.pages[0]
text = page.extract_text()
print(text)
new_trn_line = re.compile(r'(\D+)(\d.*) (\d.*) (\d.*\.\d{2})')
def transactions(sentences):
for lines in sentences.split('\n'):
yield lines
my_list = transactions(text)
my_data = []
for each_line in my_list:
if new_trn_line.search(each_line):
my_next_line = next(my_list)
if not new_trn_line.search(my_next_line):
my_data.append(new_trn_line.search(each_line).group(1) + my_next_line + " " +
new_trn_line.search(each_line).group(2) + " " + new_trn_line.search(each_line).group(3))
elif re.search(new_trn_line,text):
my_data.append(each_line)
else:
continue
my_data
#Output
['CATS THIRD PARTY PAYMENT MUTUAL/IBS /GAL /0000010318908 1,664.58 0320',
'IB TRANSFER TO 578441575425 10H32 286623383 2,000.00- 0323',
'FEE-INTER ACCOUNT TRANSFER ## 8419752 5.50- 0323',
'IB PAYMENT FROM JENNIFER LIVINGSTONE 9,000.00 0325',
'IB PAYMENT FROM JENNIFER LIVINGSTONE 1,000.00 0401',
'MONTHLY MANAGEMENT FEE ## 21.00- 0331 10,103.55',
'IB TRANSFER TO 578441575425 11H45 286623383 19,000.00- 0403'\]
If you compare it to the input you will see CREDIT TRANSFER 9,000.00 0401 19,103.55 gets skipped
Your current pattern would not match (\D+)(\d.*) (\d.*) (\d.\*.\d{2}) as \* matches an asterix which is not in the example data.
If you have read the whole text from the .pdf, perhaps you could use a single pattern with capture groups, and assemble the results.
The pattern matches
^ Start of string
([^\d\n]+) Capture group 1 Match 1+ chars other than digits or newlines
(\d[\d,.-]* \d+) Capture group 2 Match a digit followed by optional repetitions of digits, comma's, dots or a hyphen. Then match a space and 1+ digits
\d[\d,.]*\.\d{2} match a digit followed by digits, comma's and dots and then match . followed by 2 digits
( Capture group 3
(?: Non capture group to repeat as a whole part
\n(?!.*\b\d[\d,.]*\.\d{2}$) Assert that the line does not end on a digit with a decimal part having a dot and 2 digits
.* Match the whole line
)* close the non capture group and optionally repeat to also match just a single previous line
) Close group 3
See a regex101 demo
import re
pattern = r"^([^\d\n]+)(\d[\d,.-]* \d+) \d[\d,.]*\.\d{2}((?:\n(?!.*\b\d[\d,.]*\.\d{2}$).*)*)"
my_data = []
text = ("CATS THIRD PARTY PAYMENT 1,664.58 0320 2,130.05\n"
"MUTUAL/IBS /GAL /0000010318908\n"
"IB TRANSFER TO 2,000.00- 0323 130.05\n"
"578441575425 10H32 28662338\n"
"FEE-INTER ACCOUNT TRANSFER ## 5.50- 0323 124.55\n"
"8419752\n"
"IB PAYMENT FROM 9,000.00 0325 9,124.55\n"
"JENNIFER LIVINGSTONE\n"
"IB PAYMENT FROM 1,000.00 0401 10,124.55\n"
"JENNIFER LIVINGSTONE\n"
"MONTHLY MANAGEMENT FEE ## 21.00- 0331 10,103.55\n"
"CREDIT TRANSFER 9,000.00 0401 19,103.55\n"
"ABSA BANK rent\n"
"IB TRANSFER TO 19,000.00- 0403 103.55\n"
"578441575425 11H45 286623383")
matches = re.finditer(pattern, text, re.MULTILINE)
for _, match in enumerate(matches):
my_data.append(f"{match.group(1)}{match.group(3).strip()} {match.group(2)}")
print(my_data)
Note sure why in your example output only MONTHLY MANAGEMENT FEE ends with 10,103.55 because all the other output lines seems to end with 4 digits.
Output
[
'CATS THIRD PARTY PAYMENT MUTUAL/IBS /GAL /0000010318908 1,664.58 0320',
'IB TRANSFER TO 578441575425 10H32 28662338 2,000.00- 0323',
'FEE-INTER ACCOUNT TRANSFER ## 8419752 5.50- 0323',
'IB PAYMENT FROM JENNIFER LIVINGSTONE 9,000.00 0325',
'IB PAYMENT FROM JENNIFER LIVINGSTONE 1,000.00 0401',
'MONTHLY MANAGEMENT FEE ## 21.00- 0331',
'CREDIT TRANSFER ABSA BANK rent 9,000.00 0401',
'IB TRANSFER TO 578441575425 11H45 286623383 19,000.00- 0403'
]

Compare QuantLib bond pricing with Excel functions YIELD and PRICE when doing stress testing

I calculated bond price and stressed bond price (shocking up yield) in both Excel and Python Quantlib. As the following table shows, weird results were generated: base bond price matches well between Excel and Quantlib but the stressed bond prices have more gaps (1.5% relative difference). Yields also show some gaps.
Can you please provide some comments?
Excel Code:
Base Bond Price=PRICE("2021-8-19","2025-8-19",4.5%,YIELD("2021-8-19","2025-8-
19",4.5%,95,100,4,0),100,4,0)
Stress Bond Price=PRICE("2021-8-19","2025-8-19",4.5%,YIELD("2021-8-19","2025-8-
19",4.5%,95,100,4,0)+662/10000,100,4,0)
Python code:
import datetime
import QuantLib as ql
settlement_date = ql.Date(19,8,2021)
valuation_date = ql.Date(19,8,2021)
issue_date = ql.Date(19,8,2021)
maturity_date = ql.Date(19,8,2025)
tenor = ql.Period(4)
calendar = ql.UnitedStates()
business_convention = ql.Following
date_generation = ql.DateGeneration.Backward
end_month = False
face_value = 100
coupon_rate = 450/10000
day_count = ql.Thirty360(ql.Thirty360.USA)
redemption_value = 100
schedule = ql.Schedule(issue_date, maturity_date, tenor, calendar, business_convention, business_convention, date_generation, end_month)
bond = ql.FixedRateBond(settlement_date-valuation_date, face_value, schedule, [coupon_rate], day_count, business_convention, redemption_value, issue_date)
target_price = 95
bond_yield = bond.bondYield(target_price, day_count, ql.Compounded, 4, ql.Date(), 1.0e-8,1000)
bond_price = bond.cleanPrice(bond_yield, day_count, ql.Compounded, 4)
STRESS = 662
stress_bond_yield = bond_yield+STRESS/10000
stress_bond_price = bond.cleanPrice(stress_bond_yield, day_count, ql.Compounded, 4)
excel_base_bond_price = 99.50
excel_stress_bond_price = 75.02971569
print('Base bond price from excel is', excel_base_bond_price )
print('Base bond price from Quantlib is', bond_price)
print('Stressed bond price from excel is',excel_stress_bond_price)
print('Stressed bond price from Quantlib is',stress_bond_price)
You need to add
ql.Settings.instance().evaluationDate = valuation_date
before the calculation. If you don't do so, you'll be calculating the yield and price as of today instead of as of the valuation date. Once you do that, the yields and prices match a lot better.

Pine script - Security function not show correct on different timeframe

I'm newbie and try to get ichimoku data on 4 hour timeframe but it not showing the correct value when I shift.
//#version=4
study(title="test1", overlay=true)
conversionPeriods = input(9, minval=1, title="Conversion Line Length")
basePeriods = input(26, minval=1, title="Base Line Length")
laggingSpan2Periods = input(52, minval=1, title="Leading Span B Length")
displacement = input(26, minval=1, title="Displacement")
donchian_M240(len) => avg(security(syminfo.tickerid, 'D' , lowest(len)), security(syminfo.tickerid, 'D', highest(len)))
tenkanSen_M240 = donchian_M240(conversionPeriods)
kijunSen_M240 = donchian_M240(basePeriods)
senkoSpanA_M240 = avg(tenkanSen_M240, kijunSen_M240)
plot(senkoSpanA_M240[25], title="senkoSpanA_M240[25]")
The value senkoSpanA_M240[25] keep changing when I'm in M5, M15, M30, H1, H4 or D1.
Can you help please?
the reason it keeps changing when you change time frames is because you are using a historical bar reference [25] on your senkoSpanA_M240.
This means it will look for the senkoSpanA_M240 condition that occurred 25 bars ago.
Depending on which time frame you are selecting, it will look back 25 bars of that time frame and perform the calculation.
What exactly are you trying to achieve by using the [25]?

Python 3 formatting issue with '$'

I just started learning Python this week and I'm having an issue with some line formatting. I am trying to insert a '$' along with the calculated values, I've tried to insert the '$' with a new {} set, as well as here {{$:>{}.2f}} (based on Google search suggestions), however I keep getting errors.
I'm using Google Collab to run the code.
def budget_calc(money, rent, food, phone, gas, extra_income):
width = 35
price_width = 10
item_width = width - price_width
income = sum(weekly_income) + extra_income
expenses = sum(credit_cards) + rent + phone + food + gas + utilities
after_tax =income*0.84
#after_tax_instr = str(after_tax)
gross = 'Money before tax:' #+ str(income)
post_tax= 'Post tax income:' #+after_tax_instr
tax_payment ='Taxes due:' #+str(income*.16)
savings = after_tax - expenses
total = 'Money left over:' #+'$'+str(savings)
expense_total = 'Total expenses' #+str([expenses])
line = "{{:{}}} {{:>{}.2f}}".format(item_width, price_width)
print(line.format(gross, income))
print(line.format(tax_payment, (income*0.16)))
print(line.format(post_tax, after_tax))
print(line.format(expense_total, expenses))
print(line.format(total, savings))
The output I get is:
Money before tax: 3300.00
Taxes due: 528.00
Post tax income: 2772.00
Total expenses 2190.00
Money left over: 582.00
Days until my Mac: 44.36
I would appreciate any pointers in the right direction.
I think the error it throws will be keyerror and it because of the messy string format
def budget_calc(money, rent, food, phone, gas, extra_income):
width = 35
price_width = 10
item_width = width - price_width
income = sum(weekly_income) + extra_income
expenses = sum(credit_cards) + rent + phone + food + gas + utilities
after_tax =income*0.84
#after_tax_instr = str(after_tax)
gross = 'Money before tax:' #+ str(income)
post_tax= 'Post tax income:' #+after_tax_instr
tax_payment ='Taxes due:' #+str(income*.16)
savings = after_tax - expenses
total = 'Money left over:' #+'$'+str(savings)
expense_total = 'Total expenses' #+str([expenses])
# You can specify the width integer instead of formating
line = "{0:<25} ${1:.2f}"
print(line.format(gross, income))
print(line.format(tax_payment, (income*0.16)))
print(line.format(post_tax, after_tax))
print(line.format(expense_total, expenses))
print(line.format(total, savings))
Note : since weekly_income and credit_cards are not provided i just
removed it from script in order to check the output
When `budget_calc(33000,500,10,100,152,510)` this is called the output
Output :
Money before tax: $33510.00
Taxes due: $5361.60
Post tax income: $28148.40
Total expenses $762.00
Money left over: $27386.40
Python 3.6+ String interpolation is recommended way of string formatting because of its high readabililty.
The best way would be:
print(f'Money before tax: {income}')
print(f'Taxes due:{income*0.16}')
print(f'Post tax income: {after_tax}')
print(f'Total expenses: {expenses}')
print(f'Money left over :{savings}')
But if you want to use $ String Formatting only , the you should try the answer by DaVinci

Adding an integer after each printed line from dictonaries

I am learning how to program in Python 3 and I am working on a project that lets you buy a ticket to a movie. After that you can see your shopping cart with all the tickets that you have bought.
Now, I want after each printed line to add a integer.
For example: 1. Movie1 , 2. Movie2 , etc..
Here is my code that I use to print the films:
if choice == 3:
#try:
print("Daca doresti sa vezi ce filme sunt valabile, scrie exit.")
bilet = str(input("Ce film doresti sa vizionezi?: ").title())
pret = films[bilet]["price"]
cumperi = input("Doresti sa adaugi in cosul de cumparaturi {}$ (y/n)?".format(bilet)).strip().lower()
if cumperi == "y":
bani[0] -= pret
cos.append(bilet)
if choice == 4:
print (*cos, sep="\n")
You can use an integral variable and increase it's value whenever you perform a task.
example set count = 0 and when you does a task place this there count += 1.

Resources