シンプル移動平均に基づいて株式を購入するアルゴリズムがありますが、動的リストにパーセンテージを割り当てようとしています。Python:リストのすべての要素にパーセンテージを割り当てます。
たとえば、このアルゴリズムでは最初の1週間に4つの株式を購入することが許可されているため、リストは4つの要素、つまり["apple", "google", "tesla", "AMD"]
で作成されます。
次の週に6つの株を購入し、6つの株:["apple", "google", "tesla", "AMD", "intel", "qualcomm"]
でリストを作成します。
私がしたいのは、100%になるリストの各要素に動的にパーセンテージを割り当てます。
最初の1週間で、Appleには50%、Googleでは25%、テスラでは15%、AMDでは10%が割り当てられます。
2週間で、Appleには50%、Googleは25%、Teslaは16.5%、AMDは5%、Intelは2.5%、Qualcommは1%の割り当てが可能です。
最後の結果では、アルゴリズムに数値のリストを与え、各要素に高いと低いが100%に等しい百分率を割り当てたいとします。
ここで私に私の現在のコード:
from quantopian.pipeline.factors import VWAP
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import AverageDollarVolume
from quantopian.pipeline.filters.morningstar import Q1500US
import numpy as np
import pandas as pd
import math
def initialize(context):
"""
Called once at the start of the algorithm.
"""
# Sets default slippage and commission fees to simulate real trading.
set_commission(commission.PerShare(cost=0.0075, min_trade_cost=1.00))
set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.1))
set_asset_restrictions(security_lists.restrict_leveraged_etfs)
# Creates a function that runs at the beginning of each week.
schedule_function(start_of_week, date_rules.week_start(), time_rules.market_open(hours=1))
# Rebalance every day, 1 hour after market open.
schedule_function(my_rebalance, date_rules.week_end(), time_rules.market_open(hours=1))
# Record tracking variables at the end of each day.
schedule_function(my_record_vars, date_rules.every_day(), time_rules.market_close())
#Creates a function that runs at the beginning of everyday.
schedule_function(start_of_day, date_rules.every_day(), time_rules.market_open(hours=1.5))
# Create our dynamic stock selector.
pipe = Pipeline()
attach_pipeline(pipe, name='my_pipeline')
# Construct Volume Factor.
vwap = VWAP(inputs=[USEquityPricing.close, USEquityPricing.volume], window_length=14)
prices_under_5 = (vwap < 5)
pipe.set_screen(prices_under_5)
context.df_long = pd.DataFrame(None, columns=list("ABC"))
context.df_short = pd.DataFrame(None, columns=list("ABC"))
context.long_list = []
context.short_list = []
def start_of_week(context, data):
"""
Called at the begining of every week before market open.
"""
context.df_long = pd.DataFrame(None, columns=list("AB"))
context.df_short = pd.DataFrame(None, columns=list("AB"))
context.long_list = []
context.short_list = []
context.output = pipeline_output('my_pipeline')
# These are the securities that we are interested in trading each day.
context.security_list = context.output.sort_index(axis=0, ascending=True, kind='quicksort')
context.security_list = context.security_list.index
for security in context.security_list:
# Gets Simple Moving Average for 7 days and 100 days
price_hist_8 = data.history(security, 'price', 7, '1d')
mavg8 = price_hist_8.mean()
price_hist_14 = data.history(security, 'price', 100, '1d')
mavg14 = price_hist_14.mean()
current_vol = data.current(securrity, "volume")
if mavg8 > mavg14:
#Calculate percent increase of volume
current_vol = data.current(security, "volume")
hist_vol = data.history(security, "volume", 10, "1d")
difference_increase_vol = current_vol - hist_vol
percent_increase_vol = (difference_increase_vol/hist_vol) * 100
percent_increase_vol = percent_increase_vol[0]
if perecent_increase_vol >= 0:
context.df_long_tbd = pd.DataFrame([[security, mavg8]], columns=list("AB"))
frames = [context.df_long, context.df_long_tbd]
context.df_long = pd.concat(frames)
# Sorts all of the stocks in the "long" Data Frame from steepest incline in simple moving average over 8 days. The "final_long_list" contains all of the top stocks' names.
result_long = context.df_long.sort_values(by=["B", "A"], ascending=False)
context.long_final_list = result_long["A"]
# Total amout of stocks that the algorithim is allowed to buy will be determined on total portfolial value.
# If the total portfolial value is $100,000, the algorithim is only allowed to look at
port_val = context.portfolio.portfolio_value
allowed_to_purchase = round(sqrt(port_val)/10)
for stock in context.long_final_list[:allowed_to_purchase]:
if data.can_trade(stock):
はさんは「allowed_to_purchaseは」今10に等しいとしましょう、私は高く開始と終了、私のcontext.long_final_listの上位10パーセントで、各株式を割り当てます低い、100%に等しい。
シンプルな解決策や組み込み関数はありますか? "context.long_final_list"はパンダのデータフレームです。パンダが持つ機能はありますか?
ベター辞書 – bigbounty
の使用を作るには、あなたが辞書ではなく、リストをしたいよう... – alfasin
はパンダのデータフレームでそれを行うことができますね? –